sqlglot.generator API documentation

Edit on GitHub

# sqlglot.generator

View Source

       1from __future__ import annotations
       2
       3import logging
       4import re
       5import typing as t
       6from collections import defaultdict
       7from functools import reduce, wraps
       8
       9from sqlglot import exp
      10from sqlglot.errors import ErrorLevel, UnsupportedError, concat_messages
      11from sqlglot.helper import apply_index_offset, csv, name_sequence, seq_get
      12from sqlglot.jsonpath import ALL_JSON_PATH_PARTS, JSON_PATH_PART_TRANSFORMS
      13from sqlglot.time import format_time
      14from sqlglot.tokens import TokenType
      15
      16if t.TYPE_CHECKING:
      17    from sqlglot._typing import E
      18    from sqlglot.dialects.dialect import DialectType
      19
      20    G = t.TypeVar("G", bound="Generator")
      21    GeneratorMethod = t.Callable[[G, E], str]
      22
      23logger = logging.getLogger("sqlglot")
      24
      25ESCAPED_UNICODE_RE = re.compile(r"\\(\d+)")
      26UNSUPPORTED_TEMPLATE = "Argument '{}' is not supported for expression '{}' when targeting {}."
      27
      28
      29def unsupported_args(
      30    *args: t.Union[str, t.Tuple[str, str]],
      31) -> t.Callable[[GeneratorMethod], GeneratorMethod]:
      32    """
      33    Decorator that can be used to mark certain args of an `Expression` subclass as unsupported.
      34    It expects a sequence of argument names or pairs of the form (argument_name, diagnostic_msg).
      35    """
      36    diagnostic_by_arg: t.Dict[str, t.Optional[str]] = {}
      37    for arg in args:
      38        if isinstance(arg, str):
      39            diagnostic_by_arg[arg] = None
      40        else:
      41            diagnostic_by_arg[arg[0]] = arg[1]
      42
      43    def decorator(func: GeneratorMethod) -> GeneratorMethod:
      44        @wraps(func)
      45        def _func(generator: G, expression: E) -> str:
      46            expression_name = expression.__class__.__name__
      47            dialect_name = generator.dialect.__class__.__name__
      48
      49            for arg_name, diagnostic in diagnostic_by_arg.items():
      50                if expression.args.get(arg_name):
      51                    diagnostic = diagnostic or UNSUPPORTED_TEMPLATE.format(
      52                        arg_name, expression_name, dialect_name
      53                    )
      54                    generator.unsupported(diagnostic)
      55
      56            return func(generator, expression)
      57
      58        return _func
      59
      60    return decorator
      61
      62
      63class _Generator(type):
      64    def __new__(cls, clsname, bases, attrs):
      65        klass = super().__new__(cls, clsname, bases, attrs)
      66
      67        # Remove transforms that correspond to unsupported JSONPathPart expressions
      68        for part in ALL_JSON_PATH_PARTS - klass.SUPPORTED_JSON_PATH_PARTS:
      69            klass.TRANSFORMS.pop(part, None)
      70
      71        return klass
      72
      73
      74class Generator(metaclass=_Generator):
      75    """
      76    Generator converts a given syntax tree to the corresponding SQL string.
      77
      78    Args:
      79        pretty: Whether to format the produced SQL string.
      80            Default: False.
      81        identify: Determines when an identifier should be quoted. Possible values are:
      82            False (default): Never quote, except in cases where it's mandatory by the dialect.
      83            True or 'always': Always quote.
      84            'safe': Only quote identifiers that are case insensitive.
      85        normalize: Whether to normalize identifiers to lowercase.
      86            Default: False.
      87        pad: The pad size in a formatted string. For example, this affects the indentation of
      88            a projection in a query, relative to its nesting level.
      89            Default: 2.
      90        indent: The indentation size in a formatted string. For example, this affects the
      91            indentation of subqueries and filters under a `WHERE` clause.
      92            Default: 2.
      93        normalize_functions: How to normalize function names. Possible values are:
      94            "upper" or True (default): Convert names to uppercase.
      95            "lower": Convert names to lowercase.
      96            False: Disables function name normalization.
      97        unsupported_level: Determines the generator's behavior when it encounters unsupported expressions.
      98            Default ErrorLevel.WARN.
      99        max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError.
     100            This is only relevant if unsupported_level is ErrorLevel.RAISE.
     101            Default: 3
     102        leading_comma: Whether the comma is leading or trailing in select expressions.
     103            This is only relevant when generating in pretty mode.
     104            Default: False
     105        max_text_width: The max number of characters in a segment before creating new lines in pretty mode.
     106            The default is on the smaller end because the length only represents a segment and not the true
     107            line length.
     108            Default: 80
     109        comments: Whether to preserve comments in the output SQL code.
     110            Default: True
     111    """
     112
     113    TRANSFORMS: t.Dict[t.Type[exp.Expression], t.Callable[..., str]] = {
     114        **JSON_PATH_PART_TRANSFORMS,
     115        exp.AllowedValuesProperty: lambda self,
     116        e: f"ALLOWED_VALUES {self.expressions(e, flat=True)}",
     117        exp.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        cluster = self.sql(expression, "cluster")
    1318        cluster = f" {cluster}" if cluster else ""
    1319        where = self.sql(expression, "where")
    1320        returning = self.sql(expression, "returning")
    1321        limit = self.sql(expression, "limit")
    1322        tables = self.expressions(expression, key="tables")
    1323        tables = f" {tables}" if tables else ""
    1324        if self.RETURNING_END:
    1325            expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}"
    1326        else:
    1327            expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}"
    1328        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")
    1329
    1330    def drop_sql(self, expression: exp.Drop) -> str:
    1331        this = self.sql(expression, "this")
    1332        expressions = self.expressions(expression, flat=True)
    1333        expressions = f" ({expressions})" if expressions else ""
    1334        kind = expression.args["kind"]
    1335        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
    1336        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    1337        concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else ""
    1338        on_cluster = self.sql(expression, "cluster")
    1339        on_cluster = f" {on_cluster}" if on_cluster else ""
    1340        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1341        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    1342        cascade = " CASCADE" if expression.args.get("cascade") else ""
    1343        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    1344        purge = " PURGE" if expression.args.get("purge") else ""
    1345        return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}"
    1346
    1347    def set_operation(self, expression: exp.SetOperation) -> str:
    1348        op_type = type(expression)
    1349        op_name = op_type.key.upper()
    1350
    1351        distinct = expression.args.get("distinct")
    1352        if (
    1353            distinct is False
    1354            and op_type in (exp.Except, exp.Intersect)
    1355            and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
    1356        ):
    1357            self.unsupported(f"{op_name} ALL is not supported")
    1358
    1359        default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type]
    1360
    1361        if distinct is None:
    1362            distinct = default_distinct
    1363            if distinct is None:
    1364                self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified")
    1365
    1366        if distinct is default_distinct:
    1367            kind = ""
    1368        else:
    1369            kind = " DISTINCT" if distinct else " ALL"
    1370
    1371        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1372        return f"{op_name}{kind}{by_name}"
    1373
    1374    def set_operations(self, expression: exp.SetOperation) -> str:
    1375        if not self.SET_OP_MODIFIERS:
    1376            limit = expression.args.get("limit")
    1377            order = expression.args.get("order")
    1378
    1379            if limit or order:
    1380                select = exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
    1381
    1382                if limit:
    1383                    select = select.limit(limit.pop(), copy=False)
    1384                if order:
    1385                    select = select.order_by(order.pop(), copy=False)
    1386                return self.sql(select)
    1387
    1388        sqls: t.List[str] = []
    1389        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    1390
    1391        while stack:
    1392            node = stack.pop()
    1393
    1394            if isinstance(node, exp.SetOperation):
    1395                stack.append(node.expression)
    1396                stack.append(
    1397                    self.maybe_comment(
    1398                        self.set_operation(node), comments=node.comments, separated=True
    1399                    )
    1400                )
    1401                stack.append(node.this)
    1402            else:
    1403                sqls.append(self.sql(node))
    1404
    1405        this = self.sep().join(sqls)
    1406        this = self.query_modifiers(expression, this)
    1407        return self.prepend_ctes(expression, this)
    1408
    1409    def fetch_sql(self, expression: exp.Fetch) -> str:
    1410        direction = expression.args.get("direction")
    1411        direction = f" {direction}" if direction else ""
    1412        count = self.sql(expression, "count")
    1413        count = f" {count}" if count else ""
    1414        if expression.args.get("percent"):
    1415            count = f"{count} PERCENT"
    1416        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    1417        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"
    1418
    1419    def filter_sql(self, expression: exp.Filter) -> str:
    1420        if self.AGGREGATE_FILTER_SUPPORTED:
    1421            this = self.sql(expression, "this")
    1422            where = self.sql(expression, "expression").strip()
    1423            return f"{this} FILTER({where})"
    1424
    1425        agg = expression.this
    1426        agg_arg = agg.this
    1427        cond = expression.expression.this
    1428        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1429        return self.sql(agg)
    1430
    1431    def hint_sql(self, expression: exp.Hint) -> str:
    1432        if not self.QUERY_HINTS:
    1433            self.unsupported("Hints are not supported")
    1434            return ""
    1435
    1436        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"
    1437
    1438    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
    1439        using = self.sql(expression, "using")
    1440        using = f" USING {using}" if using else ""
    1441        columns = self.expressions(expression, key="columns", flat=True)
    1442        columns = f"({columns})" if columns else ""
    1443        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1444        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1445        where = self.sql(expression, "where")
    1446        include = self.expressions(expression, key="include", flat=True)
    1447        if include:
    1448            include = f" INCLUDE ({include})"
    1449        with_storage = self.expressions(expression, key="with_storage", flat=True)
    1450        with_storage = f" WITH ({with_storage})" if with_storage else ""
    1451        tablespace = self.sql(expression, "tablespace")
    1452        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
    1453        on = self.sql(expression, "on")
    1454        on = f" ON {on}" if on else ""
    1455
    1456        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"
    1457
    1458    def index_sql(self, expression: exp.Index) -> str:
    1459        unique = "UNIQUE " if expression.args.get("unique") else ""
    1460        primary = "PRIMARY " if expression.args.get("primary") else ""
    1461        amp = "AMP " if expression.args.get("amp") else ""
    1462        name = self.sql(expression, "this")
    1463        name = f"{name} " if name else ""
    1464        table = self.sql(expression, "table")
    1465        table = f"{self.INDEX_ON} {table}" if table else ""
    1466
    1467        index = "INDEX " if not table else ""
    1468
    1469        params = self.sql(expression, "params")
    1470        return f"{unique}{primary}{amp}{index}{name}{table}{params}"
    1471
    1472    def identifier_sql(self, expression: exp.Identifier) -> str:
    1473        text = expression.name
    1474        lower = text.lower()
    1475        text = lower if self.normalize and not expression.quoted else text
    1476        text = text.replace(self._identifier_end, self._escaped_identifier_end)
    1477        if (
    1478            expression.quoted
    1479            or self.dialect.can_identify(text, self.identify)
    1480            or lower in self.RESERVED_KEYWORDS
    1481            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1482        ):
    1483            text = f"{self._identifier_start}{text}{self._identifier_end}"
    1484        return text
    1485
    1486    def hex_sql(self, expression: exp.Hex) -> str:
    1487        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1488        if self.dialect.HEX_LOWERCASE:
    1489            text = self.func("LOWER", text)
    1490
    1491        return text
    1492
    1493    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
    1494        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1495        if not self.dialect.HEX_LOWERCASE:
    1496            text = self.func("LOWER", text)
    1497        return text
    1498
    1499    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1500        input_format = self.sql(expression, "input_format")
    1501        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1502        output_format = self.sql(expression, "output_format")
    1503        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1504        return self.sep().join((input_format, output_format))
    1505
    1506    def national_sql(self, expression: exp.National, prefix: str = "N") -> str:
    1507        string = self.sql(exp.Literal.string(expression.name))
    1508        return f"{prefix}{string}"
    1509
    1510    def partition_sql(self, expression: exp.Partition) -> str:
    1511        return f"PARTITION({self.expressions(expression, flat=True)})"
    1512
    1513    def properties_sql(self, expression: exp.Properties) -> str:
    1514        root_properties = []
    1515        with_properties = []
    1516
    1517        for p in expression.expressions:
    1518            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1519            if p_loc == exp.Properties.Location.POST_WITH:
    1520                with_properties.append(p)
    1521            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1522                root_properties.append(p)
    1523
    1524        root_props = self.root_properties(exp.Properties(expressions=root_properties))
    1525        with_props = self.with_properties(exp.Properties(expressions=with_properties))
    1526
    1527        if root_props and with_props and not self.pretty:
    1528            with_props = " " + with_props
    1529
    1530        return root_props + with_props
    1531
    1532    def root_properties(self, properties: exp.Properties) -> str:
    1533        if properties.expressions:
    1534            return self.expressions(properties, indent=False, sep=" ")
    1535        return ""
    1536
    1537    def properties(
    1538        self,
    1539        properties: exp.Properties,
    1540        prefix: str = "",
    1541        sep: str = ", ",
    1542        suffix: str = "",
    1543        wrapped: bool = True,
    1544    ) -> str:
    1545        if properties.expressions:
    1546            expressions = self.expressions(properties, sep=sep, indent=False)
    1547            if expressions:
    1548                expressions = self.wrap(expressions) if wrapped else expressions
    1549                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1550        return ""
    1551
    1552    def with_properties(self, properties: exp.Properties) -> str:
    1553        return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep=""))
    1554
    1555    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1556        properties_locs = defaultdict(list)
    1557        for p in properties.expressions:
    1558            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1559            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1560                properties_locs[p_loc].append(p)
    1561            else:
    1562                self.unsupported(f"Unsupported property {p.key}")
    1563
    1564        return properties_locs
    1565
    1566    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1567        if isinstance(expression.this, exp.Dot):
    1568            return self.sql(expression, "this")
    1569        return f"'{expression.name}'" if string_key else expression.name
    1570
    1571    def property_sql(self, expression: exp.Property) -> str:
    1572        property_cls = expression.__class__
    1573        if property_cls == exp.Property:
    1574            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1575
    1576        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1577        if not property_name:
    1578            self.unsupported(f"Unsupported property {expression.key}")
    1579
    1580        return f"{property_name}={self.sql(expression, 'this')}"
    1581
    1582    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1583        if self.SUPPORTS_CREATE_TABLE_LIKE:
    1584            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1585            options = f" {options}" if options else ""
    1586
    1587            like = f"LIKE {self.sql(expression, 'this')}{options}"
    1588            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
    1589                like = f"({like})"
    1590
    1591            return like
    1592
    1593        if expression.expressions:
    1594            self.unsupported("Transpilation of LIKE property options is unsupported")
    1595
    1596        select = exp.select("*").from_(expression.this).limit(0)
    1597        return f"AS {self.sql(select)}"
    1598
    1599    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1600        no = "NO " if expression.args.get("no") else ""
    1601        protection = " PROTECTION" if expression.args.get("protection") else ""
    1602        return f"{no}FALLBACK{protection}"
    1603
    1604    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1605        no = "NO " if expression.args.get("no") else ""
    1606        local = expression.args.get("local")
    1607        local = f"{local} " if local else ""
    1608        dual = "DUAL " if expression.args.get("dual") else ""
    1609        before = "BEFORE " if expression.args.get("before") else ""
    1610        after = "AFTER " if expression.args.get("after") else ""
    1611        return f"{no}{local}{dual}{before}{after}JOURNAL"
    1612
    1613    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1614        freespace = self.sql(expression, "this")
    1615        percent = " PERCENT" if expression.args.get("percent") else ""
    1616        return f"FREESPACE={freespace}{percent}"
    1617
    1618    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1619        if expression.args.get("default"):
    1620            property = "DEFAULT"
    1621        elif expression.args.get("on"):
    1622            property = "ON"
    1623        else:
    1624            property = "OFF"
    1625        return f"CHECKSUM={property}"
    1626
    1627    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1628        if expression.args.get("no"):
    1629            return "NO MERGEBLOCKRATIO"
    1630        if expression.args.get("default"):
    1631            return "DEFAULT MERGEBLOCKRATIO"
    1632
    1633        percent = " PERCENT" if expression.args.get("percent") else ""
    1634        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
    1635
    1636    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1637        default = expression.args.get("default")
    1638        minimum = expression.args.get("minimum")
    1639        maximum = expression.args.get("maximum")
    1640        if default or minimum or maximum:
    1641            if default:
    1642                prop = "DEFAULT"
    1643            elif minimum:
    1644                prop = "MINIMUM"
    1645            else:
    1646                prop = "MAXIMUM"
    1647            return f"{prop} DATABLOCKSIZE"
    1648        units = expression.args.get("units")
    1649        units = f" {units}" if units else ""
    1650        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
    1651
    1652    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1653        autotemp = expression.args.get("autotemp")
    1654        always = expression.args.get("always")
    1655        default = expression.args.get("default")
    1656        manual = expression.args.get("manual")
    1657        never = expression.args.get("never")
    1658
    1659        if autotemp is not None:
    1660            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1661        elif always:
    1662            prop = "ALWAYS"
    1663        elif default:
    1664            prop = "DEFAULT"
    1665        elif manual:
    1666            prop = "MANUAL"
    1667        elif never:
    1668            prop = "NEVER"
    1669        return f"BLOCKCOMPRESSION={prop}"
    1670
    1671    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1672        no = expression.args.get("no")
    1673        no = " NO" if no else ""
    1674        concurrent = expression.args.get("concurrent")
    1675        concurrent = " CONCURRENT" if concurrent else ""
    1676        target = self.sql(expression, "target")
    1677        target = f" {target}" if target else ""
    1678        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"
    1679
    1680    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1681        if isinstance(expression.this, list):
    1682            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1683        if expression.this:
    1684            modulus = self.sql(expression, "this")
    1685            remainder = self.sql(expression, "expression")
    1686            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1687
    1688        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1689        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1690        return f"FROM ({from_expressions}) TO ({to_expressions})"
    1691
    1692    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1693        this = self.sql(expression, "this")
    1694
    1695        for_values_or_default = expression.expression
    1696        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1697            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1698        else:
    1699            for_values_or_default = " DEFAULT"
    1700
    1701        return f"PARTITION OF {this}{for_values_or_default}"
    1702
    1703    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1704        kind = expression.args.get("kind")
    1705        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1706        for_or_in = expression.args.get("for_or_in")
    1707        for_or_in = f" {for_or_in}" if for_or_in else ""
    1708        lock_type = expression.args.get("lock_type")
    1709        override = " OVERRIDE" if expression.args.get("override") else ""
    1710        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"
    1711
    1712    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1713        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1714        statistics = expression.args.get("statistics")
    1715        statistics_sql = ""
    1716        if statistics is not None:
    1717            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1718        return f"{data_sql}{statistics_sql}"
    1719
    1720    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1721        this = self.sql(expression, "this")
    1722        this = f"HISTORY_TABLE={this}" if this else ""
    1723        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
    1724        data_consistency = (
    1725            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
    1726        )
    1727        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    1728        retention_period = (
    1729            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
    1730        )
    1731
    1732        if this:
    1733            on_sql = self.func("ON", this, data_consistency, retention_period)
    1734        else:
    1735            on_sql = "ON" if expression.args.get("on") else "OFF"
    1736
    1737        sql = f"SYSTEM_VERSIONING={on_sql}"
    1738
    1739        return f"WITH({sql})" if expression.args.get("with") else sql
    1740
    1741    def insert_sql(self, expression: exp.Insert) -> str:
    1742        hint = self.sql(expression, "hint")
    1743        overwrite = expression.args.get("overwrite")
    1744
    1745        if isinstance(expression.this, exp.Directory):
    1746            this = " OVERWRITE" if overwrite else " INTO"
    1747        else:
    1748            this = self.INSERT_OVERWRITE if overwrite else " INTO"
    1749
    1750        stored = self.sql(expression, "stored")
    1751        stored = f" {stored}" if stored else ""
    1752        alternative = expression.args.get("alternative")
    1753        alternative = f" OR {alternative}" if alternative else ""
    1754        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1755        is_function = expression.args.get("is_function")
    1756        if is_function:
    1757            this = f"{this} FUNCTION"
    1758        this = f"{this} {self.sql(expression, 'this')}"
    1759
    1760        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1761        where = self.sql(expression, "where")
    1762        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1763        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1764        on_conflict = self.sql(expression, "conflict")
    1765        on_conflict = f" {on_conflict}" if on_conflict else ""
    1766        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1767        returning = self.sql(expression, "returning")
    1768
    1769        if self.RETURNING_END:
    1770            expression_sql = f"{expression_sql}{on_conflict}{returning}"
    1771        else:
    1772            expression_sql = f"{returning}{expression_sql}{on_conflict}"
    1773
    1774        partition_by = self.sql(expression, "partition")
    1775        partition_by = f" {partition_by}" if partition_by else ""
    1776        settings = self.sql(expression, "settings")
    1777        settings = f" {settings}" if settings else ""
    1778
    1779        source = self.sql(expression, "source")
    1780        source = f"TABLE {source}" if source else ""
    1781
    1782        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}"
    1783        return self.prepend_ctes(expression, sql)
    1784
    1785    def introducer_sql(self, expression: exp.Introducer) -> str:
    1786        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
    1787
    1788    def kill_sql(self, expression: exp.Kill) -> str:
    1789        kind = self.sql(expression, "kind")
    1790        kind = f" {kind}" if kind else ""
    1791        this = self.sql(expression, "this")
    1792        this = f" {this}" if this else ""
    1793        return f"KILL{kind}{this}"
    1794
    1795    def pseudotype_sql(self, expression: exp.PseudoType) -> str:
    1796        return expression.name
    1797
    1798    def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str:
    1799        return expression.name
    1800
    1801    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1802        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1803
    1804        constraint = self.sql(expression, "constraint")
    1805        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
    1806
    1807        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
    1808        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
    1809        action = self.sql(expression, "action")
    1810
    1811        expressions = self.expressions(expression, flat=True)
    1812        if expressions:
    1813            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1814            expressions = f" {set_keyword}{expressions}"
    1815
    1816        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}"
    1817
    1818    def returning_sql(self, expression: exp.Returning) -> str:
    1819        return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}"
    1820
    1821    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1822        fields = self.sql(expression, "fields")
    1823        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1824        escaped = self.sql(expression, "escaped")
    1825        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1826        items = self.sql(expression, "collection_items")
    1827        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1828        keys = self.sql(expression, "map_keys")
    1829        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1830        lines = self.sql(expression, "lines")
    1831        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1832        null = self.sql(expression, "null")
    1833        null = f" NULL DEFINED AS {null}" if null else ""
    1834        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
    1835
    1836    def withtablehint_sql(self, expression: exp.WithTableHint) -> str:
    1837        return f"WITH ({self.expressions(expression, flat=True)})"
    1838
    1839    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1840        this = f"{self.sql(expression, 'this')} INDEX"
    1841        target = self.sql(expression, "target")
    1842        target = f" FOR {target}" if target else ""
    1843        return f"{this}{target} ({self.expressions(expression, flat=True)})"
    1844
    1845    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1846        this = self.sql(expression, "this")
    1847        kind = self.sql(expression, "kind")
    1848        expr = self.sql(expression, "expression")
    1849        return f"{this} ({kind} => {expr})"
    1850
    1851    def table_parts(self, expression: exp.Table) -> str:
    1852        return ".".join(
    1853            self.sql(part)
    1854            for part in (
    1855                expression.args.get("catalog"),
    1856                expression.args.get("db"),
    1857                expression.args.get("this"),
    1858            )
    1859            if part is not None
    1860        )
    1861
    1862    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1863        table = self.table_parts(expression)
    1864        only = "ONLY " if expression.args.get("only") else ""
    1865        partition = self.sql(expression, "partition")
    1866        partition = f" {partition}" if partition else ""
    1867        version = self.sql(expression, "version")
    1868        version = f" {version}" if version else ""
    1869        alias = self.sql(expression, "alias")
    1870        alias = f"{sep}{alias}" if alias else ""
    1871
    1872        sample = self.sql(expression, "sample")
    1873        if self.dialect.ALIAS_POST_TABLESAMPLE:
    1874            sample_pre_alias = sample
    1875            sample_post_alias = ""
    1876        else:
    1877            sample_pre_alias = ""
    1878            sample_post_alias = sample
    1879
    1880        hints = self.expressions(expression, key="hints", sep=" ")
    1881        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1882        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    1883        joins = self.indent(
    1884            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    1885        )
    1886        laterals = self.expressions(expression, key="laterals", sep="")
    1887
    1888        file_format = self.sql(expression, "format")
    1889        if file_format:
    1890            pattern = self.sql(expression, "pattern")
    1891            pattern = f", PATTERN => {pattern}" if pattern else ""
    1892            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    1893
    1894        ordinality = expression.args.get("ordinality") or ""
    1895        if ordinality:
    1896            ordinality = f" WITH ORDINALITY{alias}"
    1897            alias = ""
    1898
    1899        when = self.sql(expression, "when")
    1900        if when:
    1901            table = f"{table} {when}"
    1902
    1903        changes = self.sql(expression, "changes")
    1904        changes = f" {changes}" if changes else ""
    1905
    1906        rows_from = self.expressions(expression, key="rows_from")
    1907        if rows_from:
    1908            table = f"ROWS FROM {self.wrap(rows_from)}"
    1909
    1910        return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}"
    1911
    1912    def tablesample_sql(
    1913        self,
    1914        expression: exp.TableSample,
    1915        tablesample_keyword: t.Optional[str] = None,
    1916    ) -> str:
    1917        method = self.sql(expression, "method")
    1918        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1919        numerator = self.sql(expression, "bucket_numerator")
    1920        denominator = self.sql(expression, "bucket_denominator")
    1921        field = self.sql(expression, "bucket_field")
    1922        field = f" ON {field}" if field else ""
    1923        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1924        seed = self.sql(expression, "seed")
    1925        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
    1926
    1927        size = self.sql(expression, "size")
    1928        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
    1929            size = f"{size} ROWS"
    1930
    1931        percent = self.sql(expression, "percent")
    1932        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
    1933            percent = f"{percent} PERCENT"
    1934
    1935        expr = f"{bucket}{percent}{size}"
    1936        if self.TABLESAMPLE_REQUIRES_PARENS:
    1937            expr = f"({expr})"
    1938
    1939        return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"
    1940
    1941    def pivot_sql(self, expression: exp.Pivot) -> str:
    1942        expressions = self.expressions(expression, flat=True)
    1943
    1944        if expression.this:
    1945            this = self.sql(expression, "this")
    1946            if not expressions:
    1947                return f"UNPIVOT {this}"
    1948
    1949            on = f"{self.seg('ON')} {expressions}"
    1950            using = self.expressions(expression, key="using", flat=True)
    1951            using = f"{self.seg('USING')} {using}" if using else ""
    1952            group = self.sql(expression, "group")
    1953            return f"PIVOT {this}{on}{using}{group}"
    1954
    1955        alias = self.sql(expression, "alias")
    1956        alias = f" AS {alias}" if alias else ""
    1957        direction = self.seg("UNPIVOT" if expression.unpivot else "PIVOT")
    1958
    1959        field = self.sql(expression, "field")
    1960
    1961        include_nulls = expression.args.get("include_nulls")
    1962        if include_nulls is not None:
    1963            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    1964        else:
    1965            nulls = ""
    1966
    1967        default_on_null = self.sql(expression, "default_on_null")
    1968        default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else ""
    1969        return f"{direction}{nulls}({expressions} FOR {field}{default_on_null}){alias}"
    1970
    1971    def version_sql(self, expression: exp.Version) -> str:
    1972        this = f"FOR {expression.name}"
    1973        kind = expression.text("kind")
    1974        expr = self.sql(expression, "expression")
    1975        return f"{this} {kind} {expr}"
    1976
    1977    def tuple_sql(self, expression: exp.Tuple) -> str:
    1978        return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"
    1979
    1980    def update_sql(self, expression: exp.Update) -> str:
    1981        this = self.sql(expression, "this")
    1982        set_sql = self.expressions(expression, flat=True)
    1983        from_sql = self.sql(expression, "from")
    1984        where_sql = self.sql(expression, "where")
    1985        returning = self.sql(expression, "returning")
    1986        order = self.sql(expression, "order")
    1987        limit = self.sql(expression, "limit")
    1988        if self.RETURNING_END:
    1989            expression_sql = f"{from_sql}{where_sql}{returning}"
    1990        else:
    1991            expression_sql = f"{returning}{from_sql}{where_sql}"
    1992        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    1993        return self.prepend_ctes(expression, sql)
    1994
    1995    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
    1996        values_as_table = values_as_table and self.VALUES_AS_TABLE
    1997
    1998        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    1999        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
    2000            args = self.expressions(expression)
    2001            alias = self.sql(expression, "alias")
    2002            values = f"VALUES{self.seg('')}{args}"
    2003            values = (
    2004                f"({values})"
    2005                if self.WRAP_DERIVED_VALUES
    2006                and (alias or isinstance(expression.parent, (exp.From, exp.Table)))
    2007                else values
    2008            )
    2009            return f"{values} AS {alias}" if alias else values
    2010
    2011        # Converts `VALUES...` expression into a series of select unions.
    2012        alias_node = expression.args.get("alias")
    2013        column_names = alias_node and alias_node.columns
    2014
    2015        selects: t.List[exp.Query] = []
    2016
    2017        for i, tup in enumerate(expression.expressions):
    2018            row = tup.expressions
    2019
    2020            if i == 0 and column_names:
    2021                row = [
    2022                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    2023                ]
    2024
    2025            selects.append(exp.Select(expressions=row))
    2026
    2027        if self.pretty:
    2028            # This may result in poor performance for large-cardinality `VALUES` tables, due to
    2029            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
    2030            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
    2031            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
    2032            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
    2033
    2034        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
    2035        unions = " UNION ALL ".join(self.sql(select) for select in selects)
    2036        return f"({unions}){alias}"
    2037
    2038    def var_sql(self, expression: exp.Var) -> str:
    2039        return self.sql(expression, "this")
    2040
    2041    def into_sql(self, expression: exp.Into) -> str:
    2042        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    2043        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
    2044        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
    2045
    2046    def from_sql(self, expression: exp.From) -> str:
    2047        return f"{self.seg('FROM')} {self.sql(expression, 'this')}"
    2048
    2049    def groupingsets_sql(self, expression: exp.GroupingSets) -> str:
    2050        grouping_sets = self.expressions(expression, indent=False)
    2051        return f"GROUPING SETS {self.wrap(grouping_sets)}"
    2052
    2053    def rollup_sql(self, expression: exp.Rollup) -> str:
    2054        expressions = self.expressions(expression, indent=False)
    2055        return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP"
    2056
    2057    def cube_sql(self, expression: exp.Cube) -> str:
    2058        expressions = self.expressions(expression, indent=False)
    2059        return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE"
    2060
    2061    def group_sql(self, expression: exp.Group) -> str:
    2062        group_by_all = expression.args.get("all")
    2063        if group_by_all is True:
    2064            modifier = " ALL"
    2065        elif group_by_all is False:
    2066            modifier = " DISTINCT"
    2067        else:
    2068            modifier = ""
    2069
    2070        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
    2071
    2072        grouping_sets = self.expressions(expression, key="grouping_sets")
    2073        cube = self.expressions(expression, key="cube")
    2074        rollup = self.expressions(expression, key="rollup")
    2075
    2076        groupings = csv(
    2077            self.seg(grouping_sets) if grouping_sets else "",
    2078            self.seg(cube) if cube else "",
    2079            self.seg(rollup) if rollup else "",
    2080            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    2081            sep=self.GROUPINGS_SEP,
    2082        )
    2083
    2084        if (
    2085            expression.expressions
    2086            and groupings
    2087            and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP")
    2088        ):
    2089            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    2090
    2091        return f"{group_by}{groupings}"
    2092
    2093    def having_sql(self, expression: exp.Having) -> str:
    2094        this = self.indent(self.sql(expression, "this"))
    2095        return f"{self.seg('HAVING')}{self.sep()}{this}"
    2096
    2097    def connect_sql(self, expression: exp.Connect) -> str:
    2098        start = self.sql(expression, "start")
    2099        start = self.seg(f"START WITH {start}") if start else ""
    2100        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
    2101        connect = self.sql(expression, "connect")
    2102        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
    2103        return start + connect
    2104
    2105    def prior_sql(self, expression: exp.Prior) -> str:
    2106        return f"PRIOR {self.sql(expression, 'this')}"
    2107
    2108    def join_sql(self, expression: exp.Join) -> str:
    2109        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    2110            side = None
    2111        else:
    2112            side = expression.side
    2113
    2114        op_sql = " ".join(
    2115            op
    2116            for op in (
    2117                expression.method,
    2118                "GLOBAL" if expression.args.get("global") else None,
    2119                side,
    2120                expression.kind,
    2121                expression.hint if self.JOIN_HINTS else None,
    2122            )
    2123            if op
    2124        )
    2125        match_cond = self.sql(expression, "match_condition")
    2126        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
    2127        on_sql = self.sql(expression, "on")
    2128        using = expression.args.get("using")
    2129
    2130        if not on_sql and using:
    2131            on_sql = csv(*(self.sql(column) for column in using))
    2132
    2133        this = expression.this
    2134        this_sql = self.sql(this)
    2135
    2136        if on_sql:
    2137            on_sql = self.indent(on_sql, skip_first=True)
    2138            space = self.seg(" " * self.pad) if self.pretty else " "
    2139            if using:
    2140                on_sql = f"{space}USING ({on_sql})"
    2141            else:
    2142                on_sql = f"{space}ON {on_sql}"
    2143        elif not op_sql:
    2144            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
    2145                return f" {this_sql}"
    2146
    2147            return f", {this_sql}"
    2148
    2149        if op_sql != "STRAIGHT_JOIN":
    2150            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    2151
    2152        return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}"
    2153
    2154    def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str:
    2155        args = self.expressions(expression, flat=True)
    2156        args = f"({args})" if len(args.split(",")) > 1 else args
    2157        return f"{args} {arrow_sep} {self.sql(expression, 'this')}"
    2158
    2159    def lateral_op(self, expression: exp.Lateral) -> str:
    2160        cross_apply = expression.args.get("cross_apply")
    2161
    2162        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    2163        if cross_apply is True:
    2164            op = "INNER JOIN "
    2165        elif cross_apply is False:
    2166            op = "LEFT JOIN "
    2167        else:
    2168            op = ""
    2169
    2170        return f"{op}LATERAL"
    2171
    2172    def lateral_sql(self, expression: exp.Lateral) -> str:
    2173        this = self.sql(expression, "this")
    2174
    2175        if expression.args.get("view"):
    2176            alias = expression.args["alias"]
    2177            columns = self.expressions(alias, key="columns", flat=True)
    2178            table = f" {alias.name}" if alias.name else ""
    2179            columns = f" AS {columns}" if columns else ""
    2180            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    2181            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    2182
    2183        alias = self.sql(expression, "alias")
    2184        alias = f" AS {alias}" if alias else ""
    2185        return f"{self.lateral_op(expression)} {this}{alias}"
    2186
    2187    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    2188        this = self.sql(expression, "this")
    2189
    2190        args = [
    2191            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    2192            for e in (expression.args.get(k) for k in ("offset", "expression"))
    2193            if e
    2194        ]
    2195
    2196        args_sql = ", ".join(self.sql(e) for e in args)
    2197        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
    2198        expressions = self.expressions(expression, flat=True)
    2199        expressions = f" BY {expressions}" if expressions else ""
    2200
    2201        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}"
    2202
    2203    def offset_sql(self, expression: exp.Offset) -> str:
    2204        this = self.sql(expression, "this")
    2205        value = expression.expression
    2206        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    2207        expressions = self.expressions(expression, flat=True)
    2208        expressions = f" BY {expressions}" if expressions else ""
    2209        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"
    2210
    2211    def setitem_sql(self, expression: exp.SetItem) -> str:
    2212        kind = self.sql(expression, "kind")
    2213        kind = f"{kind} " if kind else ""
    2214        this = self.sql(expression, "this")
    2215        expressions = self.expressions(expression)
    2216        collate = self.sql(expression, "collate")
    2217        collate = f" COLLATE {collate}" if collate else ""
    2218        global_ = "GLOBAL " if expression.args.get("global") else ""
    2219        return f"{global_}{kind}{this}{expressions}{collate}"
    2220
    2221    def set_sql(self, expression: exp.Set) -> str:
    2222        expressions = (
    2223            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    2224        )
    2225        tag = " TAG" if expression.args.get("tag") else ""
    2226        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"
    2227
    2228    def pragma_sql(self, expression: exp.Pragma) -> str:
    2229        return f"PRAGMA {self.sql(expression, 'this')}"
    2230
    2231    def lock_sql(self, expression: exp.Lock) -> str:
    2232        if not self.LOCKING_READS_SUPPORTED:
    2233            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    2234            return ""
    2235
    2236        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    2237        expressions = self.expressions(expression, flat=True)
    2238        expressions = f" OF {expressions}" if expressions else ""
    2239        wait = expression.args.get("wait")
    2240
    2241        if wait is not None:
    2242            if isinstance(wait, exp.Literal):
    2243                wait = f" WAIT {self.sql(wait)}"
    2244            else:
    2245                wait = " NOWAIT" if wait else " SKIP LOCKED"
    2246
    2247        return f"{lock_type}{expressions}{wait or ''}"
    2248
    2249    def literal_sql(self, expression: exp.Literal) -> str:
    2250        text = expression.this or ""
    2251        if expression.is_string:
    2252            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    2253        return text
    2254
    2255    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
    2256        if self.dialect.ESCAPED_SEQUENCES:
    2257            to_escaped = self.dialect.ESCAPED_SEQUENCES
    2258            text = "".join(
    2259                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
    2260            )
    2261
    2262        return self._replace_line_breaks(text).replace(
    2263            self.dialect.QUOTE_END, self._escaped_quote_end
    2264        )
    2265
    2266    def loaddata_sql(self, expression: exp.LoadData) -> str:
    2267        local = " LOCAL" if expression.args.get("local") else ""
    2268        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    2269        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    2270        this = f" INTO TABLE {self.sql(expression, 'this')}"
    2271        partition = self.sql(expression, "partition")
    2272        partition = f" {partition}" if partition else ""
    2273        input_format = self.sql(expression, "input_format")
    2274        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    2275        serde = self.sql(expression, "serde")
    2276        serde = f" SERDE {serde}" if serde else ""
    2277        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
    2278
    2279    def null_sql(self, *_) -> str:
    2280        return "NULL"
    2281
    2282    def boolean_sql(self, expression: exp.Boolean) -> str:
    2283        return "TRUE" if expression.this else "FALSE"
    2284
    2285    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2286        this = self.sql(expression, "this")
    2287        this = f"{this} " if this else this
    2288        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2289        return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat)  # type: ignore
    2290
    2291    def withfill_sql(self, expression: exp.WithFill) -> str:
    2292        from_sql = self.sql(expression, "from")
    2293        from_sql = f" FROM {from_sql}" if from_sql else ""
    2294        to_sql = self.sql(expression, "to")
    2295        to_sql = f" TO {to_sql}" if to_sql else ""
    2296        step_sql = self.sql(expression, "step")
    2297        step_sql = f" STEP {step_sql}" if step_sql else ""
    2298        interpolated_values = [
    2299            f"{self.sql(named_expression, 'alias')} AS {self.sql(named_expression, 'this')}"
    2300            for named_expression in expression.args.get("interpolate") or []
    2301        ]
    2302        interpolate = (
    2303            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    2304        )
    2305        return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"
    2306
    2307    def cluster_sql(self, expression: exp.Cluster) -> str:
    2308        return self.op_expressions("CLUSTER BY", expression)
    2309
    2310    def distribute_sql(self, expression: exp.Distribute) -> str:
    2311        return self.op_expressions("DISTRIBUTE BY", expression)
    2312
    2313    def sort_sql(self, expression: exp.Sort) -> str:
    2314        return self.op_expressions("SORT BY", expression)
    2315
    2316    def ordered_sql(self, expression: exp.Ordered) -> str:
    2317        desc = expression.args.get("desc")
    2318        asc = not desc
    2319
    2320        nulls_first = expression.args.get("nulls_first")
    2321        nulls_last = not nulls_first
    2322        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
    2323        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
    2324        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
    2325
    2326        this = self.sql(expression, "this")
    2327
    2328        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
    2329        nulls_sort_change = ""
    2330        if nulls_first and (
    2331            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    2332        ):
    2333            nulls_sort_change = " NULLS FIRST"
    2334        elif (
    2335            nulls_last
    2336            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    2337            and not nulls_are_last
    2338        ):
    2339            nulls_sort_change = " NULLS LAST"
    2340
    2341        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
    2342        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    2343            window = expression.find_ancestor(exp.Window, exp.Select)
    2344            if isinstance(window, exp.Window) and window.args.get("spec"):
    2345                self.unsupported(
    2346                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
    2347                )
    2348                nulls_sort_change = ""
    2349            elif self.NULL_ORDERING_SUPPORTED is None:
    2350                if expression.this.is_int:
    2351                    self.unsupported(
    2352                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
    2353                    )
    2354                elif not isinstance(expression.this, exp.Rand):
    2355                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
    2356                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
    2357                nulls_sort_change = ""
    2358
    2359        with_fill = self.sql(expression, "with_fill")
    2360        with_fill = f" {with_fill}" if with_fill else ""
    2361
    2362        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"
    2363
    2364    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
    2365        window_frame = self.sql(expression, "window_frame")
    2366        window_frame = f"{window_frame} " if window_frame else ""
    2367
    2368        this = self.sql(expression, "this")
    2369
    2370        return f"{window_frame}{this}"
    2371
    2372    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    2373        partition = self.partition_by_sql(expression)
    2374        order = self.sql(expression, "order")
    2375        measures = self.expressions(expression, key="measures")
    2376        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    2377        rows = self.sql(expression, "rows")
    2378        rows = self.seg(rows) if rows else ""
    2379        after = self.sql(expression, "after")
    2380        after = self.seg(after) if after else ""
    2381        pattern = self.sql(expression, "pattern")
    2382        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    2383        definition_sqls = [
    2384            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    2385            for definition in expression.args.get("define", [])
    2386        ]
    2387        definitions = self.expressions(sqls=definition_sqls)
    2388        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    2389        body = "".join(
    2390            (
    2391                partition,
    2392                order,
    2393                measures,
    2394                rows,
    2395                after,
    2396                pattern,
    2397                define,
    2398            )
    2399        )
    2400        alias = self.sql(expression, "alias")
    2401        alias = f" {alias}" if alias else ""
    2402        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
    2403
    2404    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    2405        limit = expression.args.get("limit")
    2406
    2407        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    2408            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    2409        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    2410            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    2411
    2412        return csv(
    2413            *sqls,
    2414            *[self.sql(join) for join in expression.args.get("joins") or []],
    2415            self.sql(expression, "connect"),
    2416            self.sql(expression, "match"),
    2417            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2418            self.sql(expression, "prewhere"),
    2419            self.sql(expression, "where"),
    2420            self.sql(expression, "group"),
    2421            self.sql(expression, "having"),
    2422            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
    2423            self.sql(expression, "order"),
    2424            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
    2425            *self.after_limit_modifiers(expression),
    2426            self.options_modifier(expression),
    2427            sep="",
    2428        )
    2429
    2430    def options_modifier(self, expression: exp.Expression) -> str:
    2431        options = self.expressions(expression, key="options")
    2432        return f" {options}" if options else ""
    2433
    2434    def queryoption_sql(self, expression: exp.QueryOption) -> str:
    2435        return ""
    2436
    2437    def offset_limit_modifiers(
    2438        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2439    ) -> t.List[str]:
    2440        return [
    2441            self.sql(expression, "offset") if fetch else self.sql(limit),
    2442            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2443        ]
    2444
    2445    def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
    2446        locks = self.expressions(expression, key="locks", sep=" ")
    2447        locks = f" {locks}" if locks else ""
    2448        return [locks, self.sql(expression, "sample")]
    2449
    2450    def select_sql(self, expression: exp.Select) -> str:
    2451        into = expression.args.get("into")
    2452        if not self.SUPPORTS_SELECT_INTO and into:
    2453            into.pop()
    2454
    2455        hint = self.sql(expression, "hint")
    2456        distinct = self.sql(expression, "distinct")
    2457        distinct = f" {distinct}" if distinct else ""
    2458        kind = self.sql(expression, "kind")
    2459
    2460        limit = expression.args.get("limit")
    2461        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
    2462            top = self.limit_sql(limit, top=True)
    2463            limit.pop()
    2464        else:
    2465            top = ""
    2466
    2467        expressions = self.expressions(expression)
    2468
    2469        if kind:
    2470            if kind in self.SELECT_KINDS:
    2471                kind = f" AS {kind}"
    2472            else:
    2473                if kind == "STRUCT":
    2474                    expressions = self.expressions(
    2475                        sqls=[
    2476                            self.sql(
    2477                                exp.Struct(
    2478                                    expressions=[
    2479                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
    2480                                        if isinstance(e, exp.Alias)
    2481                                        else e
    2482                                        for e in expression.expressions
    2483                                    ]
    2484                                )
    2485                            )
    2486                        ]
    2487                    )
    2488                kind = ""
    2489
    2490        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
    2491        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
    2492        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
    2493        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    2494        sql = self.query_modifiers(
    2495            expression,
    2496            f"SELECT{top_distinct}{kind}{expressions}",
    2497            self.sql(expression, "into", comment=False),
    2498            self.sql(expression, "from", comment=False),
    2499        )
    2500
    2501        sql = self.prepend_ctes(expression, sql)
    2502
    2503        if not self.SUPPORTS_SELECT_INTO and into:
    2504            if into.args.get("temporary"):
    2505                table_kind = " TEMPORARY"
    2506            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
    2507                table_kind = " UNLOGGED"
    2508            else:
    2509                table_kind = ""
    2510            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
    2511
    2512        return sql
    2513
    2514    def schema_sql(self, expression: exp.Schema) -> str:
    2515        this = self.sql(expression, "this")
    2516        sql = self.schema_columns_sql(expression)
    2517        return f"{this} {sql}" if this and sql else this or sql
    2518
    2519    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2520        if expression.expressions:
    2521            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2522        return ""
    2523
    2524    def star_sql(self, expression: exp.Star) -> str:
    2525        except_ = self.expressions(expression, key="except", flat=True)
    2526        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
    2527        replace = self.expressions(expression, key="replace", flat=True)
    2528        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
    2529        rename = self.expressions(expression, key="rename", flat=True)
    2530        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
    2531        return f"*{except_}{replace}{rename}"
    2532
    2533    def parameter_sql(self, expression: exp.Parameter) -> str:
    2534        this = self.sql(expression, "this")
    2535        return f"{self.PARAMETER_TOKEN}{this}"
    2536
    2537    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2538        this = self.sql(expression, "this")
    2539        kind = expression.text("kind")
    2540        if kind:
    2541            kind = f"{kind}."
    2542        return f"@@{kind}{this}"
    2543
    2544    def placeholder_sql(self, expression: exp.Placeholder) -> str:
    2545        return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?"
    2546
    2547    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2548        alias = self.sql(expression, "alias")
    2549        alias = f"{sep}{alias}" if alias else ""
    2550        sample = self.sql(expression, "sample")
    2551        if self.dialect.ALIAS_POST_TABLESAMPLE and sample:
    2552            alias = f"{sample}{alias}"
    2553
    2554            # Set to None so it's not generated again by self.query_modifiers()
    2555            expression.set("sample", None)
    2556
    2557        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2558        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2559        return self.prepend_ctes(expression, sql)
    2560
    2561    def qualify_sql(self, expression: exp.Qualify) -> str:
    2562        this = self.indent(self.sql(expression, "this"))
    2563        return f"{self.seg('QUALIFY')}{self.sep()}{this}"
    2564
    2565    def unnest_sql(self, expression: exp.Unnest) -> str:
    2566        args = self.expressions(expression, flat=True)
    2567
    2568        alias = expression.args.get("alias")
    2569        offset = expression.args.get("offset")
    2570
    2571        if self.UNNEST_WITH_ORDINALITY:
    2572            if alias and isinstance(offset, exp.Expression):
    2573                alias.append("columns", offset)
    2574
    2575        if alias and self.dialect.UNNEST_COLUMN_ONLY:
    2576            columns = alias.columns
    2577            alias = self.sql(columns[0]) if columns else ""
    2578        else:
    2579            alias = self.sql(alias)
    2580
    2581        alias = f" AS {alias}" if alias else alias
    2582        if self.UNNEST_WITH_ORDINALITY:
    2583            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2584        else:
    2585            if isinstance(offset, exp.Expression):
    2586                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2587            elif offset:
    2588                suffix = f"{alias} WITH OFFSET"
    2589            else:
    2590                suffix = alias
    2591
    2592        return f"UNNEST({args}){suffix}"
    2593
    2594    def prewhere_sql(self, expression: exp.PreWhere) -> str:
    2595        return ""
    2596
    2597    def where_sql(self, expression: exp.Where) -> str:
    2598        this = self.indent(self.sql(expression, "this"))
    2599        return f"{self.seg('WHERE')}{self.sep()}{this}"
    2600
    2601    def window_sql(self, expression: exp.Window) -> str:
    2602        this = self.sql(expression, "this")
    2603        partition = self.partition_by_sql(expression)
    2604        order = expression.args.get("order")
    2605        order = self.order_sql(order, flat=True) if order else ""
    2606        spec = self.sql(expression, "spec")
    2607        alias = self.sql(expression, "alias")
    2608        over = self.sql(expression, "over") or "OVER"
    2609
    2610        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2611
    2612        first = expression.args.get("first")
    2613        if first is None:
    2614            first = ""
    2615        else:
    2616            first = "FIRST" if first else "LAST"
    2617
    2618        if not partition and not order and not spec and alias:
    2619            return f"{this} {alias}"
    2620
    2621        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    2622        return f"{this} ({args})"
    2623
    2624    def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str:
    2625        partition = self.expressions(expression, key="partition_by", flat=True)
    2626        return f"PARTITION BY {partition}" if partition else ""
    2627
    2628    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2629        kind = self.sql(expression, "kind")
    2630        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2631        end = (
    2632            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2633            or "CURRENT ROW"
    2634        )
    2635        return f"{kind} BETWEEN {start} AND {end}"
    2636
    2637    def withingroup_sql(self, expression: exp.WithinGroup) -> str:
    2638        this = self.sql(expression, "this")
    2639        expression_sql = self.sql(expression, "expression")[1:]  # order has a leading space
    2640        return f"{this} WITHIN GROUP ({expression_sql})"
    2641
    2642    def between_sql(self, expression: exp.Between) -> str:
    2643        this = self.sql(expression, "this")
    2644        low = self.sql(expression, "low")
    2645        high = self.sql(expression, "high")
    2646        return f"{this} BETWEEN {low} AND {high}"
    2647
    2648    def bracket_offset_expressions(self, expression: exp.Bracket) -> t.List[exp.Expression]:
    2649        return apply_index_offset(
    2650            expression.this,
    2651            expression.expressions,
    2652            self.dialect.INDEX_OFFSET - expression.args.get("offset", 0),
    2653        )
    2654
    2655    def bracket_sql(self, expression: exp.Bracket) -> str:
    2656        expressions = self.bracket_offset_expressions(expression)
    2657        expressions_sql = ", ".join(self.sql(e) for e in expressions)
    2658        return f"{self.sql(expression, 'this')}[{expressions_sql}]"
    2659
    2660    def all_sql(self, expression: exp.All) -> str:
    2661        return f"ALL {self.wrap(expression)}"
    2662
    2663    def any_sql(self, expression: exp.Any) -> str:
    2664        this = self.sql(expression, "this")
    2665        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
    2666            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2667                this = self.wrap(this)
    2668            return f"ANY{this}"
    2669        return f"ANY {this}"
    2670
    2671    def exists_sql(self, expression: exp.Exists) -> str:
    2672        return f"EXISTS{self.wrap(expression)}"
    2673
    2674    def case_sql(self, expression: exp.Case) -> str:
    2675        this = self.sql(expression, "this")
    2676        statements = [f"CASE {this}" if this else "CASE"]
    2677
    2678        for e in expression.args["ifs"]:
    2679            statements.append(f"WHEN {self.sql(e, 'this')}")
    2680            statements.append(f"THEN {self.sql(e, 'true')}")
    2681
    2682        default = self.sql(expression, "default")
    2683
    2684        if default:
    2685            statements.append(f"ELSE {default}")
    2686
    2687        statements.append("END")
    2688
    2689        if self.pretty and self.too_wide(statements):
    2690            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2691
    2692        return " ".join(statements)
    2693
    2694    def constraint_sql(self, expression: exp.Constraint) -> str:
    2695        this = self.sql(expression, "this")
    2696        expressions = self.expressions(expression, flat=True)
    2697        return f"CONSTRAINT {this} {expressions}"
    2698
    2699    def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str:
    2700        order = expression.args.get("order")
    2701        order = f" OVER ({self.order_sql(order, flat=True)})" if order else ""
    2702        return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}"
    2703
    2704    def extract_sql(self, expression: exp.Extract) -> str:
    2705        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2706        expression_sql = self.sql(expression, "expression")
    2707        return f"EXTRACT({this} FROM {expression_sql})"
    2708
    2709    def trim_sql(self, expression: exp.Trim) -> str:
    2710        trim_type = self.sql(expression, "position")
    2711
    2712        if trim_type == "LEADING":
    2713            func_name = "LTRIM"
    2714        elif trim_type == "TRAILING":
    2715            func_name = "RTRIM"
    2716        else:
    2717            func_name = "TRIM"
    2718
    2719        return self.func(func_name, expression.this, expression.expression)
    2720
    2721    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2722        args = expression.expressions
    2723        if isinstance(expression, exp.ConcatWs):
    2724            args = args[1:]  # Skip the delimiter
    2725
    2726        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2727            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
    2728
    2729        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2730            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2731
    2732        return args
    2733
    2734    def concat_sql(self, expression: exp.Concat) -> str:
    2735        expressions = self.convert_concat_args(expression)
    2736
    2737        # Some dialects don't allow a single-argument CONCAT call
    2738        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2739            return self.sql(expressions[0])
    2740
    2741        return self.func("CONCAT", *expressions)
    2742
    2743    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2744        return self.func(
    2745            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2746        )
    2747
    2748    def check_sql(self, expression: exp.Check) -> str:
    2749        this = self.sql(expression, key="this")
    2750        return f"CHECK ({this})"
    2751
    2752    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2753        expressions = self.expressions(expression, flat=True)
    2754        reference = self.sql(expression, "reference")
    2755        reference = f" {reference}" if reference else ""
    2756        delete = self.sql(expression, "delete")
    2757        delete = f" ON DELETE {delete}" if delete else ""
    2758        update = self.sql(expression, "update")
    2759        update = f" ON UPDATE {update}" if update else ""
    2760        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"
    2761
    2762    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2763        expressions = self.expressions(expression, flat=True)
    2764        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2765        options = f" {options}" if options else ""
    2766        return f"PRIMARY KEY ({expressions}){options}"
    2767
    2768    def if_sql(self, expression: exp.If) -> str:
    2769        return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false")))
    2770
    2771    def matchagainst_sql(self, expression: exp.MatchAgainst) -> str:
    2772        modifier = expression.args.get("modifier")
    2773        modifier = f" {modifier}" if modifier else ""
    2774        return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})"
    2775
    2776    def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str:
    2777        return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}"
    2778
    2779    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
    2780        path = self.expressions(expression, sep="", flat=True).lstrip(".")
    2781
    2782        if expression.args.get("escape"):
    2783            path = self.escape_str(path)
    2784
    2785        if self.QUOTE_JSON_PATH:
    2786            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
    2787
    2788        return path
    2789
    2790    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
    2791        if isinstance(expression, exp.JSONPathPart):
    2792            transform = self.TRANSFORMS.get(expression.__class__)
    2793            if not callable(transform):
    2794                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
    2795                return ""
    2796
    2797            return transform(self, expression)
    2798
    2799        if isinstance(expression, int):
    2800            return str(expression)
    2801
    2802        if self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
    2803            escaped = expression.replace("'", "\\'")
    2804            escaped = f"\\'{expression}\\'"
    2805        else:
    2806            escaped = expression.replace('"', '\\"')
    2807            escaped = f'"{escaped}"'
    2808
    2809        return escaped
    2810
    2811    def formatjson_sql(self, expression: exp.FormatJson) -> str:
    2812        return f"{self.sql(expression, 'this')} FORMAT JSON"
    2813
    2814    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    2815        null_handling = expression.args.get("null_handling")
    2816        null_handling = f" {null_handling}" if null_handling else ""
    2817
    2818        unique_keys = expression.args.get("unique_keys")
    2819        if unique_keys is not None:
    2820            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2821        else:
    2822            unique_keys = ""
    2823
    2824        return_type = self.sql(expression, "return_type")
    2825        return_type = f" RETURNING {return_type}" if return_type else ""
    2826        encoding = self.sql(expression, "encoding")
    2827        encoding = f" ENCODING {encoding}" if encoding else ""
    2828
    2829        return self.func(
    2830            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    2831            *expression.expressions,
    2832            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2833        )
    2834
    2835    def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str:
    2836        return self.jsonobject_sql(expression)
    2837
    2838    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2839        null_handling = expression.args.get("null_handling")
    2840        null_handling = f" {null_handling}" if null_handling else ""
    2841        return_type = self.sql(expression, "return_type")
    2842        return_type = f" RETURNING {return_type}" if return_type else ""
    2843        strict = " STRICT" if expression.args.get("strict") else ""
    2844        return self.func(
    2845            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2846        )
    2847
    2848    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2849        this = self.sql(expression, "this")
    2850        order = self.sql(expression, "order")
    2851        null_handling = expression.args.get("null_handling")
    2852        null_handling = f" {null_handling}" if null_handling else ""
    2853        return_type = self.sql(expression, "return_type")
    2854        return_type = f" RETURNING {return_type}" if return_type else ""
    2855        strict = " STRICT" if expression.args.get("strict") else ""
    2856        return self.func(
    2857            "JSON_ARRAYAGG",
    2858            this,
    2859            suffix=f"{order}{null_handling}{return_type}{strict})",
    2860        )
    2861
    2862    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2863        path = self.sql(expression, "path")
    2864        path = f" PATH {path}" if path else ""
    2865        nested_schema = self.sql(expression, "nested_schema")
    2866
    2867        if nested_schema:
    2868            return f"NESTED{path} {nested_schema}"
    2869
    2870        this = self.sql(expression, "this")
    2871        kind = self.sql(expression, "kind")
    2872        kind = f" {kind}" if kind else ""
    2873        return f"{this}{kind}{path}"
    2874
    2875    def jsonschema_sql(self, expression: exp.JSONSchema) -> str:
    2876        return self.func("COLUMNS", *expression.expressions)
    2877
    2878    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    2879        this = self.sql(expression, "this")
    2880        path = self.sql(expression, "path")
    2881        path = f", {path}" if path else ""
    2882        error_handling = expression.args.get("error_handling")
    2883        error_handling = f" {error_handling}" if error_handling else ""
    2884        empty_handling = expression.args.get("empty_handling")
    2885        empty_handling = f" {empty_handling}" if empty_handling else ""
    2886        schema = self.sql(expression, "schema")
    2887        return self.func(
    2888            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    2889        )
    2890
    2891    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    2892        this = self.sql(expression, "this")
    2893        kind = self.sql(expression, "kind")
    2894        path = self.sql(expression, "path")
    2895        path = f" {path}" if path else ""
    2896        as_json = " AS JSON" if expression.args.get("as_json") else ""
    2897        return f"{this} {kind}{path}{as_json}"
    2898
    2899    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    2900        this = self.sql(expression, "this")
    2901        path = self.sql(expression, "path")
    2902        path = f", {path}" if path else ""
    2903        expressions = self.expressions(expression)
    2904        with_ = (
    2905            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2906            if expressions
    2907            else ""
    2908        )
    2909        return f"OPENJSON({this}{path}){with_}"
    2910
    2911    def in_sql(self, expression: exp.In) -> str:
    2912        query = expression.args.get("query")
    2913        unnest = expression.args.get("unnest")
    2914        field = expression.args.get("field")
    2915        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    2916
    2917        if query:
    2918            in_sql = self.sql(query)
    2919        elif unnest:
    2920            in_sql = self.in_unnest_op(unnest)
    2921        elif field:
    2922            in_sql = self.sql(field)
    2923        else:
    2924            in_sql = f"({self.expressions(expression, flat=True)})"
    2925
    2926        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
    2927
    2928    def in_unnest_op(self, unnest: exp.Unnest) -> str:
    2929        return f"(SELECT {self.sql(unnest)})"
    2930
    2931    def interval_sql(self, expression: exp.Interval) -> str:
    2932        unit = self.sql(expression, "unit")
    2933        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    2934            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    2935        unit = f" {unit}" if unit else ""
    2936
    2937        if self.SINGLE_STRING_INTERVAL:
    2938            this = expression.this.name if expression.this else ""
    2939            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    2940
    2941        this = self.sql(expression, "this")
    2942        if this:
    2943            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    2944            this = f" {this}" if unwrapped else f" ({this})"
    2945
    2946        return f"INTERVAL{this}{unit}"
    2947
    2948    def return_sql(self, expression: exp.Return) -> str:
    2949        return f"RETURN {self.sql(expression, 'this')}"
    2950
    2951    def reference_sql(self, expression: exp.Reference) -> str:
    2952        this = self.sql(expression, "this")
    2953        expressions = self.expressions(expression, flat=True)
    2954        expressions = f"({expressions})" if expressions else ""
    2955        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2956        options = f" {options}" if options else ""
    2957        return f"REFERENCES {this}{expressions}{options}"
    2958
    2959    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    2960        # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive
    2961        parent = expression.parent
    2962        is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression
    2963        return self.func(
    2964            self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified
    2965        )
    2966
    2967    def paren_sql(self, expression: exp.Paren) -> str:
    2968        sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
    2969        return f"({sql}{self.seg(')', sep='')}"
    2970
    2971    def neg_sql(self, expression: exp.Neg) -> str:
    2972        # This makes sure we don't convert "- - 5" to "--5", which is a comment
    2973        this_sql = self.sql(expression, "this")
    2974        sep = " " if this_sql[0] == "-" else ""
    2975        return f"-{sep}{this_sql}"
    2976
    2977    def not_sql(self, expression: exp.Not) -> str:
    2978        return f"NOT {self.sql(expression, 'this')}"
    2979
    2980    def alias_sql(self, expression: exp.Alias) -> str:
    2981        alias = self.sql(expression, "alias")
    2982        alias = f" AS {alias}" if alias else ""
    2983        return f"{self.sql(expression, 'this')}{alias}"
    2984
    2985    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    2986        alias = expression.args["alias"]
    2987
    2988        identifier_alias = isinstance(alias, exp.Identifier)
    2989        literal_alias = isinstance(alias, exp.Literal)
    2990
    2991        if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2992            alias.replace(exp.Literal.string(alias.output_name))
    2993        elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2994            alias.replace(exp.to_identifier(alias.output_name))
    2995
    2996        return self.alias_sql(expression)
    2997
    2998    def aliases_sql(self, expression: exp.Aliases) -> str:
    2999        return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})"
    3000
    3001    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    3002        this = self.sql(expression, "this")
    3003        index = self.sql(expression, "expression")
    3004        return f"{this} AT {index}"
    3005
    3006    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    3007        this = self.sql(expression, "this")
    3008        zone = self.sql(expression, "zone")
    3009        return f"{this} AT TIME ZONE {zone}"
    3010
    3011    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    3012        this = self.sql(expression, "this")
    3013        zone = self.sql(expression, "zone")
    3014        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"
    3015
    3016    def add_sql(self, expression: exp.Add) -> str:
    3017        return self.binary(expression, "+")
    3018
    3019    def and_sql(
    3020        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
    3021    ) -> str:
    3022        return self.connector_sql(expression, "AND", stack)
    3023
    3024    def or_sql(
    3025        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
    3026    ) -> str:
    3027        return self.connector_sql(expression, "OR", stack)
    3028
    3029    def xor_sql(
    3030        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
    3031    ) -> str:
    3032        return self.connector_sql(expression, "XOR", stack)
    3033
    3034    def connector_sql(
    3035        self,
    3036        expression: exp.Connector,
    3037        op: str,
    3038        stack: t.Optional[t.List[str | exp.Expression]] = None,
    3039    ) -> str:
    3040        if stack is not None:
    3041            if expression.expressions:
    3042                stack.append(self.expressions(expression, sep=f" {op} "))
    3043            else:
    3044                stack.append(expression.right)
    3045                if expression.comments and self.comments:
    3046                    for comment in expression.comments:
    3047                        if comment:
    3048                            op += f" /*{self.pad_comment(comment)}*/"
    3049                stack.extend((op, expression.left))
    3050            return op
    3051
    3052        stack = [expression]
    3053        sqls: t.List[str] = []
    3054        ops = set()
    3055
    3056        while stack:
    3057            node = stack.pop()
    3058            if isinstance(node, exp.Connector):
    3059                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
    3060            else:
    3061                sql = self.sql(node)
    3062                if sqls and sqls[-1] in ops:
    3063                    sqls[-1] += f" {sql}"
    3064                else:
    3065                    sqls.append(sql)
    3066
    3067        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
    3068        return sep.join(sqls)
    3069
    3070    def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str:
    3071        return self.binary(expression, "&")
    3072
    3073    def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str:
    3074        return self.binary(expression, "<<")
    3075
    3076    def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str:
    3077        return f"~{self.sql(expression, 'this')}"
    3078
    3079    def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str:
    3080        return self.binary(expression, "|")
    3081
    3082    def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str:
    3083        return self.binary(expression, ">>")
    3084
    3085    def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str:
    3086        return self.binary(expression, "^")
    3087
    3088    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    3089        format_sql = self.sql(expression, "format")
    3090        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    3091        to_sql = self.sql(expression, "to")
    3092        to_sql = f" {to_sql}" if to_sql else ""
    3093        action = self.sql(expression, "action")
    3094        action = f" {action}" if action else ""
    3095        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{format_sql}{action})"
    3096
    3097    def currentdate_sql(self, expression: exp.CurrentDate) -> str:
    3098        zone = self.sql(expression, "this")
    3099        return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE"
    3100
    3101    def collate_sql(self, expression: exp.Collate) -> str:
    3102        if self.COLLATE_IS_FUNC:
    3103            return self.function_fallback_sql(expression)
    3104        return self.binary(expression, "COLLATE")
    3105
    3106    def command_sql(self, expression: exp.Command) -> str:
    3107        return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}"
    3108
    3109    def comment_sql(self, expression: exp.Comment) -> str:
    3110        this = self.sql(expression, "this")
    3111        kind = expression.args["kind"]
    3112        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    3113        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    3114        expression_sql = self.sql(expression, "expression")
    3115        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"
    3116
    3117    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    3118        this = self.sql(expression, "this")
    3119        delete = " DELETE" if expression.args.get("delete") else ""
    3120        recompress = self.sql(expression, "recompress")
    3121        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    3122        to_disk = self.sql(expression, "to_disk")
    3123        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    3124        to_volume = self.sql(expression, "to_volume")
    3125        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    3126        return f"{this}{delete}{recompress}{to_disk}{to_volume}"
    3127
    3128    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    3129        where = self.sql(expression, "where")
    3130        group = self.sql(expression, "group")
    3131        aggregates = self.expressions(expression, key="aggregates")
    3132        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    3133
    3134        if not (where or group or aggregates) and len(expression.expressions) == 1:
    3135            return f"TTL {self.expressions(expression, flat=True)}"
    3136
    3137        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
    3138
    3139    def transaction_sql(self, expression: exp.Transaction) -> str:
    3140        return "BEGIN"
    3141
    3142    def commit_sql(self, expression: exp.Commit) -> str:
    3143        chain = expression.args.get("chain")
    3144        if chain is not None:
    3145            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    3146
    3147        return f"COMMIT{chain or ''}"
    3148
    3149    def rollback_sql(self, expression: exp.Rollback) -> str:
    3150        savepoint = expression.args.get("savepoint")
    3151        savepoint = f" TO {savepoint}" if savepoint else ""
    3152        return f"ROLLBACK{savepoint}"
    3153
    3154    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    3155        this = self.sql(expression, "this")
    3156
    3157        dtype = self.sql(expression, "dtype")
    3158        if dtype:
    3159            collate = self.sql(expression, "collate")
    3160            collate = f" COLLATE {collate}" if collate else ""
    3161            using = self.sql(expression, "using")
    3162            using = f" USING {using}" if using else ""
    3163            return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}"
    3164
    3165        default = self.sql(expression, "default")
    3166        if default:
    3167            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    3168
    3169        comment = self.sql(expression, "comment")
    3170        if comment:
    3171            return f"ALTER COLUMN {this} COMMENT {comment}"
    3172
    3173        allow_null = expression.args.get("allow_null")
    3174        drop = expression.args.get("drop")
    3175
    3176        if not drop and not allow_null:
    3177            self.unsupported("Unsupported ALTER COLUMN syntax")
    3178
    3179        if allow_null is not None:
    3180            keyword = "DROP" if drop else "SET"
    3181            return f"ALTER COLUMN {this} {keyword} NOT NULL"
    3182
    3183        return f"ALTER COLUMN {this} DROP DEFAULT"
    3184
    3185    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
    3186        this = self.sql(expression, "this")
    3187        if not isinstance(expression.this, exp.Var):
    3188            this = f"KEY DISTKEY {this}"
    3189        return f"ALTER DISTSTYLE {this}"
    3190
    3191    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
    3192        compound = " COMPOUND" if expression.args.get("compound") else ""
    3193        this = self.sql(expression, "this")
    3194        expressions = self.expressions(expression, flat=True)
    3195        expressions = f"({expressions})" if expressions else ""
    3196        return f"ALTER{compound} SORTKEY {this or expressions}"
    3197
    3198    def renametable_sql(self, expression: exp.RenameTable) -> str:
    3199        if not self.RENAME_TABLE_WITH_DB:
    3200            # Remove db from tables
    3201            expression = expression.transform(
    3202                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    3203            ).assert_is(exp.RenameTable)
    3204        this = self.sql(expression, "this")
    3205        return f"RENAME TO {this}"
    3206
    3207    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    3208        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3209        old_column = self.sql(expression, "this")
    3210        new_column = self.sql(expression, "to")
    3211        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"
    3212
    3213    def alterset_sql(self, expression: exp.AlterSet) -> str:
    3214        exprs = self.expressions(expression, flat=True)
    3215        return f"SET {exprs}"
    3216
    3217    def alter_sql(self, expression: exp.Alter) -> str:
    3218        actions = expression.args["actions"]
    3219
    3220        if isinstance(actions[0], exp.ColumnDef):
    3221            actions = self.add_column_sql(expression)
    3222        elif isinstance(actions[0], exp.Schema):
    3223            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    3224        elif isinstance(actions[0], exp.Delete):
    3225            actions = self.expressions(expression, key="actions", flat=True)
    3226        elif isinstance(actions[0], exp.Query):
    3227            actions = "AS " + self.expressions(expression, key="actions")
    3228        else:
    3229            actions = self.expressions(expression, key="actions", flat=True)
    3230
    3231        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3232        on_cluster = self.sql(expression, "cluster")
    3233        on_cluster = f" {on_cluster}" if on_cluster else ""
    3234        only = " ONLY" if expression.args.get("only") else ""
    3235        options = self.expressions(expression, key="options")
    3236        options = f", {options}" if options else ""
    3237        kind = self.sql(expression, "kind")
    3238        not_valid = " NOT VALID" if expression.args.get("not_valid") else ""
    3239
    3240        return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}"
    3241
    3242    def add_column_sql(self, expression: exp.Alter) -> str:
    3243        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    3244            return self.expressions(
    3245                expression,
    3246                key="actions",
    3247                prefix="ADD COLUMN ",
    3248                skip_first=True,
    3249            )
    3250        return f"ADD {self.expressions(expression, key='actions', flat=True)}"
    3251
    3252    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    3253        expressions = self.expressions(expression)
    3254        exists = " IF EXISTS " if expression.args.get("exists") else " "
    3255        return f"DROP{exists}{expressions}"
    3256
    3257    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
    3258        return f"ADD {self.expressions(expression)}"
    3259
    3260    def distinct_sql(self, expression: exp.Distinct) -> str:
    3261        this = self.expressions(expression, flat=True)
    3262
    3263        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    3264            case = exp.case()
    3265            for arg in expression.expressions:
    3266                case = case.when(arg.is_(exp.null()), exp.null())
    3267            this = self.sql(case.else_(f"({this})"))
    3268
    3269        this = f" {this}" if this else ""
    3270
    3271        on = self.sql(expression, "on")
    3272        on = f" ON {on}" if on else ""
    3273        return f"DISTINCT{this}{on}"
    3274
    3275    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
    3276        return self._embed_ignore_nulls(expression, "IGNORE NULLS")
    3277
    3278    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
    3279        return self._embed_ignore_nulls(expression, "RESPECT NULLS")
    3280
    3281    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    3282        this_sql = self.sql(expression, "this")
    3283        expression_sql = self.sql(expression, "expression")
    3284        kind = "MAX" if expression.args.get("max") else "MIN"
    3285        return f"{this_sql} HAVING {kind} {expression_sql}"
    3286
    3287    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    3288        return self.sql(
    3289            exp.Cast(
    3290                this=exp.Div(this=expression.this, expression=expression.expression),
    3291                to=exp.DataType(this=exp.DataType.Type.INT),
    3292            )
    3293        )
    3294
    3295    def dpipe_sql(self, expression: exp.DPipe) -> str:
    3296        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    3297            return self.func(
    3298                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
    3299            )
    3300        return self.binary(expression, "||")
    3301
    3302    def div_sql(self, expression: exp.Div) -> str:
    3303        l, r = expression.left, expression.right
    3304
    3305        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    3306            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    3307
    3308        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    3309            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
    3310                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    3311
    3312        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    3313            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    3314                return self.sql(
    3315                    exp.cast(
    3316                        l / r,
    3317                        to=exp.DataType.Type.BIGINT,
    3318                    )
    3319                )
    3320
    3321        return self.binary(expression, "/")
    3322
    3323    def overlaps_sql(self, expression: exp.Overlaps) -> str:
    3324        return self.binary(expression, "OVERLAPS")
    3325
    3326    def distance_sql(self, expression: exp.Distance) -> str:
    3327        return self.binary(expression, "<->")
    3328
    3329    def dot_sql(self, expression: exp.Dot) -> str:
    3330        return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}"
    3331
    3332    def eq_sql(self, expression: exp.EQ) -> str:
    3333        return self.binary(expression, "=")
    3334
    3335    def propertyeq_sql(self, expression: exp.PropertyEQ) -> str:
    3336        return self.binary(expression, ":=")
    3337
    3338    def escape_sql(self, expression: exp.Escape) -> str:
    3339        return self.binary(expression, "ESCAPE")
    3340
    3341    def glob_sql(self, expression: exp.Glob) -> str:
    3342        return self.binary(expression, "GLOB")
    3343
    3344    def gt_sql(self, expression: exp.GT) -> str:
    3345        return self.binary(expression, ">")
    3346
    3347    def gte_sql(self, expression: exp.GTE) -> str:
    3348        return self.binary(expression, ">=")
    3349
    3350    def ilike_sql(self, expression: exp.ILike) -> str:
    3351        return self.binary(expression, "ILIKE")
    3352
    3353    def ilikeany_sql(self, expression: exp.ILikeAny) -> str:
    3354        return self.binary(expression, "ILIKE ANY")
    3355
    3356    def is_sql(self, expression: exp.Is) -> str:
    3357        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3358            return self.sql(
    3359                expression.this if expression.expression.this else exp.not_(expression.this)
    3360            )
    3361        return self.binary(expression, "IS")
    3362
    3363    def like_sql(self, expression: exp.Like) -> str:
    3364        return self.binary(expression, "LIKE")
    3365
    3366    def likeany_sql(self, expression: exp.LikeAny) -> str:
    3367        return self.binary(expression, "LIKE ANY")
    3368
    3369    def similarto_sql(self, expression: exp.SimilarTo) -> str:
    3370        return self.binary(expression, "SIMILAR TO")
    3371
    3372    def lt_sql(self, expression: exp.LT) -> str:
    3373        return self.binary(expression, "<")
    3374
    3375    def lte_sql(self, expression: exp.LTE) -> str:
    3376        return self.binary(expression, "<=")
    3377
    3378    def mod_sql(self, expression: exp.Mod) -> str:
    3379        return self.binary(expression, "%")
    3380
    3381    def mul_sql(self, expression: exp.Mul) -> str:
    3382        return self.binary(expression, "*")
    3383
    3384    def neq_sql(self, expression: exp.NEQ) -> str:
    3385        return self.binary(expression, "<>")
    3386
    3387    def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str:
    3388        return self.binary(expression, "IS NOT DISTINCT FROM")
    3389
    3390    def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str:
    3391        return self.binary(expression, "IS DISTINCT FROM")
    3392
    3393    def slice_sql(self, expression: exp.Slice) -> str:
    3394        return self.binary(expression, ":")
    3395
    3396    def sub_sql(self, expression: exp.Sub) -> str:
    3397        return self.binary(expression, "-")
    3398
    3399    def trycast_sql(self, expression: exp.TryCast) -> str:
    3400        return self.cast_sql(expression, safe_prefix="TRY_")
    3401
    3402    def try_sql(self, expression: exp.Try) -> str:
    3403        if not self.TRY_SUPPORTED:
    3404            self.unsupported("Unsupported TRY function")
    3405            return self.sql(expression, "this")
    3406
    3407        return self.func("TRY", expression.this)
    3408
    3409    def log_sql(self, expression: exp.Log) -> str:
    3410        this = expression.this
    3411        expr = expression.expression
    3412
    3413        if self.dialect.LOG_BASE_FIRST is False:
    3414            this, expr = expr, this
    3415        elif self.dialect.LOG_BASE_FIRST is None and expr:
    3416            if this.name in ("2", "10"):
    3417                return self.func(f"LOG{this.name}", expr)
    3418
    3419            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
    3420
    3421        return self.func("LOG", this, expr)
    3422
    3423    def use_sql(self, expression: exp.Use) -> str:
    3424        kind = self.sql(expression, "kind")
    3425        kind = f" {kind}" if kind else ""
    3426        this = self.sql(expression, "this")
    3427        this = f" {this}" if this else ""
    3428        return f"USE{kind}{this}"
    3429
    3430    def binary(self, expression: exp.Binary, op: str) -> str:
    3431        sqls: t.List[str] = []
    3432        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    3433        binary_type = type(expression)
    3434
    3435        while stack:
    3436            node = stack.pop()
    3437
    3438            if type(node) is binary_type:
    3439                op_func = node.args.get("operator")
    3440                if op_func:
    3441                    op = f"OPERATOR({self.sql(op_func)})"
    3442
    3443                stack.append(node.right)
    3444                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
    3445                stack.append(node.left)
    3446            else:
    3447                sqls.append(self.sql(node))
    3448
    3449        return "".join(sqls)
    3450
    3451    def function_fallback_sql(self, expression: exp.Func) -> str:
    3452        args = []
    3453
    3454        for key in expression.arg_types:
    3455            arg_value = expression.args.get(key)
    3456
    3457            if isinstance(arg_value, list):
    3458                for value in arg_value:
    3459                    args.append(value)
    3460            elif arg_value is not None:
    3461                args.append(arg_value)
    3462
    3463        if self.normalize_functions:
    3464            name = expression.sql_name()
    3465        else:
    3466            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3467
    3468        return self.func(name, *args)
    3469
    3470    def func(
    3471        self,
    3472        name: str,
    3473        *args: t.Optional[exp.Expression | str],
    3474        prefix: str = "(",
    3475        suffix: str = ")",
    3476        normalize: bool = True,
    3477    ) -> str:
    3478        name = self.normalize_func(name) if normalize else name
    3479        return f"{name}{prefix}{self.format_args(*args)}{suffix}"
    3480
    3481    def format_args(self, *args: t.Optional[str | exp.Expression]) -> str:
    3482        arg_sqls = tuple(
    3483            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
    3484        )
    3485        if self.pretty and self.too_wide(arg_sqls):
    3486            return self.indent("\n" + ",\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True)
    3487        return ", ".join(arg_sqls)
    3488
    3489    def too_wide(self, args: t.Iterable) -> bool:
    3490        return sum(len(arg) for arg in args) > self.max_text_width
    3491
    3492    def format_time(
    3493        self,
    3494        expression: exp.Expression,
    3495        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
    3496        inverse_time_trie: t.Optional[t.Dict] = None,
    3497    ) -> t.Optional[str]:
    3498        return format_time(
    3499            self.sql(expression, "format"),
    3500            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
    3501            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
    3502        )
    3503
    3504    def expressions(
    3505        self,
    3506        expression: t.Optional[exp.Expression] = None,
    3507        key: t.Optional[str] = None,
    3508        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    3509        flat: bool = False,
    3510        indent: bool = True,
    3511        skip_first: bool = False,
    3512        skip_last: bool = False,
    3513        sep: str = ", ",
    3514        prefix: str = "",
    3515        dynamic: bool = False,
    3516        new_line: bool = False,
    3517    ) -> str:
    3518        expressions = expression.args.get(key or "expressions") if expression else sqls
    3519
    3520        if not expressions:
    3521            return ""
    3522
    3523        if flat:
    3524            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    3525
    3526        num_sqls = len(expressions)
    3527        result_sqls = []
    3528
    3529        for i, e in enumerate(expressions):
    3530            sql = self.sql(e, comment=False)
    3531            if not sql:
    3532                continue
    3533
    3534            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    3535
    3536            if self.pretty:
    3537                if self.leading_comma:
    3538                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
    3539                else:
    3540                    result_sqls.append(
    3541                        f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}"
    3542                    )
    3543            else:
    3544                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    3545
    3546        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
    3547            if new_line:
    3548                result_sqls.insert(0, "")
    3549                result_sqls.append("")
    3550            result_sql = "\n".join(s.rstrip() for s in result_sqls)
    3551        else:
    3552            result_sql = "".join(result_sqls)
    3553
    3554        return (
    3555            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
    3556            if indent
    3557            else result_sql
    3558        )
    3559
    3560    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3561        flat = flat or isinstance(expression.parent, exp.Properties)
    3562        expressions_sql = self.expressions(expression, flat=flat)
    3563        if flat:
    3564            return f"{op} {expressions_sql}"
    3565        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
    3566
    3567    def naked_property(self, expression: exp.Property) -> str:
    3568        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3569        if not property_name:
    3570            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3571        return f"{property_name} {self.sql(expression, 'this')}"
    3572
    3573    def tag_sql(self, expression: exp.Tag) -> str:
    3574        return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}"
    3575
    3576    def token_sql(self, token_type: TokenType) -> str:
    3577        return self.TOKEN_MAPPING.get(token_type, token_type.name)
    3578
    3579    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3580        this = self.sql(expression, "this")
    3581        expressions = self.no_identify(self.expressions, expression)
    3582        expressions = (
    3583            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3584        )
    3585        return f"{this}{expressions}"
    3586
    3587    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3588        this = self.sql(expression, "this")
    3589        expressions = self.expressions(expression, flat=True)
    3590        return f"{this}({expressions})"
    3591
    3592    def kwarg_sql(self, expression: exp.Kwarg) -> str:
    3593        return self.binary(expression, "=>")
    3594
    3595    def when_sql(self, expression: exp.When) -> str:
    3596        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3597        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3598        condition = self.sql(expression, "condition")
    3599        condition = f" AND {condition}" if condition else ""
    3600
    3601        then_expression = expression.args.get("then")
    3602        if isinstance(then_expression, exp.Insert):
    3603            this = self.sql(then_expression, "this")
    3604            this = f"INSERT {this}" if this else "INSERT"
    3605            then = self.sql(then_expression, "expression")
    3606            then = f"{this} VALUES {then}" if then else this
    3607        elif isinstance(then_expression, exp.Update):
    3608            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3609                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3610            else:
    3611                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    3612        else:
    3613            then = self.sql(then_expression)
    3614        return f"WHEN {matched}{source}{condition} THEN {then}"
    3615
    3616    def merge_sql(self, expression: exp.Merge) -> str:
    3617        table = expression.this
    3618        table_alias = ""
    3619
    3620        hints = table.args.get("hints")
    3621        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3622            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3623            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3624
    3625        this = self.sql(table)
    3626        using = f"USING {self.sql(expression, 'using')}"
    3627        on = f"ON {self.sql(expression, 'on')}"
    3628        expressions = self.expressions(expression, sep=" ", indent=False)
    3629        returning = self.sql(expression, "returning")
    3630        if returning:
    3631            expressions = f"{expressions}{returning}"
    3632
    3633        sep = self.sep()
    3634
    3635        return self.prepend_ctes(
    3636            expression,
    3637            f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{expressions}",
    3638        )
    3639
    3640    @unsupported_args("format")
    3641    def tochar_sql(self, expression: exp.ToChar) -> str:
    3642        return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT))
    3643
    3644    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3645        if not self.SUPPORTS_TO_NUMBER:
    3646            self.unsupported("Unsupported TO_NUMBER function")
    3647            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3648
    3649        fmt = expression.args.get("format")
    3650        if not fmt:
    3651            self.unsupported("Conversion format is required for TO_NUMBER")
    3652            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3653
    3654        return self.func("TO_NUMBER", expression.this, fmt)
    3655
    3656    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3657        this = self.sql(expression, "this")
    3658        kind = self.sql(expression, "kind")
    3659        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3660        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3661        return f"{this}({kind}{args})"
    3662
    3663    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3664        this = self.sql(expression, "this")
    3665        max = self.sql(expression, "max")
    3666        min = self.sql(expression, "min")
    3667        return f"{this}(MIN {min} MAX {max})"
    3668
    3669    def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str:
    3670        return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}"
    3671
    3672    def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str:
    3673        return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})"
    3674
    3675    # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc
    3676    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
    3677        expressions = self.expressions(expression, flat=True)
    3678        expressions = f" {self.wrap(expressions)}" if expressions else ""
    3679        buckets = self.sql(expression, "buckets")
    3680        kind = self.sql(expression, "kind")
    3681        buckets = f" BUCKETS {buckets}" if buckets else ""
    3682        order = self.sql(expression, "order")
    3683        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"
    3684
    3685    def oncluster_sql(self, expression: exp.OnCluster) -> str:
    3686        return ""
    3687
    3688    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3689        expressions = self.expressions(expression, key="expressions", flat=True)
    3690        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3691        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3692        buckets = self.sql(expression, "buckets")
    3693        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
    3694
    3695    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3696        this = self.sql(expression, "this")
    3697        having = self.sql(expression, "having")
    3698
    3699        if having:
    3700            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3701
    3702        return self.func("ANY_VALUE", this)
    3703
    3704    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3705        transform = self.func("TRANSFORM", *expression.expressions)
    3706        row_format_before = self.sql(expression, "row_format_before")
    3707        row_format_before = f" {row_format_before}" if row_format_before else ""
    3708        record_writer = self.sql(expression, "record_writer")
    3709        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3710        using = f" USING {self.sql(expression, 'command_script')}"
    3711        schema = self.sql(expression, "schema")
    3712        schema = f" AS {schema}" if schema else ""
    3713        row_format_after = self.sql(expression, "row_format_after")
    3714        row_format_after = f" {row_format_after}" if row_format_after else ""
    3715        record_reader = self.sql(expression, "record_reader")
    3716        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3717        return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"
    3718
    3719    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3720        key_block_size = self.sql(expression, "key_block_size")
    3721        if key_block_size:
    3722            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3723
    3724        using = self.sql(expression, "using")
    3725        if using:
    3726            return f"USING {using}"
    3727
    3728        parser = self.sql(expression, "parser")
    3729        if parser:
    3730            return f"WITH PARSER {parser}"
    3731
    3732        comment = self.sql(expression, "comment")
    3733        if comment:
    3734            return f"COMMENT {comment}"
    3735
    3736        visible = expression.args.get("visible")
    3737        if visible is not None:
    3738            return "VISIBLE" if visible else "INVISIBLE"
    3739
    3740        engine_attr = self.sql(expression, "engine_attr")
    3741        if engine_attr:
    3742            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3743
    3744        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3745        if secondary_engine_attr:
    3746            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3747
    3748        self.unsupported("Unsupported index constraint option.")
    3749        return ""
    3750
    3751    def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str:
    3752        enforced = " ENFORCED" if expression.args.get("enforced") else ""
    3753        return f"CHECK ({self.sql(expression, 'this')}){enforced}"
    3754
    3755    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3756        kind = self.sql(expression, "kind")
    3757        kind = f"{kind} INDEX" if kind else "INDEX"
    3758        this = self.sql(expression, "this")
    3759        this = f" {this}" if this else ""
    3760        index_type = self.sql(expression, "index_type")
    3761        index_type = f" USING {index_type}" if index_type else ""
    3762        expressions = self.expressions(expression, flat=True)
    3763        expressions = f" ({expressions})" if expressions else ""
    3764        options = self.expressions(expression, key="options", sep=" ")
    3765        options = f" {options}" if options else ""
    3766        return f"{kind}{this}{index_type}{expressions}{options}"
    3767
    3768    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3769        if self.NVL2_SUPPORTED:
    3770            return self.function_fallback_sql(expression)
    3771
    3772        case = exp.Case().when(
    3773            expression.this.is_(exp.null()).not_(copy=False),
    3774            expression.args["true"],
    3775            copy=False,
    3776        )
    3777        else_cond = expression.args.get("false")
    3778        if else_cond:
    3779            case.else_(else_cond, copy=False)
    3780
    3781        return self.sql(case)
    3782
    3783    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3784        this = self.sql(expression, "this")
    3785        expr = self.sql(expression, "expression")
    3786        iterator = self.sql(expression, "iterator")
    3787        condition = self.sql(expression, "condition")
    3788        condition = f" IF {condition}" if condition else ""
    3789        return f"{this} FOR {expr} IN {iterator}{condition}"
    3790
    3791    def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str:
    3792        return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})"
    3793
    3794    def opclass_sql(self, expression: exp.Opclass) -> str:
    3795        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
    3796
    3797    def predict_sql(self, expression: exp.Predict) -> str:
    3798        model = self.sql(expression, "this")
    3799        model = f"MODEL {model}"
    3800        table = self.sql(expression, "expression")
    3801        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    3802        parameters = self.sql(expression, "params_struct")
    3803        return self.func("PREDICT", model, table, parameters or None)
    3804
    3805    def forin_sql(self, expression: exp.ForIn) -> str:
    3806        this = self.sql(expression, "this")
    3807        expression_sql = self.sql(expression, "expression")
    3808        return f"FOR {this} DO {expression_sql}"
    3809
    3810    def refresh_sql(self, expression: exp.Refresh) -> str:
    3811        this = self.sql(expression, "this")
    3812        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    3813        return f"REFRESH {table}{this}"
    3814
    3815    def toarray_sql(self, expression: exp.ToArray) -> str:
    3816        arg = expression.this
    3817        if not arg.type:
    3818            from sqlglot.optimizer.annotate_types import annotate_types
    3819
    3820            arg = annotate_types(arg)
    3821
    3822        if arg.is_type(exp.DataType.Type.ARRAY):
    3823            return self.sql(arg)
    3824
    3825        cond_for_null = arg.is_(exp.null())
    3826        return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False)))
    3827
    3828    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    3829        this = expression.this
    3830        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    3831            return self.sql(this)
    3832
    3833        return self.sql(exp.cast(this, exp.DataType.Type.TIME))
    3834
    3835    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
    3836        this = expression.this
    3837        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
    3838            return self.sql(this)
    3839
    3840        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP))
    3841
    3842    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    3843        this = expression.this
    3844        time_format = self.format_time(expression)
    3845
    3846        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    3847            return self.sql(
    3848                exp.cast(
    3849                    exp.StrToTime(this=this, format=expression.args["format"]),
    3850                    exp.DataType.Type.DATE,
    3851                )
    3852            )
    3853
    3854        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    3855            return self.sql(this)
    3856
    3857        return self.sql(exp.cast(this, exp.DataType.Type.DATE))
    3858
    3859    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    3860        return self.sql(
    3861            exp.func(
    3862                "DATEDIFF",
    3863                expression.this,
    3864                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
    3865                "day",
    3866            )
    3867        )
    3868
    3869    def lastday_sql(self, expression: exp.LastDay) -> str:
    3870        if self.LAST_DAY_SUPPORTS_DATE_PART:
    3871            return self.function_fallback_sql(expression)
    3872
    3873        unit = expression.text("unit")
    3874        if unit and unit != "MONTH":
    3875            self.unsupported("Date parts are not supported in LAST_DAY.")
    3876
    3877        return self.func("LAST_DAY", expression.this)
    3878
    3879    def dateadd_sql(self, expression: exp.DateAdd) -> str:
    3880        from sqlglot.dialects.dialect import unit_to_str
    3881
    3882        return self.func(
    3883            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
    3884        )
    3885
    3886    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    3887        if self.CAN_IMPLEMENT_ARRAY_ANY:
    3888            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    3889            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    3890            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    3891            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    3892
    3893        from sqlglot.dialects import Dialect
    3894
    3895        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    3896        if self.dialect.__class__ != Dialect:
    3897            self.unsupported("ARRAY_ANY is unsupported")
    3898
    3899        return self.function_fallback_sql(expression)
    3900
    3901    def struct_sql(self, expression: exp.Struct) -> str:
    3902        expression.set(
    3903            "expressions",
    3904            [
    3905                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    3906                if isinstance(e, exp.PropertyEQ)
    3907                else e
    3908                for e in expression.expressions
    3909            ],
    3910        )
    3911
    3912        return self.function_fallback_sql(expression)
    3913
    3914    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    3915        low = self.sql(expression, "this")
    3916        high = self.sql(expression, "expression")
    3917
    3918        return f"{low} TO {high}"
    3919
    3920    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    3921        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    3922        tables = f" {self.expressions(expression)}"
    3923
    3924        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3925
    3926        on_cluster = self.sql(expression, "cluster")
    3927        on_cluster = f" {on_cluster}" if on_cluster else ""
    3928
    3929        identity = self.sql(expression, "identity")
    3930        identity = f" {identity} IDENTITY" if identity else ""
    3931
    3932        option = self.sql(expression, "option")
    3933        option = f" {option}" if option else ""
    3934
    3935        partition = self.sql(expression, "partition")
    3936        partition = f" {partition}" if partition else ""
    3937
    3938        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"
    3939
    3940    # This transpiles T-SQL's CONVERT function
    3941    # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16
    3942    def convert_sql(self, expression: exp.Convert) -> str:
    3943        to = expression.this
    3944        value = expression.expression
    3945        style = expression.args.get("style")
    3946        safe = expression.args.get("safe")
    3947        strict = expression.args.get("strict")
    3948
    3949        if not to or not value:
    3950            return ""
    3951
    3952        # Retrieve length of datatype and override to default if not specified
    3953        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3954            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    3955
    3956        transformed: t.Optional[exp.Expression] = None
    3957        cast = exp.Cast if strict else exp.TryCast
    3958
    3959        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
    3960        if isinstance(style, exp.Literal) and style.is_int:
    3961            from sqlglot.dialects.tsql import TSQL
    3962
    3963            style_value = style.name
    3964            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
    3965            if not converted_style:
    3966                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
    3967
    3968            fmt = exp.Literal.string(converted_style)
    3969
    3970            if to.this == exp.DataType.Type.DATE:
    3971                transformed = exp.StrToDate(this=value, format=fmt)
    3972            elif to.this == exp.DataType.Type.DATETIME:
    3973                transformed = exp.StrToTime(this=value, format=fmt)
    3974            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3975                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
    3976            elif to.this == exp.DataType.Type.TEXT:
    3977                transformed = exp.TimeToStr(this=value, format=fmt)
    3978
    3979        if not transformed:
    3980            transformed = cast(this=value, to=to, safe=safe)
    3981
    3982        return self.sql(transformed)
    3983
    3984    def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str:
    3985        this = expression.this
    3986        if isinstance(this, exp.JSONPathWildcard):
    3987            this = self.json_path_part(this)
    3988            return f".{this}" if this else ""
    3989
    3990        if exp.SAFE_IDENTIFIER_RE.match(this):
    3991            return f".{this}"
    3992
    3993        this = self.json_path_part(this)
    3994        return f"[{this}]" if self.JSON_PATH_BRACKETED_KEY_SUPPORTED else f".{this}"
    3995
    3996    def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str:
    3997        this = self.json_path_part(expression.this)
    3998        return f"[{this}]" if this else ""
    3999
    4000    def _simplify_unless_literal(self, expression: E) -> E:
    4001        if not isinstance(expression, exp.Literal):
    4002            from sqlglot.optimizer.simplify import simplify
    4003
    4004            expression = simplify(expression, dialect=self.dialect)
    4005
    4006        return expression
    4007
    4008    def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str:
    4009        if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"):
    4010            # The first modifier here will be the one closest to the AggFunc's arg
    4011            mods = sorted(
    4012                expression.find_all(exp.HavingMax, exp.Order, exp.Limit),
    4013                key=lambda x: 0
    4014                if isinstance(x, exp.HavingMax)
    4015                else (1 if isinstance(x, exp.Order) else 2),
    4016            )
    4017
    4018            if mods:
    4019                mod = mods[0]
    4020                this = expression.__class__(this=mod.this.copy())
    4021                this.meta["inline"] = True
    4022                mod.this.replace(this)
    4023                return self.sql(expression.this)
    4024
    4025            agg_func = expression.find(exp.AggFunc)
    4026
    4027            if agg_func:
    4028                return self.sql(agg_func)[:-1] + f" {text})"
    4029
    4030        return f"{self.sql(expression, 'this')} {text}"
    4031
    4032    def _replace_line_breaks(self, string: str) -> str:
    4033        """We don't want to extra indent line breaks so we temporarily replace them with sentinels."""
    4034        if self.pretty:
    4035            return string.replace("\n", self.SENTINEL_LINE_BREAK)
    4036        return string
    4037
    4038    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
    4039        option = self.sql(expression, "this")
    4040
    4041        if expression.expressions:
    4042            upper = option.upper()
    4043
    4044            # Snowflake FILE_FORMAT options are separated by whitespace
    4045            sep = " " if upper == "FILE_FORMAT" else ", "
    4046
    4047            # Databricks copy/format options do not set their list of values with EQ
    4048            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
    4049            values = self.expressions(expression, flat=True, sep=sep)
    4050            return f"{option}{op}({values})"
    4051
    4052        value = self.sql(expression, "expression")
    4053
    4054        if not value:
    4055            return option
    4056
    4057        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
    4058
    4059        return f"{option}{op}{value}"
    4060
    4061    def credentials_sql(self, expression: exp.Credentials) -> str:
    4062        cred_expr = expression.args.get("credentials")
    4063        if isinstance(cred_expr, exp.Literal):
    4064            # Redshift case: CREDENTIALS <string>
    4065            credentials = self.sql(expression, "credentials")
    4066            credentials = f"CREDENTIALS {credentials}" if credentials else ""
    4067        else:
    4068            # Snowflake case: CREDENTIALS = (...)
    4069            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
    4070            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
    4071
    4072        storage = self.sql(expression, "storage")
    4073        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
    4074
    4075        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
    4076        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
    4077
    4078        iam_role = self.sql(expression, "iam_role")
    4079        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
    4080
    4081        region = self.sql(expression, "region")
    4082        region = f" REGION {region}" if region else ""
    4083
    4084        return f"{credentials}{storage}{encryption}{iam_role}{region}"
    4085
    4086    def copy_sql(self, expression: exp.Copy) -> str:
    4087        this = self.sql(expression, "this")
    4088        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
    4089
    4090        credentials = self.sql(expression, "credentials")
    4091        credentials = self.seg(credentials) if credentials else ""
    4092        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
    4093        files = self.expressions(expression, key="files", flat=True)
    4094
    4095        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
    4096        params = self.expressions(
    4097            expression,
    4098            key="params",
    4099            sep=sep,
    4100            new_line=True,
    4101            skip_last=True,
    4102            skip_first=True,
    4103            indent=self.COPY_PARAMS_ARE_WRAPPED,
    4104        )
    4105
    4106        if params:
    4107            if self.COPY_PARAMS_ARE_WRAPPED:
    4108                params = f" WITH ({params})"
    4109            elif not self.pretty:
    4110                params = f" {params}"
    4111
    4112        return f"COPY{this}{kind} {files}{credentials}{params}"
    4113
    4114    def semicolon_sql(self, expression: exp.Semicolon) -> str:
    4115        return ""
    4116
    4117    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
    4118        on_sql = "ON" if expression.args.get("on") else "OFF"
    4119        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
    4120        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
    4121        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    4122        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
    4123
    4124        if filter_col or retention_period:
    4125            on_sql = self.func("ON", filter_col, retention_period)
    4126
    4127        return f"DATA_DELETION={on_sql}"
    4128
    4129    def maskingpolicycolumnconstraint_sql(
    4130        self, expression: exp.MaskingPolicyColumnConstraint
    4131    ) -> str:
    4132        this = self.sql(expression, "this")
    4133        expressions = self.expressions(expression, flat=True)
    4134        expressions = f" USING ({expressions})" if expressions else ""
    4135        return f"MASKING POLICY {this}{expressions}"
    4136
    4137    def gapfill_sql(self, expression: exp.GapFill) -> str:
    4138        this = self.sql(expression, "this")
    4139        this = f"TABLE {this}"
    4140        return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"])
    4141
    4142    def scope_resolution(self, rhs: str, scope_name: str) -> str:
    4143        return self.func("SCOPE_RESOLUTION", scope_name or None, rhs)
    4144
    4145    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
    4146        this = self.sql(expression, "this")
    4147        expr = expression.expression
    4148
    4149        if isinstance(expr, exp.Func):
    4150            # T-SQL's CLR functions are case sensitive
    4151            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
    4152        else:
    4153            expr = self.sql(expression, "expression")
    4154
    4155        return self.scope_resolution(expr, this)
    4156
    4157    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
    4158        if self.PARSE_JSON_NAME is None:
    4159            return self.sql(expression.this)
    4160
    4161        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)
    4162
    4163    def rand_sql(self, expression: exp.Rand) -> str:
    4164        lower = self.sql(expression, "lower")
    4165        upper = self.sql(expression, "upper")
    4166
    4167        if lower and upper:
    4168            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
    4169        return self.func("RAND", expression.this)
    4170
    4171    def changes_sql(self, expression: exp.Changes) -> str:
    4172        information = self.sql(expression, "information")
    4173        information = f"INFORMATION => {information}"
    4174        at_before = self.sql(expression, "at_before")
    4175        at_before = f"{self.seg('')}{at_before}" if at_before else ""
    4176        end = self.sql(expression, "end")
    4177        end = f"{self.seg('')}{end}" if end else ""
    4178
    4179        return f"CHANGES ({information}){at_before}{end}"
    4180
    4181    def pad_sql(self, expression: exp.Pad) -> str:
    4182        prefix = "L" if expression.args.get("is_left") else "R"
    4183
    4184        fill_pattern = self.sql(expression, "fill_pattern") or None
    4185        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
    4186            fill_pattern = "' '"
    4187
    4188        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)
    4189
    4190    def summarize_sql(self, expression: exp.Summarize) -> str:
    4191        table = " TABLE" if expression.args.get("table") else ""
    4192        return f"SUMMARIZE{table} {self.sql(expression.this)}"
    4193
    4194    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
    4195        generate_series = exp.GenerateSeries(**expression.args)
    4196
    4197        parent = expression.parent
    4198        if isinstance(parent, (exp.Alias, exp.TableAlias)):
    4199            parent = parent.parent
    4200
    4201        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
    4202            return self.sql(exp.Unnest(expressions=[generate_series]))
    4203
    4204        if isinstance(parent, exp.Select):
    4205            self.unsupported("GenerateSeries projection unnesting is not supported.")
    4206
    4207        return self.sql(generate_series)
    4208
    4209    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
    4210        exprs = expression.expressions
    4211        if not self.ARRAY_CONCAT_IS_VAR_LEN:
    4212            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
    4213        else:
    4214            rhs = self.expressions(expression)
    4215
    4216        return self.func(name, expression.this, rhs)
    4217
    4218    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
    4219        if self.SUPPORTS_CONVERT_TIMEZONE:
    4220            return self.function_fallback_sql(expression)
    4221
    4222        source_tz = expression.args.get("source_tz")
    4223        target_tz = expression.args.get("target_tz")
    4224        timestamp = expression.args.get("timestamp")
    4225
    4226        if source_tz and timestamp:
    4227            timestamp = exp.AtTimeZone(
    4228                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
    4229            )
    4230
    4231        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
    4232
    4233        return self.sql(expr)
    4234
    4235    def json_sql(self, expression: exp.JSON) -> str:
    4236        this = self.sql(expression, "this")
    4237        this = f" {this}" if this else ""
    4238
    4239        _with = expression.args.get("with")
    4240
    4241        if _with is None:
    4242            with_sql = ""
    4243        elif not _with:
    4244            with_sql = " WITHOUT"
    4245        else:
    4246            with_sql = " WITH"
    4247
    4248        unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else ""
    4249
    4250        return f"JSON{this}{with_sql}{unique_sql}"
    4251
    4252    def jsonvalue_sql(self, expression: exp.JSONValue) -> str:
    4253        def _generate_on_options(arg: t.Any) -> str:
    4254            return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}"
    4255
    4256        path = self.sql(expression, "path")
    4257        returning = self.sql(expression, "returning")
    4258        returning = f" RETURNING {returning}" if returning else ""
    4259
    4260        on_condition = self.sql(expression, "on_condition")
    4261        on_condition = f" {on_condition}" if on_condition else ""
    4262
    4263        return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")
    4264
    4265    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
    4266        else_ = "ELSE " if expression.args.get("else_") else ""
    4267        condition = self.sql(expression, "expression")
    4268        condition = f"WHEN {condition} THEN " if condition else else_
    4269        insert = self.sql(expression, "this")[len("INSERT") :].strip()
    4270        return f"{condition}{insert}"
    4271
    4272    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
    4273        kind = self.sql(expression, "kind")
    4274        expressions = self.seg(self.expressions(expression, sep=" "))
    4275        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
    4276        return res
    4277
    4278    def oncondition_sql(self, expression: exp.OnCondition) -> str:
    4279        # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR"
    4280        empty = expression.args.get("empty")
    4281        empty = (
    4282            f"DEFAULT {empty} ON EMPTY"
    4283            if isinstance(empty, exp.Expression)
    4284            else self.sql(expression, "empty")
    4285        )
    4286
    4287        error = expression.args.get("error")
    4288        error = (
    4289            f"DEFAULT {error} ON ERROR"
    4290            if isinstance(error, exp.Expression)
    4291            else self.sql(expression, "error")
    4292        )
    4293
    4294        if error and empty:
    4295            error = (
    4296                f"{empty} {error}"
    4297                if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR
    4298                else f"{error} {empty}"
    4299            )
    4300            empty = ""
    4301
    4302        null = self.sql(expression, "null")
    4303
    4304        return f"{empty}{error}{null}"
    4305
    4306    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
    4307        this = self.sql(expression, "this")
    4308        path = self.sql(expression, "path")
    4309
    4310        passing = self.expressions(expression, "passing")
    4311        passing = f" PASSING {passing}" if passing else ""
    4312
    4313        on_condition = self.sql(expression, "on_condition")
    4314        on_condition = f" {on_condition}" if on_condition else ""
    4315
    4316        path = f"{path}{passing}{on_condition}"
    4317
    4318        return self.func("JSON_EXISTS", this, path)
    4319
    4320    def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
    4321        array_agg = self.function_fallback_sql(expression)
    4322
    4323        if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"):
    4324            parent = expression.parent
    4325            if isinstance(parent, exp.Filter):
    4326                parent_cond = parent.expression.this
    4327                parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_()))
    4328            else:
    4329                # DISTINCT is already present in the agg function, do not propagate it to FILTER as well
    4330                this = expression.this
    4331                this_sql = (
    4332                    self.expressions(this)
    4333                    if isinstance(this, exp.Distinct)
    4334                    else self.sql(expression, "this")
    4335                )
    4336                array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)"
    4337
    4338        return array_agg
    4339
    4340    def apply_sql(self, expression: exp.Apply) -> str:
    4341        this = self.sql(expression, "this")
    4342        expr = self.sql(expression, "expression")
    4343
    4344        return f"{this} APPLY({expr})"
    4345
    4346    def grant_sql(self, expression: exp.Grant) -> str:
    4347        privileges_sql = self.expressions(expression, key="privileges", flat=True)
    4348
    4349        kind = self.sql(expression, "kind")
    4350        kind = f" {kind}" if kind else ""
    4351
    4352        securable = self.sql(expression, "securable")
    4353        securable = f" {securable}" if securable else ""
    4354
    4355        principals = self.expressions(expression, key="principals", flat=True)
    4356
    4357        grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else ""
    4358
    4359        return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"
    4360
    4361    def grantprivilege_sql(self, expression: exp.GrantPrivilege):
    4362        this = self.sql(expression, "this")
    4363        columns = self.expressions(expression, flat=True)
    4364        columns = f"({columns})" if columns else ""
    4365
    4366        return f"{this}{columns}"
    4367
    4368    def grantprincipal_sql(self, expression: exp.GrantPrincipal):
    4369        this = self.sql(expression, "this")
    4370
    4371        kind = self.sql(expression, "kind")
    4372        kind = f"{kind} " if kind else ""
    4373
    4374        return f"{kind}{this}"

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

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

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

class Generator: View Source

      75class Generator(metaclass=_Generator):
      76    """
      77    Generator converts a given syntax tree to the corresponding SQL string.
      78
      79    Args:
      80        pretty: Whether to format the produced SQL string.
      81            Default: False.
      82        identify: Determines when an identifier should be quoted. Possible values are:
      83            False (default): Never quote, except in cases where it's mandatory by the dialect.
      84            True or 'always': Always quote.
      85            'safe': Only quote identifiers that are case insensitive.
      86        normalize: Whether to normalize identifiers to lowercase.
      87            Default: False.
      88        pad: The pad size in a formatted string. For example, this affects the indentation of
      89            a projection in a query, relative to its nesting level.
      90            Default: 2.
      91        indent: The indentation size in a formatted string. For example, this affects the
      92            indentation of subqueries and filters under a `WHERE` clause.
      93            Default: 2.
      94        normalize_functions: How to normalize function names. Possible values are:
      95            "upper" or True (default): Convert names to uppercase.
      96            "lower": Convert names to lowercase.
      97            False: Disables function name normalization.
      98        unsupported_level: Determines the generator's behavior when it encounters unsupported expressions.
      99            Default ErrorLevel.WARN.
     100        max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError.
     101            This is only relevant if unsupported_level is ErrorLevel.RAISE.
     102            Default: 3
     103        leading_comma: Whether the comma is leading or trailing in select expressions.
     104            This is only relevant when generating in pretty mode.
     105            Default: False
     106        max_text_width: The max number of characters in a segment before creating new lines in pretty mode.
     107            The default is on the smaller end because the length only represents a segment and not the true
     108            line length.
     109            Default: 80
     110        comments: Whether to preserve comments in the output SQL code.
     111            Default: True
     112    """
     113
     114    TRANSFORMS: t.Dict[t.Type[exp.Expression], t.Callable[..., str]] = {
     115        **JSON_PATH_PART_TRANSFORMS,
     116        exp.AllowedValuesProperty: lambda self,
     117        e: f"ALLOWED_VALUES {self.expressions(e, flat=True)}",
     118        exp.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        cluster = self.sql(expression, "cluster")
    1319        cluster = f" {cluster}" if cluster else ""
    1320        where = self.sql(expression, "where")
    1321        returning = self.sql(expression, "returning")
    1322        limit = self.sql(expression, "limit")
    1323        tables = self.expressions(expression, key="tables")
    1324        tables = f" {tables}" if tables else ""
    1325        if self.RETURNING_END:
    1326            expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}"
    1327        else:
    1328            expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}"
    1329        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")
    1330
    1331    def drop_sql(self, expression: exp.Drop) -> str:
    1332        this = self.sql(expression, "this")
    1333        expressions = self.expressions(expression, flat=True)
    1334        expressions = f" ({expressions})" if expressions else ""
    1335        kind = expression.args["kind"]
    1336        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
    1337        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    1338        concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else ""
    1339        on_cluster = self.sql(expression, "cluster")
    1340        on_cluster = f" {on_cluster}" if on_cluster else ""
    1341        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1342        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    1343        cascade = " CASCADE" if expression.args.get("cascade") else ""
    1344        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    1345        purge = " PURGE" if expression.args.get("purge") else ""
    1346        return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}"
    1347
    1348    def set_operation(self, expression: exp.SetOperation) -> str:
    1349        op_type = type(expression)
    1350        op_name = op_type.key.upper()
    1351
    1352        distinct = expression.args.get("distinct")
    1353        if (
    1354            distinct is False
    1355            and op_type in (exp.Except, exp.Intersect)
    1356            and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
    1357        ):
    1358            self.unsupported(f"{op_name} ALL is not supported")
    1359
    1360        default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type]
    1361
    1362        if distinct is None:
    1363            distinct = default_distinct
    1364            if distinct is None:
    1365                self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified")
    1366
    1367        if distinct is default_distinct:
    1368            kind = ""
    1369        else:
    1370            kind = " DISTINCT" if distinct else " ALL"
    1371
    1372        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1373        return f"{op_name}{kind}{by_name}"
    1374
    1375    def set_operations(self, expression: exp.SetOperation) -> str:
    1376        if not self.SET_OP_MODIFIERS:
    1377            limit = expression.args.get("limit")
    1378            order = expression.args.get("order")
    1379
    1380            if limit or order:
    1381                select = exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
    1382
    1383                if limit:
    1384                    select = select.limit(limit.pop(), copy=False)
    1385                if order:
    1386                    select = select.order_by(order.pop(), copy=False)
    1387                return self.sql(select)
    1388
    1389        sqls: t.List[str] = []
    1390        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    1391
    1392        while stack:
    1393            node = stack.pop()
    1394
    1395            if isinstance(node, exp.SetOperation):
    1396                stack.append(node.expression)
    1397                stack.append(
    1398                    self.maybe_comment(
    1399                        self.set_operation(node), comments=node.comments, separated=True
    1400                    )
    1401                )
    1402                stack.append(node.this)
    1403            else:
    1404                sqls.append(self.sql(node))
    1405
    1406        this = self.sep().join(sqls)
    1407        this = self.query_modifiers(expression, this)
    1408        return self.prepend_ctes(expression, this)
    1409
    1410    def fetch_sql(self, expression: exp.Fetch) -> str:
    1411        direction = expression.args.get("direction")
    1412        direction = f" {direction}" if direction else ""
    1413        count = self.sql(expression, "count")
    1414        count = f" {count}" if count else ""
    1415        if expression.args.get("percent"):
    1416            count = f"{count} PERCENT"
    1417        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    1418        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"
    1419
    1420    def filter_sql(self, expression: exp.Filter) -> str:
    1421        if self.AGGREGATE_FILTER_SUPPORTED:
    1422            this = self.sql(expression, "this")
    1423            where = self.sql(expression, "expression").strip()
    1424            return f"{this} FILTER({where})"
    1425
    1426        agg = expression.this
    1427        agg_arg = agg.this
    1428        cond = expression.expression.this
    1429        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1430        return self.sql(agg)
    1431
    1432    def hint_sql(self, expression: exp.Hint) -> str:
    1433        if not self.QUERY_HINTS:
    1434            self.unsupported("Hints are not supported")
    1435            return ""
    1436
    1437        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"
    1438
    1439    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
    1440        using = self.sql(expression, "using")
    1441        using = f" USING {using}" if using else ""
    1442        columns = self.expressions(expression, key="columns", flat=True)
    1443        columns = f"({columns})" if columns else ""
    1444        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1445        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1446        where = self.sql(expression, "where")
    1447        include = self.expressions(expression, key="include", flat=True)
    1448        if include:
    1449            include = f" INCLUDE ({include})"
    1450        with_storage = self.expressions(expression, key="with_storage", flat=True)
    1451        with_storage = f" WITH ({with_storage})" if with_storage else ""
    1452        tablespace = self.sql(expression, "tablespace")
    1453        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
    1454        on = self.sql(expression, "on")
    1455        on = f" ON {on}" if on else ""
    1456
    1457        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"
    1458
    1459    def index_sql(self, expression: exp.Index) -> str:
    1460        unique = "UNIQUE " if expression.args.get("unique") else ""
    1461        primary = "PRIMARY " if expression.args.get("primary") else ""
    1462        amp = "AMP " if expression.args.get("amp") else ""
    1463        name = self.sql(expression, "this")
    1464        name = f"{name} " if name else ""
    1465        table = self.sql(expression, "table")
    1466        table = f"{self.INDEX_ON} {table}" if table else ""
    1467
    1468        index = "INDEX " if not table else ""
    1469
    1470        params = self.sql(expression, "params")
    1471        return f"{unique}{primary}{amp}{index}{name}{table}{params}"
    1472
    1473    def identifier_sql(self, expression: exp.Identifier) -> str:
    1474        text = expression.name
    1475        lower = text.lower()
    1476        text = lower if self.normalize and not expression.quoted else text
    1477        text = text.replace(self._identifier_end, self._escaped_identifier_end)
    1478        if (
    1479            expression.quoted
    1480            or self.dialect.can_identify(text, self.identify)
    1481            or lower in self.RESERVED_KEYWORDS
    1482            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1483        ):
    1484            text = f"{self._identifier_start}{text}{self._identifier_end}"
    1485        return text
    1486
    1487    def hex_sql(self, expression: exp.Hex) -> str:
    1488        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1489        if self.dialect.HEX_LOWERCASE:
    1490            text = self.func("LOWER", text)
    1491
    1492        return text
    1493
    1494    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
    1495        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1496        if not self.dialect.HEX_LOWERCASE:
    1497            text = self.func("LOWER", text)
    1498        return text
    1499
    1500    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1501        input_format = self.sql(expression, "input_format")
    1502        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1503        output_format = self.sql(expression, "output_format")
    1504        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1505        return self.sep().join((input_format, output_format))
    1506
    1507    def national_sql(self, expression: exp.National, prefix: str = "N") -> str:
    1508        string = self.sql(exp.Literal.string(expression.name))
    1509        return f"{prefix}{string}"
    1510
    1511    def partition_sql(self, expression: exp.Partition) -> str:
    1512        return f"PARTITION({self.expressions(expression, flat=True)})"
    1513
    1514    def properties_sql(self, expression: exp.Properties) -> str:
    1515        root_properties = []
    1516        with_properties = []
    1517
    1518        for p in expression.expressions:
    1519            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1520            if p_loc == exp.Properties.Location.POST_WITH:
    1521                with_properties.append(p)
    1522            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1523                root_properties.append(p)
    1524
    1525        root_props = self.root_properties(exp.Properties(expressions=root_properties))
    1526        with_props = self.with_properties(exp.Properties(expressions=with_properties))
    1527
    1528        if root_props and with_props and not self.pretty:
    1529            with_props = " " + with_props
    1530
    1531        return root_props + with_props
    1532
    1533    def root_properties(self, properties: exp.Properties) -> str:
    1534        if properties.expressions:
    1535            return self.expressions(properties, indent=False, sep=" ")
    1536        return ""
    1537
    1538    def properties(
    1539        self,
    1540        properties: exp.Properties,
    1541        prefix: str = "",
    1542        sep: str = ", ",
    1543        suffix: str = "",
    1544        wrapped: bool = True,
    1545    ) -> str:
    1546        if properties.expressions:
    1547            expressions = self.expressions(properties, sep=sep, indent=False)
    1548            if expressions:
    1549                expressions = self.wrap(expressions) if wrapped else expressions
    1550                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1551        return ""
    1552
    1553    def with_properties(self, properties: exp.Properties) -> str:
    1554        return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep=""))
    1555
    1556    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1557        properties_locs = defaultdict(list)
    1558        for p in properties.expressions:
    1559            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1560            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1561                properties_locs[p_loc].append(p)
    1562            else:
    1563                self.unsupported(f"Unsupported property {p.key}")
    1564
    1565        return properties_locs
    1566
    1567    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1568        if isinstance(expression.this, exp.Dot):
    1569            return self.sql(expression, "this")
    1570        return f"'{expression.name}'" if string_key else expression.name
    1571
    1572    def property_sql(self, expression: exp.Property) -> str:
    1573        property_cls = expression.__class__
    1574        if property_cls == exp.Property:
    1575            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1576
    1577        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1578        if not property_name:
    1579            self.unsupported(f"Unsupported property {expression.key}")
    1580
    1581        return f"{property_name}={self.sql(expression, 'this')}"
    1582
    1583    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1584        if self.SUPPORTS_CREATE_TABLE_LIKE:
    1585            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1586            options = f" {options}" if options else ""
    1587
    1588            like = f"LIKE {self.sql(expression, 'this')}{options}"
    1589            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
    1590                like = f"({like})"
    1591
    1592            return like
    1593
    1594        if expression.expressions:
    1595            self.unsupported("Transpilation of LIKE property options is unsupported")
    1596
    1597        select = exp.select("*").from_(expression.this).limit(0)
    1598        return f"AS {self.sql(select)}"
    1599
    1600    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1601        no = "NO " if expression.args.get("no") else ""
    1602        protection = " PROTECTION" if expression.args.get("protection") else ""
    1603        return f"{no}FALLBACK{protection}"
    1604
    1605    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1606        no = "NO " if expression.args.get("no") else ""
    1607        local = expression.args.get("local")
    1608        local = f"{local} " if local else ""
    1609        dual = "DUAL " if expression.args.get("dual") else ""
    1610        before = "BEFORE " if expression.args.get("before") else ""
    1611        after = "AFTER " if expression.args.get("after") else ""
    1612        return f"{no}{local}{dual}{before}{after}JOURNAL"
    1613
    1614    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1615        freespace = self.sql(expression, "this")
    1616        percent = " PERCENT" if expression.args.get("percent") else ""
    1617        return f"FREESPACE={freespace}{percent}"
    1618
    1619    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1620        if expression.args.get("default"):
    1621            property = "DEFAULT"
    1622        elif expression.args.get("on"):
    1623            property = "ON"
    1624        else:
    1625            property = "OFF"
    1626        return f"CHECKSUM={property}"
    1627
    1628    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1629        if expression.args.get("no"):
    1630            return "NO MERGEBLOCKRATIO"
    1631        if expression.args.get("default"):
    1632            return "DEFAULT MERGEBLOCKRATIO"
    1633
    1634        percent = " PERCENT" if expression.args.get("percent") else ""
    1635        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
    1636
    1637    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1638        default = expression.args.get("default")
    1639        minimum = expression.args.get("minimum")
    1640        maximum = expression.args.get("maximum")
    1641        if default or minimum or maximum:
    1642            if default:
    1643                prop = "DEFAULT"
    1644            elif minimum:
    1645                prop = "MINIMUM"
    1646            else:
    1647                prop = "MAXIMUM"
    1648            return f"{prop} DATABLOCKSIZE"
    1649        units = expression.args.get("units")
    1650        units = f" {units}" if units else ""
    1651        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
    1652
    1653    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1654        autotemp = expression.args.get("autotemp")
    1655        always = expression.args.get("always")
    1656        default = expression.args.get("default")
    1657        manual = expression.args.get("manual")
    1658        never = expression.args.get("never")
    1659
    1660        if autotemp is not None:
    1661            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1662        elif always:
    1663            prop = "ALWAYS"
    1664        elif default:
    1665            prop = "DEFAULT"
    1666        elif manual:
    1667            prop = "MANUAL"
    1668        elif never:
    1669            prop = "NEVER"
    1670        return f"BLOCKCOMPRESSION={prop}"
    1671
    1672    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1673        no = expression.args.get("no")
    1674        no = " NO" if no else ""
    1675        concurrent = expression.args.get("concurrent")
    1676        concurrent = " CONCURRENT" if concurrent else ""
    1677        target = self.sql(expression, "target")
    1678        target = f" {target}" if target else ""
    1679        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"
    1680
    1681    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1682        if isinstance(expression.this, list):
    1683            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1684        if expression.this:
    1685            modulus = self.sql(expression, "this")
    1686            remainder = self.sql(expression, "expression")
    1687            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1688
    1689        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1690        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1691        return f"FROM ({from_expressions}) TO ({to_expressions})"
    1692
    1693    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1694        this = self.sql(expression, "this")
    1695
    1696        for_values_or_default = expression.expression
    1697        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1698            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1699        else:
    1700            for_values_or_default = " DEFAULT"
    1701
    1702        return f"PARTITION OF {this}{for_values_or_default}"
    1703
    1704    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1705        kind = expression.args.get("kind")
    1706        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1707        for_or_in = expression.args.get("for_or_in")
    1708        for_or_in = f" {for_or_in}" if for_or_in else ""
    1709        lock_type = expression.args.get("lock_type")
    1710        override = " OVERRIDE" if expression.args.get("override") else ""
    1711        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"
    1712
    1713    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1714        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1715        statistics = expression.args.get("statistics")
    1716        statistics_sql = ""
    1717        if statistics is not None:
    1718            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1719        return f"{data_sql}{statistics_sql}"
    1720
    1721    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1722        this = self.sql(expression, "this")
    1723        this = f"HISTORY_TABLE={this}" if this else ""
    1724        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
    1725        data_consistency = (
    1726            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
    1727        )
    1728        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    1729        retention_period = (
    1730            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
    1731        )
    1732
    1733        if this:
    1734            on_sql = self.func("ON", this, data_consistency, retention_period)
    1735        else:
    1736            on_sql = "ON" if expression.args.get("on") else "OFF"
    1737
    1738        sql = f"SYSTEM_VERSIONING={on_sql}"
    1739
    1740        return f"WITH({sql})" if expression.args.get("with") else sql
    1741
    1742    def insert_sql(self, expression: exp.Insert) -> str:
    1743        hint = self.sql(expression, "hint")
    1744        overwrite = expression.args.get("overwrite")
    1745
    1746        if isinstance(expression.this, exp.Directory):
    1747            this = " OVERWRITE" if overwrite else " INTO"
    1748        else:
    1749            this = self.INSERT_OVERWRITE if overwrite else " INTO"
    1750
    1751        stored = self.sql(expression, "stored")
    1752        stored = f" {stored}" if stored else ""
    1753        alternative = expression.args.get("alternative")
    1754        alternative = f" OR {alternative}" if alternative else ""
    1755        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1756        is_function = expression.args.get("is_function")
    1757        if is_function:
    1758            this = f"{this} FUNCTION"
    1759        this = f"{this} {self.sql(expression, 'this')}"
    1760
    1761        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1762        where = self.sql(expression, "where")
    1763        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1764        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1765        on_conflict = self.sql(expression, "conflict")
    1766        on_conflict = f" {on_conflict}" if on_conflict else ""
    1767        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1768        returning = self.sql(expression, "returning")
    1769
    1770        if self.RETURNING_END:
    1771            expression_sql = f"{expression_sql}{on_conflict}{returning}"
    1772        else:
    1773            expression_sql = f"{returning}{expression_sql}{on_conflict}"
    1774
    1775        partition_by = self.sql(expression, "partition")
    1776        partition_by = f" {partition_by}" if partition_by else ""
    1777        settings = self.sql(expression, "settings")
    1778        settings = f" {settings}" if settings else ""
    1779
    1780        source = self.sql(expression, "source")
    1781        source = f"TABLE {source}" if source else ""
    1782
    1783        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}"
    1784        return self.prepend_ctes(expression, sql)
    1785
    1786    def introducer_sql(self, expression: exp.Introducer) -> str:
    1787        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
    1788
    1789    def kill_sql(self, expression: exp.Kill) -> str:
    1790        kind = self.sql(expression, "kind")
    1791        kind = f" {kind}" if kind else ""
    1792        this = self.sql(expression, "this")
    1793        this = f" {this}" if this else ""
    1794        return f"KILL{kind}{this}"
    1795
    1796    def pseudotype_sql(self, expression: exp.PseudoType) -> str:
    1797        return expression.name
    1798
    1799    def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str:
    1800        return expression.name
    1801
    1802    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1803        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1804
    1805        constraint = self.sql(expression, "constraint")
    1806        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
    1807
    1808        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
    1809        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
    1810        action = self.sql(expression, "action")
    1811
    1812        expressions = self.expressions(expression, flat=True)
    1813        if expressions:
    1814            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1815            expressions = f" {set_keyword}{expressions}"
    1816
    1817        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}"
    1818
    1819    def returning_sql(self, expression: exp.Returning) -> str:
    1820        return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}"
    1821
    1822    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1823        fields = self.sql(expression, "fields")
    1824        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1825        escaped = self.sql(expression, "escaped")
    1826        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1827        items = self.sql(expression, "collection_items")
    1828        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1829        keys = self.sql(expression, "map_keys")
    1830        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1831        lines = self.sql(expression, "lines")
    1832        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1833        null = self.sql(expression, "null")
    1834        null = f" NULL DEFINED AS {null}" if null else ""
    1835        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
    1836
    1837    def withtablehint_sql(self, expression: exp.WithTableHint) -> str:
    1838        return f"WITH ({self.expressions(expression, flat=True)})"
    1839
    1840    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1841        this = f"{self.sql(expression, 'this')} INDEX"
    1842        target = self.sql(expression, "target")
    1843        target = f" FOR {target}" if target else ""
    1844        return f"{this}{target} ({self.expressions(expression, flat=True)})"
    1845
    1846    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1847        this = self.sql(expression, "this")
    1848        kind = self.sql(expression, "kind")
    1849        expr = self.sql(expression, "expression")
    1850        return f"{this} ({kind} => {expr})"
    1851
    1852    def table_parts(self, expression: exp.Table) -> str:
    1853        return ".".join(
    1854            self.sql(part)
    1855            for part in (
    1856                expression.args.get("catalog"),
    1857                expression.args.get("db"),
    1858                expression.args.get("this"),
    1859            )
    1860            if part is not None
    1861        )
    1862
    1863    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1864        table = self.table_parts(expression)
    1865        only = "ONLY " if expression.args.get("only") else ""
    1866        partition = self.sql(expression, "partition")
    1867        partition = f" {partition}" if partition else ""
    1868        version = self.sql(expression, "version")
    1869        version = f" {version}" if version else ""
    1870        alias = self.sql(expression, "alias")
    1871        alias = f"{sep}{alias}" if alias else ""
    1872
    1873        sample = self.sql(expression, "sample")
    1874        if self.dialect.ALIAS_POST_TABLESAMPLE:
    1875            sample_pre_alias = sample
    1876            sample_post_alias = ""
    1877        else:
    1878            sample_pre_alias = ""
    1879            sample_post_alias = sample
    1880
    1881        hints = self.expressions(expression, key="hints", sep=" ")
    1882        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1883        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    1884        joins = self.indent(
    1885            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    1886        )
    1887        laterals = self.expressions(expression, key="laterals", sep="")
    1888
    1889        file_format = self.sql(expression, "format")
    1890        if file_format:
    1891            pattern = self.sql(expression, "pattern")
    1892            pattern = f", PATTERN => {pattern}" if pattern else ""
    1893            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    1894
    1895        ordinality = expression.args.get("ordinality") or ""
    1896        if ordinality:
    1897            ordinality = f" WITH ORDINALITY{alias}"
    1898            alias = ""
    1899
    1900        when = self.sql(expression, "when")
    1901        if when:
    1902            table = f"{table} {when}"
    1903
    1904        changes = self.sql(expression, "changes")
    1905        changes = f" {changes}" if changes else ""
    1906
    1907        rows_from = self.expressions(expression, key="rows_from")
    1908        if rows_from:
    1909            table = f"ROWS FROM {self.wrap(rows_from)}"
    1910
    1911        return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}"
    1912
    1913    def tablesample_sql(
    1914        self,
    1915        expression: exp.TableSample,
    1916        tablesample_keyword: t.Optional[str] = None,
    1917    ) -> str:
    1918        method = self.sql(expression, "method")
    1919        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1920        numerator = self.sql(expression, "bucket_numerator")
    1921        denominator = self.sql(expression, "bucket_denominator")
    1922        field = self.sql(expression, "bucket_field")
    1923        field = f" ON {field}" if field else ""
    1924        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1925        seed = self.sql(expression, "seed")
    1926        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
    1927
    1928        size = self.sql(expression, "size")
    1929        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
    1930            size = f"{size} ROWS"
    1931
    1932        percent = self.sql(expression, "percent")
    1933        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
    1934            percent = f"{percent} PERCENT"
    1935
    1936        expr = f"{bucket}{percent}{size}"
    1937        if self.TABLESAMPLE_REQUIRES_PARENS:
    1938            expr = f"({expr})"
    1939
    1940        return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"
    1941
    1942    def pivot_sql(self, expression: exp.Pivot) -> str:
    1943        expressions = self.expressions(expression, flat=True)
    1944
    1945        if expression.this:
    1946            this = self.sql(expression, "this")
    1947            if not expressions:
    1948                return f"UNPIVOT {this}"
    1949
    1950            on = f"{self.seg('ON')} {expressions}"
    1951            using = self.expressions(expression, key="using", flat=True)
    1952            using = f"{self.seg('USING')} {using}" if using else ""
    1953            group = self.sql(expression, "group")
    1954            return f"PIVOT {this}{on}{using}{group}"
    1955
    1956        alias = self.sql(expression, "alias")
    1957        alias = f" AS {alias}" if alias else ""
    1958        direction = self.seg("UNPIVOT" if expression.unpivot else "PIVOT")
    1959
    1960        field = self.sql(expression, "field")
    1961
    1962        include_nulls = expression.args.get("include_nulls")
    1963        if include_nulls is not None:
    1964            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    1965        else:
    1966            nulls = ""
    1967
    1968        default_on_null = self.sql(expression, "default_on_null")
    1969        default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else ""
    1970        return f"{direction}{nulls}({expressions} FOR {field}{default_on_null}){alias}"
    1971
    1972    def version_sql(self, expression: exp.Version) -> str:
    1973        this = f"FOR {expression.name}"
    1974        kind = expression.text("kind")
    1975        expr = self.sql(expression, "expression")
    1976        return f"{this} {kind} {expr}"
    1977
    1978    def tuple_sql(self, expression: exp.Tuple) -> str:
    1979        return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"
    1980
    1981    def update_sql(self, expression: exp.Update) -> str:
    1982        this = self.sql(expression, "this")
    1983        set_sql = self.expressions(expression, flat=True)
    1984        from_sql = self.sql(expression, "from")
    1985        where_sql = self.sql(expression, "where")
    1986        returning = self.sql(expression, "returning")
    1987        order = self.sql(expression, "order")
    1988        limit = self.sql(expression, "limit")
    1989        if self.RETURNING_END:
    1990            expression_sql = f"{from_sql}{where_sql}{returning}"
    1991        else:
    1992            expression_sql = f"{returning}{from_sql}{where_sql}"
    1993        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    1994        return self.prepend_ctes(expression, sql)
    1995
    1996    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
    1997        values_as_table = values_as_table and self.VALUES_AS_TABLE
    1998
    1999        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    2000        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
    2001            args = self.expressions(expression)
    2002            alias = self.sql(expression, "alias")
    2003            values = f"VALUES{self.seg('')}{args}"
    2004            values = (
    2005                f"({values})"
    2006                if self.WRAP_DERIVED_VALUES
    2007                and (alias or isinstance(expression.parent, (exp.From, exp.Table)))
    2008                else values
    2009            )
    2010            return f"{values} AS {alias}" if alias else values
    2011
    2012        # Converts `VALUES...` expression into a series of select unions.
    2013        alias_node = expression.args.get("alias")
    2014        column_names = alias_node and alias_node.columns
    2015
    2016        selects: t.List[exp.Query] = []
    2017
    2018        for i, tup in enumerate(expression.expressions):
    2019            row = tup.expressions
    2020
    2021            if i == 0 and column_names:
    2022                row = [
    2023                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    2024                ]
    2025
    2026            selects.append(exp.Select(expressions=row))
    2027
    2028        if self.pretty:
    2029            # This may result in poor performance for large-cardinality `VALUES` tables, due to
    2030            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
    2031            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
    2032            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
    2033            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
    2034
    2035        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
    2036        unions = " UNION ALL ".join(self.sql(select) for select in selects)
    2037        return f"({unions}){alias}"
    2038
    2039    def var_sql(self, expression: exp.Var) -> str:
    2040        return self.sql(expression, "this")
    2041
    2042    def into_sql(self, expression: exp.Into) -> str:
    2043        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    2044        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
    2045        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
    2046
    2047    def from_sql(self, expression: exp.From) -> str:
    2048        return f"{self.seg('FROM')} {self.sql(expression, 'this')}"
    2049
    2050    def groupingsets_sql(self, expression: exp.GroupingSets) -> str:
    2051        grouping_sets = self.expressions(expression, indent=False)
    2052        return f"GROUPING SETS {self.wrap(grouping_sets)}"
    2053
    2054    def rollup_sql(self, expression: exp.Rollup) -> str:
    2055        expressions = self.expressions(expression, indent=False)
    2056        return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP"
    2057
    2058    def cube_sql(self, expression: exp.Cube) -> str:
    2059        expressions = self.expressions(expression, indent=False)
    2060        return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE"
    2061
    2062    def group_sql(self, expression: exp.Group) -> str:
    2063        group_by_all = expression.args.get("all")
    2064        if group_by_all is True:
    2065            modifier = " ALL"
    2066        elif group_by_all is False:
    2067            modifier = " DISTINCT"
    2068        else:
    2069            modifier = ""
    2070
    2071        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
    2072
    2073        grouping_sets = self.expressions(expression, key="grouping_sets")
    2074        cube = self.expressions(expression, key="cube")
    2075        rollup = self.expressions(expression, key="rollup")
    2076
    2077        groupings = csv(
    2078            self.seg(grouping_sets) if grouping_sets else "",
    2079            self.seg(cube) if cube else "",
    2080            self.seg(rollup) if rollup else "",
    2081            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    2082            sep=self.GROUPINGS_SEP,
    2083        )
    2084
    2085        if (
    2086            expression.expressions
    2087            and groupings
    2088            and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP")
    2089        ):
    2090            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    2091
    2092        return f"{group_by}{groupings}"
    2093
    2094    def having_sql(self, expression: exp.Having) -> str:
    2095        this = self.indent(self.sql(expression, "this"))
    2096        return f"{self.seg('HAVING')}{self.sep()}{this}"
    2097
    2098    def connect_sql(self, expression: exp.Connect) -> str:
    2099        start = self.sql(expression, "start")
    2100        start = self.seg(f"START WITH {start}") if start else ""
    2101        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
    2102        connect = self.sql(expression, "connect")
    2103        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
    2104        return start + connect
    2105
    2106    def prior_sql(self, expression: exp.Prior) -> str:
    2107        return f"PRIOR {self.sql(expression, 'this')}"
    2108
    2109    def join_sql(self, expression: exp.Join) -> str:
    2110        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    2111            side = None
    2112        else:
    2113            side = expression.side
    2114
    2115        op_sql = " ".join(
    2116            op
    2117            for op in (
    2118                expression.method,
    2119                "GLOBAL" if expression.args.get("global") else None,
    2120                side,
    2121                expression.kind,
    2122                expression.hint if self.JOIN_HINTS else None,
    2123            )
    2124            if op
    2125        )
    2126        match_cond = self.sql(expression, "match_condition")
    2127        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
    2128        on_sql = self.sql(expression, "on")
    2129        using = expression.args.get("using")
    2130
    2131        if not on_sql and using:
    2132            on_sql = csv(*(self.sql(column) for column in using))
    2133
    2134        this = expression.this
    2135        this_sql = self.sql(this)
    2136
    2137        if on_sql:
    2138            on_sql = self.indent(on_sql, skip_first=True)
    2139            space = self.seg(" " * self.pad) if self.pretty else " "
    2140            if using:
    2141                on_sql = f"{space}USING ({on_sql})"
    2142            else:
    2143                on_sql = f"{space}ON {on_sql}"
    2144        elif not op_sql:
    2145            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
    2146                return f" {this_sql}"
    2147
    2148            return f", {this_sql}"
    2149
    2150        if op_sql != "STRAIGHT_JOIN":
    2151            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    2152
    2153        return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}"
    2154
    2155    def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str:
    2156        args = self.expressions(expression, flat=True)
    2157        args = f"({args})" if len(args.split(",")) > 1 else args
    2158        return f"{args} {arrow_sep} {self.sql(expression, 'this')}"
    2159
    2160    def lateral_op(self, expression: exp.Lateral) -> str:
    2161        cross_apply = expression.args.get("cross_apply")
    2162
    2163        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    2164        if cross_apply is True:
    2165            op = "INNER JOIN "
    2166        elif cross_apply is False:
    2167            op = "LEFT JOIN "
    2168        else:
    2169            op = ""
    2170
    2171        return f"{op}LATERAL"
    2172
    2173    def lateral_sql(self, expression: exp.Lateral) -> str:
    2174        this = self.sql(expression, "this")
    2175
    2176        if expression.args.get("view"):
    2177            alias = expression.args["alias"]
    2178            columns = self.expressions(alias, key="columns", flat=True)
    2179            table = f" {alias.name}" if alias.name else ""
    2180            columns = f" AS {columns}" if columns else ""
    2181            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    2182            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    2183
    2184        alias = self.sql(expression, "alias")
    2185        alias = f" AS {alias}" if alias else ""
    2186        return f"{self.lateral_op(expression)} {this}{alias}"
    2187
    2188    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    2189        this = self.sql(expression, "this")
    2190
    2191        args = [
    2192            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    2193            for e in (expression.args.get(k) for k in ("offset", "expression"))
    2194            if e
    2195        ]
    2196
    2197        args_sql = ", ".join(self.sql(e) for e in args)
    2198        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
    2199        expressions = self.expressions(expression, flat=True)
    2200        expressions = f" BY {expressions}" if expressions else ""
    2201
    2202        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}"
    2203
    2204    def offset_sql(self, expression: exp.Offset) -> str:
    2205        this = self.sql(expression, "this")
    2206        value = expression.expression
    2207        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    2208        expressions = self.expressions(expression, flat=True)
    2209        expressions = f" BY {expressions}" if expressions else ""
    2210        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"
    2211
    2212    def setitem_sql(self, expression: exp.SetItem) -> str:
    2213        kind = self.sql(expression, "kind")
    2214        kind = f"{kind} " if kind else ""
    2215        this = self.sql(expression, "this")
    2216        expressions = self.expressions(expression)
    2217        collate = self.sql(expression, "collate")
    2218        collate = f" COLLATE {collate}" if collate else ""
    2219        global_ = "GLOBAL " if expression.args.get("global") else ""
    2220        return f"{global_}{kind}{this}{expressions}{collate}"
    2221
    2222    def set_sql(self, expression: exp.Set) -> str:
    2223        expressions = (
    2224            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    2225        )
    2226        tag = " TAG" if expression.args.get("tag") else ""
    2227        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"
    2228
    2229    def pragma_sql(self, expression: exp.Pragma) -> str:
    2230        return f"PRAGMA {self.sql(expression, 'this')}"
    2231
    2232    def lock_sql(self, expression: exp.Lock) -> str:
    2233        if not self.LOCKING_READS_SUPPORTED:
    2234            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    2235            return ""
    2236
    2237        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    2238        expressions = self.expressions(expression, flat=True)
    2239        expressions = f" OF {expressions}" if expressions else ""
    2240        wait = expression.args.get("wait")
    2241
    2242        if wait is not None:
    2243            if isinstance(wait, exp.Literal):
    2244                wait = f" WAIT {self.sql(wait)}"
    2245            else:
    2246                wait = " NOWAIT" if wait else " SKIP LOCKED"
    2247
    2248        return f"{lock_type}{expressions}{wait or ''}"
    2249
    2250    def literal_sql(self, expression: exp.Literal) -> str:
    2251        text = expression.this or ""
    2252        if expression.is_string:
    2253            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    2254        return text
    2255
    2256    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
    2257        if self.dialect.ESCAPED_SEQUENCES:
    2258            to_escaped = self.dialect.ESCAPED_SEQUENCES
    2259            text = "".join(
    2260                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
    2261            )
    2262
    2263        return self._replace_line_breaks(text).replace(
    2264            self.dialect.QUOTE_END, self._escaped_quote_end
    2265        )
    2266
    2267    def loaddata_sql(self, expression: exp.LoadData) -> str:
    2268        local = " LOCAL" if expression.args.get("local") else ""
    2269        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    2270        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    2271        this = f" INTO TABLE {self.sql(expression, 'this')}"
    2272        partition = self.sql(expression, "partition")
    2273        partition = f" {partition}" if partition else ""
    2274        input_format = self.sql(expression, "input_format")
    2275        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    2276        serde = self.sql(expression, "serde")
    2277        serde = f" SERDE {serde}" if serde else ""
    2278        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
    2279
    2280    def null_sql(self, *_) -> str:
    2281        return "NULL"
    2282
    2283    def boolean_sql(self, expression: exp.Boolean) -> str:
    2284        return "TRUE" if expression.this else "FALSE"
    2285
    2286    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2287        this = self.sql(expression, "this")
    2288        this = f"{this} " if this else this
    2289        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2290        return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat)  # type: ignore
    2291
    2292    def withfill_sql(self, expression: exp.WithFill) -> str:
    2293        from_sql = self.sql(expression, "from")
    2294        from_sql = f" FROM {from_sql}" if from_sql else ""
    2295        to_sql = self.sql(expression, "to")
    2296        to_sql = f" TO {to_sql}" if to_sql else ""
    2297        step_sql = self.sql(expression, "step")
    2298        step_sql = f" STEP {step_sql}" if step_sql else ""
    2299        interpolated_values = [
    2300            f"{self.sql(named_expression, 'alias')} AS {self.sql(named_expression, 'this')}"
    2301            for named_expression in expression.args.get("interpolate") or []
    2302        ]
    2303        interpolate = (
    2304            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    2305        )
    2306        return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"
    2307
    2308    def cluster_sql(self, expression: exp.Cluster) -> str:
    2309        return self.op_expressions("CLUSTER BY", expression)
    2310
    2311    def distribute_sql(self, expression: exp.Distribute) -> str:
    2312        return self.op_expressions("DISTRIBUTE BY", expression)
    2313
    2314    def sort_sql(self, expression: exp.Sort) -> str:
    2315        return self.op_expressions("SORT BY", expression)
    2316
    2317    def ordered_sql(self, expression: exp.Ordered) -> str:
    2318        desc = expression.args.get("desc")
    2319        asc = not desc
    2320
    2321        nulls_first = expression.args.get("nulls_first")
    2322        nulls_last = not nulls_first
    2323        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
    2324        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
    2325        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
    2326
    2327        this = self.sql(expression, "this")
    2328
    2329        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
    2330        nulls_sort_change = ""
    2331        if nulls_first and (
    2332            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    2333        ):
    2334            nulls_sort_change = " NULLS FIRST"
    2335        elif (
    2336            nulls_last
    2337            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    2338            and not nulls_are_last
    2339        ):
    2340            nulls_sort_change = " NULLS LAST"
    2341
    2342        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
    2343        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    2344            window = expression.find_ancestor(exp.Window, exp.Select)
    2345            if isinstance(window, exp.Window) and window.args.get("spec"):
    2346                self.unsupported(
    2347                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
    2348                )
    2349                nulls_sort_change = ""
    2350            elif self.NULL_ORDERING_SUPPORTED is None:
    2351                if expression.this.is_int:
    2352                    self.unsupported(
    2353                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
    2354                    )
    2355                elif not isinstance(expression.this, exp.Rand):
    2356                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
    2357                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
    2358                nulls_sort_change = ""
    2359
    2360        with_fill = self.sql(expression, "with_fill")
    2361        with_fill = f" {with_fill}" if with_fill else ""
    2362
    2363        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"
    2364
    2365    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
    2366        window_frame = self.sql(expression, "window_frame")
    2367        window_frame = f"{window_frame} " if window_frame else ""
    2368
    2369        this = self.sql(expression, "this")
    2370
    2371        return f"{window_frame}{this}"
    2372
    2373    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    2374        partition = self.partition_by_sql(expression)
    2375        order = self.sql(expression, "order")
    2376        measures = self.expressions(expression, key="measures")
    2377        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    2378        rows = self.sql(expression, "rows")
    2379        rows = self.seg(rows) if rows else ""
    2380        after = self.sql(expression, "after")
    2381        after = self.seg(after) if after else ""
    2382        pattern = self.sql(expression, "pattern")
    2383        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    2384        definition_sqls = [
    2385            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    2386            for definition in expression.args.get("define", [])
    2387        ]
    2388        definitions = self.expressions(sqls=definition_sqls)
    2389        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    2390        body = "".join(
    2391            (
    2392                partition,
    2393                order,
    2394                measures,
    2395                rows,
    2396                after,
    2397                pattern,
    2398                define,
    2399            )
    2400        )
    2401        alias = self.sql(expression, "alias")
    2402        alias = f" {alias}" if alias else ""
    2403        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
    2404
    2405    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    2406        limit = expression.args.get("limit")
    2407
    2408        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    2409            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    2410        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    2411            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    2412
    2413        return csv(
    2414            *sqls,
    2415            *[self.sql(join) for join in expression.args.get("joins") or []],
    2416            self.sql(expression, "connect"),
    2417            self.sql(expression, "match"),
    2418            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2419            self.sql(expression, "prewhere"),
    2420            self.sql(expression, "where"),
    2421            self.sql(expression, "group"),
    2422            self.sql(expression, "having"),
    2423            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
    2424            self.sql(expression, "order"),
    2425            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
    2426            *self.after_limit_modifiers(expression),
    2427            self.options_modifier(expression),
    2428            sep="",
    2429        )
    2430
    2431    def options_modifier(self, expression: exp.Expression) -> str:
    2432        options = self.expressions(expression, key="options")
    2433        return f" {options}" if options else ""
    2434
    2435    def queryoption_sql(self, expression: exp.QueryOption) -> str:
    2436        return ""
    2437
    2438    def offset_limit_modifiers(
    2439        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2440    ) -> t.List[str]:
    2441        return [
    2442            self.sql(expression, "offset") if fetch else self.sql(limit),
    2443            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2444        ]
    2445
    2446    def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
    2447        locks = self.expressions(expression, key="locks", sep=" ")
    2448        locks = f" {locks}" if locks else ""
    2449        return [locks, self.sql(expression, "sample")]
    2450
    2451    def select_sql(self, expression: exp.Select) -> str:
    2452        into = expression.args.get("into")
    2453        if not self.SUPPORTS_SELECT_INTO and into:
    2454            into.pop()
    2455
    2456        hint = self.sql(expression, "hint")
    2457        distinct = self.sql(expression, "distinct")
    2458        distinct = f" {distinct}" if distinct else ""
    2459        kind = self.sql(expression, "kind")
    2460
    2461        limit = expression.args.get("limit")
    2462        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
    2463            top = self.limit_sql(limit, top=True)
    2464            limit.pop()
    2465        else:
    2466            top = ""
    2467
    2468        expressions = self.expressions(expression)
    2469
    2470        if kind:
    2471            if kind in self.SELECT_KINDS:
    2472                kind = f" AS {kind}"
    2473            else:
    2474                if kind == "STRUCT":
    2475                    expressions = self.expressions(
    2476                        sqls=[
    2477                            self.sql(
    2478                                exp.Struct(
    2479                                    expressions=[
    2480                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
    2481                                        if isinstance(e, exp.Alias)
    2482                                        else e
    2483                                        for e in expression.expressions
    2484                                    ]
    2485                                )
    2486                            )
    2487                        ]
    2488                    )
    2489                kind = ""
    2490
    2491        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
    2492        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
    2493        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
    2494        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    2495        sql = self.query_modifiers(
    2496            expression,
    2497            f"SELECT{top_distinct}{kind}{expressions}",
    2498            self.sql(expression, "into", comment=False),
    2499            self.sql(expression, "from", comment=False),
    2500        )
    2501
    2502        sql = self.prepend_ctes(expression, sql)
    2503
    2504        if not self.SUPPORTS_SELECT_INTO and into:
    2505            if into.args.get("temporary"):
    2506                table_kind = " TEMPORARY"
    2507            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
    2508                table_kind = " UNLOGGED"
    2509            else:
    2510                table_kind = ""
    2511            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
    2512
    2513        return sql
    2514
    2515    def schema_sql(self, expression: exp.Schema) -> str:
    2516        this = self.sql(expression, "this")
    2517        sql = self.schema_columns_sql(expression)
    2518        return f"{this} {sql}" if this and sql else this or sql
    2519
    2520    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2521        if expression.expressions:
    2522            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2523        return ""
    2524
    2525    def star_sql(self, expression: exp.Star) -> str:
    2526        except_ = self.expressions(expression, key="except", flat=True)
    2527        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
    2528        replace = self.expressions(expression, key="replace", flat=True)
    2529        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
    2530        rename = self.expressions(expression, key="rename", flat=True)
    2531        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
    2532        return f"*{except_}{replace}{rename}"
    2533
    2534    def parameter_sql(self, expression: exp.Parameter) -> str:
    2535        this = self.sql(expression, "this")
    2536        return f"{self.PARAMETER_TOKEN}{this}"
    2537
    2538    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2539        this = self.sql(expression, "this")
    2540        kind = expression.text("kind")
    2541        if kind:
    2542            kind = f"{kind}."
    2543        return f"@@{kind}{this}"
    2544
    2545    def placeholder_sql(self, expression: exp.Placeholder) -> str:
    2546        return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?"
    2547
    2548    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2549        alias = self.sql(expression, "alias")
    2550        alias = f"{sep}{alias}" if alias else ""
    2551        sample = self.sql(expression, "sample")
    2552        if self.dialect.ALIAS_POST_TABLESAMPLE and sample:
    2553            alias = f"{sample}{alias}"
    2554
    2555            # Set to None so it's not generated again by self.query_modifiers()
    2556            expression.set("sample", None)
    2557
    2558        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2559        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2560        return self.prepend_ctes(expression, sql)
    2561
    2562    def qualify_sql(self, expression: exp.Qualify) -> str:
    2563        this = self.indent(self.sql(expression, "this"))
    2564        return f"{self.seg('QUALIFY')}{self.sep()}{this}"
    2565
    2566    def unnest_sql(self, expression: exp.Unnest) -> str:
    2567        args = self.expressions(expression, flat=True)
    2568
    2569        alias = expression.args.get("alias")
    2570        offset = expression.args.get("offset")
    2571
    2572        if self.UNNEST_WITH_ORDINALITY:
    2573            if alias and isinstance(offset, exp.Expression):
    2574                alias.append("columns", offset)
    2575
    2576        if alias and self.dialect.UNNEST_COLUMN_ONLY:
    2577            columns = alias.columns
    2578            alias = self.sql(columns[0]) if columns else ""
    2579        else:
    2580            alias = self.sql(alias)
    2581
    2582        alias = f" AS {alias}" if alias else alias
    2583        if self.UNNEST_WITH_ORDINALITY:
    2584            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2585        else:
    2586            if isinstance(offset, exp.Expression):
    2587                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2588            elif offset:
    2589                suffix = f"{alias} WITH OFFSET"
    2590            else:
    2591                suffix = alias
    2592
    2593        return f"UNNEST({args}){suffix}"
    2594
    2595    def prewhere_sql(self, expression: exp.PreWhere) -> str:
    2596        return ""
    2597
    2598    def where_sql(self, expression: exp.Where) -> str:
    2599        this = self.indent(self.sql(expression, "this"))
    2600        return f"{self.seg('WHERE')}{self.sep()}{this}"
    2601
    2602    def window_sql(self, expression: exp.Window) -> str:
    2603        this = self.sql(expression, "this")
    2604        partition = self.partition_by_sql(expression)
    2605        order = expression.args.get("order")
    2606        order = self.order_sql(order, flat=True) if order else ""
    2607        spec = self.sql(expression, "spec")
    2608        alias = self.sql(expression, "alias")
    2609        over = self.sql(expression, "over") or "OVER"
    2610
    2611        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2612
    2613        first = expression.args.get("first")
    2614        if first is None:
    2615            first = ""
    2616        else:
    2617            first = "FIRST" if first else "LAST"
    2618
    2619        if not partition and not order and not spec and alias:
    2620            return f"{this} {alias}"
    2621
    2622        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    2623        return f"{this} ({args})"
    2624
    2625    def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str:
    2626        partition = self.expressions(expression, key="partition_by", flat=True)
    2627        return f"PARTITION BY {partition}" if partition else ""
    2628
    2629    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2630        kind = self.sql(expression, "kind")
    2631        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2632        end = (
    2633            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2634            or "CURRENT ROW"
    2635        )
    2636        return f"{kind} BETWEEN {start} AND {end}"
    2637
    2638    def withingroup_sql(self, expression: exp.WithinGroup) -> str:
    2639        this = self.sql(expression, "this")
    2640        expression_sql = self.sql(expression, "expression")[1:]  # order has a leading space
    2641        return f"{this} WITHIN GROUP ({expression_sql})"
    2642
    2643    def between_sql(self, expression: exp.Between) -> str:
    2644        this = self.sql(expression, "this")
    2645        low = self.sql(expression, "low")
    2646        high = self.sql(expression, "high")
    2647        return f"{this} BETWEEN {low} AND {high}"
    2648
    2649    def bracket_offset_expressions(self, expression: exp.Bracket) -> t.List[exp.Expression]:
    2650        return apply_index_offset(
    2651            expression.this,
    2652            expression.expressions,
    2653            self.dialect.INDEX_OFFSET - expression.args.get("offset", 0),
    2654        )
    2655
    2656    def bracket_sql(self, expression: exp.Bracket) -> str:
    2657        expressions = self.bracket_offset_expressions(expression)
    2658        expressions_sql = ", ".join(self.sql(e) for e in expressions)
    2659        return f"{self.sql(expression, 'this')}[{expressions_sql}]"
    2660
    2661    def all_sql(self, expression: exp.All) -> str:
    2662        return f"ALL {self.wrap(expression)}"
    2663
    2664    def any_sql(self, expression: exp.Any) -> str:
    2665        this = self.sql(expression, "this")
    2666        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
    2667            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2668                this = self.wrap(this)
    2669            return f"ANY{this}"
    2670        return f"ANY {this}"
    2671
    2672    def exists_sql(self, expression: exp.Exists) -> str:
    2673        return f"EXISTS{self.wrap(expression)}"
    2674
    2675    def case_sql(self, expression: exp.Case) -> str:
    2676        this = self.sql(expression, "this")
    2677        statements = [f"CASE {this}" if this else "CASE"]
    2678
    2679        for e in expression.args["ifs"]:
    2680            statements.append(f"WHEN {self.sql(e, 'this')}")
    2681            statements.append(f"THEN {self.sql(e, 'true')}")
    2682
    2683        default = self.sql(expression, "default")
    2684
    2685        if default:
    2686            statements.append(f"ELSE {default}")
    2687
    2688        statements.append("END")
    2689
    2690        if self.pretty and self.too_wide(statements):
    2691            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2692
    2693        return " ".join(statements)
    2694
    2695    def constraint_sql(self, expression: exp.Constraint) -> str:
    2696        this = self.sql(expression, "this")
    2697        expressions = self.expressions(expression, flat=True)
    2698        return f"CONSTRAINT {this} {expressions}"
    2699
    2700    def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str:
    2701        order = expression.args.get("order")
    2702        order = f" OVER ({self.order_sql(order, flat=True)})" if order else ""
    2703        return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}"
    2704
    2705    def extract_sql(self, expression: exp.Extract) -> str:
    2706        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2707        expression_sql = self.sql(expression, "expression")
    2708        return f"EXTRACT({this} FROM {expression_sql})"
    2709
    2710    def trim_sql(self, expression: exp.Trim) -> str:
    2711        trim_type = self.sql(expression, "position")
    2712
    2713        if trim_type == "LEADING":
    2714            func_name = "LTRIM"
    2715        elif trim_type == "TRAILING":
    2716            func_name = "RTRIM"
    2717        else:
    2718            func_name = "TRIM"
    2719
    2720        return self.func(func_name, expression.this, expression.expression)
    2721
    2722    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2723        args = expression.expressions
    2724        if isinstance(expression, exp.ConcatWs):
    2725            args = args[1:]  # Skip the delimiter
    2726
    2727        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2728            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
    2729
    2730        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2731            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2732
    2733        return args
    2734
    2735    def concat_sql(self, expression: exp.Concat) -> str:
    2736        expressions = self.convert_concat_args(expression)
    2737
    2738        # Some dialects don't allow a single-argument CONCAT call
    2739        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2740            return self.sql(expressions[0])
    2741
    2742        return self.func("CONCAT", *expressions)
    2743
    2744    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2745        return self.func(
    2746            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2747        )
    2748
    2749    def check_sql(self, expression: exp.Check) -> str:
    2750        this = self.sql(expression, key="this")
    2751        return f"CHECK ({this})"
    2752
    2753    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2754        expressions = self.expressions(expression, flat=True)
    2755        reference = self.sql(expression, "reference")
    2756        reference = f" {reference}" if reference else ""
    2757        delete = self.sql(expression, "delete")
    2758        delete = f" ON DELETE {delete}" if delete else ""
    2759        update = self.sql(expression, "update")
    2760        update = f" ON UPDATE {update}" if update else ""
    2761        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"
    2762
    2763    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2764        expressions = self.expressions(expression, flat=True)
    2765        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2766        options = f" {options}" if options else ""
    2767        return f"PRIMARY KEY ({expressions}){options}"
    2768
    2769    def if_sql(self, expression: exp.If) -> str:
    2770        return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false")))
    2771
    2772    def matchagainst_sql(self, expression: exp.MatchAgainst) -> str:
    2773        modifier = expression.args.get("modifier")
    2774        modifier = f" {modifier}" if modifier else ""
    2775        return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})"
    2776
    2777    def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str:
    2778        return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}"
    2779
    2780    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
    2781        path = self.expressions(expression, sep="", flat=True).lstrip(".")
    2782
    2783        if expression.args.get("escape"):
    2784            path = self.escape_str(path)
    2785
    2786        if self.QUOTE_JSON_PATH:
    2787            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
    2788
    2789        return path
    2790
    2791    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
    2792        if isinstance(expression, exp.JSONPathPart):
    2793            transform = self.TRANSFORMS.get(expression.__class__)
    2794            if not callable(transform):
    2795                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
    2796                return ""
    2797
    2798            return transform(self, expression)
    2799
    2800        if isinstance(expression, int):
    2801            return str(expression)
    2802
    2803        if self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
    2804            escaped = expression.replace("'", "\\'")
    2805            escaped = f"\\'{expression}\\'"
    2806        else:
    2807            escaped = expression.replace('"', '\\"')
    2808            escaped = f'"{escaped}"'
    2809
    2810        return escaped
    2811
    2812    def formatjson_sql(self, expression: exp.FormatJson) -> str:
    2813        return f"{self.sql(expression, 'this')} FORMAT JSON"
    2814
    2815    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    2816        null_handling = expression.args.get("null_handling")
    2817        null_handling = f" {null_handling}" if null_handling else ""
    2818
    2819        unique_keys = expression.args.get("unique_keys")
    2820        if unique_keys is not None:
    2821            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2822        else:
    2823            unique_keys = ""
    2824
    2825        return_type = self.sql(expression, "return_type")
    2826        return_type = f" RETURNING {return_type}" if return_type else ""
    2827        encoding = self.sql(expression, "encoding")
    2828        encoding = f" ENCODING {encoding}" if encoding else ""
    2829
    2830        return self.func(
    2831            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    2832            *expression.expressions,
    2833            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2834        )
    2835
    2836    def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str:
    2837        return self.jsonobject_sql(expression)
    2838
    2839    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2840        null_handling = expression.args.get("null_handling")
    2841        null_handling = f" {null_handling}" if null_handling else ""
    2842        return_type = self.sql(expression, "return_type")
    2843        return_type = f" RETURNING {return_type}" if return_type else ""
    2844        strict = " STRICT" if expression.args.get("strict") else ""
    2845        return self.func(
    2846            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2847        )
    2848
    2849    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2850        this = self.sql(expression, "this")
    2851        order = self.sql(expression, "order")
    2852        null_handling = expression.args.get("null_handling")
    2853        null_handling = f" {null_handling}" if null_handling else ""
    2854        return_type = self.sql(expression, "return_type")
    2855        return_type = f" RETURNING {return_type}" if return_type else ""
    2856        strict = " STRICT" if expression.args.get("strict") else ""
    2857        return self.func(
    2858            "JSON_ARRAYAGG",
    2859            this,
    2860            suffix=f"{order}{null_handling}{return_type}{strict})",
    2861        )
    2862
    2863    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2864        path = self.sql(expression, "path")
    2865        path = f" PATH {path}" if path else ""
    2866        nested_schema = self.sql(expression, "nested_schema")
    2867
    2868        if nested_schema:
    2869            return f"NESTED{path} {nested_schema}"
    2870
    2871        this = self.sql(expression, "this")
    2872        kind = self.sql(expression, "kind")
    2873        kind = f" {kind}" if kind else ""
    2874        return f"{this}{kind}{path}"
    2875
    2876    def jsonschema_sql(self, expression: exp.JSONSchema) -> str:
    2877        return self.func("COLUMNS", *expression.expressions)
    2878
    2879    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    2880        this = self.sql(expression, "this")
    2881        path = self.sql(expression, "path")
    2882        path = f", {path}" if path else ""
    2883        error_handling = expression.args.get("error_handling")
    2884        error_handling = f" {error_handling}" if error_handling else ""
    2885        empty_handling = expression.args.get("empty_handling")
    2886        empty_handling = f" {empty_handling}" if empty_handling else ""
    2887        schema = self.sql(expression, "schema")
    2888        return self.func(
    2889            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    2890        )
    2891
    2892    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    2893        this = self.sql(expression, "this")
    2894        kind = self.sql(expression, "kind")
    2895        path = self.sql(expression, "path")
    2896        path = f" {path}" if path else ""
    2897        as_json = " AS JSON" if expression.args.get("as_json") else ""
    2898        return f"{this} {kind}{path}{as_json}"
    2899
    2900    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    2901        this = self.sql(expression, "this")
    2902        path = self.sql(expression, "path")
    2903        path = f", {path}" if path else ""
    2904        expressions = self.expressions(expression)
    2905        with_ = (
    2906            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2907            if expressions
    2908            else ""
    2909        )
    2910        return f"OPENJSON({this}{path}){with_}"
    2911
    2912    def in_sql(self, expression: exp.In) -> str:
    2913        query = expression.args.get("query")
    2914        unnest = expression.args.get("unnest")
    2915        field = expression.args.get("field")
    2916        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    2917
    2918        if query:
    2919            in_sql = self.sql(query)
    2920        elif unnest:
    2921            in_sql = self.in_unnest_op(unnest)
    2922        elif field:
    2923            in_sql = self.sql(field)
    2924        else:
    2925            in_sql = f"({self.expressions(expression, flat=True)})"
    2926
    2927        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
    2928
    2929    def in_unnest_op(self, unnest: exp.Unnest) -> str:
    2930        return f"(SELECT {self.sql(unnest)})"
    2931
    2932    def interval_sql(self, expression: exp.Interval) -> str:
    2933        unit = self.sql(expression, "unit")
    2934        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    2935            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    2936        unit = f" {unit}" if unit else ""
    2937
    2938        if self.SINGLE_STRING_INTERVAL:
    2939            this = expression.this.name if expression.this else ""
    2940            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    2941
    2942        this = self.sql(expression, "this")
    2943        if this:
    2944            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    2945            this = f" {this}" if unwrapped else f" ({this})"
    2946
    2947        return f"INTERVAL{this}{unit}"
    2948
    2949    def return_sql(self, expression: exp.Return) -> str:
    2950        return f"RETURN {self.sql(expression, 'this')}"
    2951
    2952    def reference_sql(self, expression: exp.Reference) -> str:
    2953        this = self.sql(expression, "this")
    2954        expressions = self.expressions(expression, flat=True)
    2955        expressions = f"({expressions})" if expressions else ""
    2956        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2957        options = f" {options}" if options else ""
    2958        return f"REFERENCES {this}{expressions}{options}"
    2959
    2960    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    2961        # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive
    2962        parent = expression.parent
    2963        is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression
    2964        return self.func(
    2965            self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified
    2966        )
    2967
    2968    def paren_sql(self, expression: exp.Paren) -> str:
    2969        sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
    2970        return f"({sql}{self.seg(')', sep='')}"
    2971
    2972    def neg_sql(self, expression: exp.Neg) -> str:
    2973        # This makes sure we don't convert "- - 5" to "--5", which is a comment
    2974        this_sql = self.sql(expression, "this")
    2975        sep = " " if this_sql[0] == "-" else ""
    2976        return f"-{sep}{this_sql}"
    2977
    2978    def not_sql(self, expression: exp.Not) -> str:
    2979        return f"NOT {self.sql(expression, 'this')}"
    2980
    2981    def alias_sql(self, expression: exp.Alias) -> str:
    2982        alias = self.sql(expression, "alias")
    2983        alias = f" AS {alias}" if alias else ""
    2984        return f"{self.sql(expression, 'this')}{alias}"
    2985
    2986    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    2987        alias = expression.args["alias"]
    2988
    2989        identifier_alias = isinstance(alias, exp.Identifier)
    2990        literal_alias = isinstance(alias, exp.Literal)
    2991
    2992        if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2993            alias.replace(exp.Literal.string(alias.output_name))
    2994        elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2995            alias.replace(exp.to_identifier(alias.output_name))
    2996
    2997        return self.alias_sql(expression)
    2998
    2999    def aliases_sql(self, expression: exp.Aliases) -> str:
    3000        return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})"
    3001
    3002    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    3003        this = self.sql(expression, "this")
    3004        index = self.sql(expression, "expression")
    3005        return f"{this} AT {index}"
    3006
    3007    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    3008        this = self.sql(expression, "this")
    3009        zone = self.sql(expression, "zone")
    3010        return f"{this} AT TIME ZONE {zone}"
    3011
    3012    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    3013        this = self.sql(expression, "this")
    3014        zone = self.sql(expression, "zone")
    3015        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"
    3016
    3017    def add_sql(self, expression: exp.Add) -> str:
    3018        return self.binary(expression, "+")
    3019
    3020    def and_sql(
    3021        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
    3022    ) -> str:
    3023        return self.connector_sql(expression, "AND", stack)
    3024
    3025    def or_sql(
    3026        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
    3027    ) -> str:
    3028        return self.connector_sql(expression, "OR", stack)
    3029
    3030    def xor_sql(
    3031        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
    3032    ) -> str:
    3033        return self.connector_sql(expression, "XOR", stack)
    3034
    3035    def connector_sql(
    3036        self,
    3037        expression: exp.Connector,
    3038        op: str,
    3039        stack: t.Optional[t.List[str | exp.Expression]] = None,
    3040    ) -> str:
    3041        if stack is not None:
    3042            if expression.expressions:
    3043                stack.append(self.expressions(expression, sep=f" {op} "))
    3044            else:
    3045                stack.append(expression.right)
    3046                if expression.comments and self.comments:
    3047                    for comment in expression.comments:
    3048                        if comment:
    3049                            op += f" /*{self.pad_comment(comment)}*/"
    3050                stack.extend((op, expression.left))
    3051            return op
    3052
    3053        stack = [expression]
    3054        sqls: t.List[str] = []
    3055        ops = set()
    3056
    3057        while stack:
    3058            node = stack.pop()
    3059            if isinstance(node, exp.Connector):
    3060                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
    3061            else:
    3062                sql = self.sql(node)
    3063                if sqls and sqls[-1] in ops:
    3064                    sqls[-1] += f" {sql}"
    3065                else:
    3066                    sqls.append(sql)
    3067
    3068        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
    3069        return sep.join(sqls)
    3070
    3071    def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str:
    3072        return self.binary(expression, "&")
    3073
    3074    def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str:
    3075        return self.binary(expression, "<<")
    3076
    3077    def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str:
    3078        return f"~{self.sql(expression, 'this')}"
    3079
    3080    def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str:
    3081        return self.binary(expression, "|")
    3082
    3083    def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str:
    3084        return self.binary(expression, ">>")
    3085
    3086    def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str:
    3087        return self.binary(expression, "^")
    3088
    3089    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    3090        format_sql = self.sql(expression, "format")
    3091        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    3092        to_sql = self.sql(expression, "to")
    3093        to_sql = f" {to_sql}" if to_sql else ""
    3094        action = self.sql(expression, "action")
    3095        action = f" {action}" if action else ""
    3096        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{format_sql}{action})"
    3097
    3098    def currentdate_sql(self, expression: exp.CurrentDate) -> str:
    3099        zone = self.sql(expression, "this")
    3100        return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE"
    3101
    3102    def collate_sql(self, expression: exp.Collate) -> str:
    3103        if self.COLLATE_IS_FUNC:
    3104            return self.function_fallback_sql(expression)
    3105        return self.binary(expression, "COLLATE")
    3106
    3107    def command_sql(self, expression: exp.Command) -> str:
    3108        return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}"
    3109
    3110    def comment_sql(self, expression: exp.Comment) -> str:
    3111        this = self.sql(expression, "this")
    3112        kind = expression.args["kind"]
    3113        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    3114        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    3115        expression_sql = self.sql(expression, "expression")
    3116        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"
    3117
    3118    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    3119        this = self.sql(expression, "this")
    3120        delete = " DELETE" if expression.args.get("delete") else ""
    3121        recompress = self.sql(expression, "recompress")
    3122        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    3123        to_disk = self.sql(expression, "to_disk")
    3124        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    3125        to_volume = self.sql(expression, "to_volume")
    3126        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    3127        return f"{this}{delete}{recompress}{to_disk}{to_volume}"
    3128
    3129    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    3130        where = self.sql(expression, "where")
    3131        group = self.sql(expression, "group")
    3132        aggregates = self.expressions(expression, key="aggregates")
    3133        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    3134
    3135        if not (where or group or aggregates) and len(expression.expressions) == 1:
    3136            return f"TTL {self.expressions(expression, flat=True)}"
    3137
    3138        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
    3139
    3140    def transaction_sql(self, expression: exp.Transaction) -> str:
    3141        return "BEGIN"
    3142
    3143    def commit_sql(self, expression: exp.Commit) -> str:
    3144        chain = expression.args.get("chain")
    3145        if chain is not None:
    3146            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    3147
    3148        return f"COMMIT{chain or ''}"
    3149
    3150    def rollback_sql(self, expression: exp.Rollback) -> str:
    3151        savepoint = expression.args.get("savepoint")
    3152        savepoint = f" TO {savepoint}" if savepoint else ""
    3153        return f"ROLLBACK{savepoint}"
    3154
    3155    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    3156        this = self.sql(expression, "this")
    3157
    3158        dtype = self.sql(expression, "dtype")
    3159        if dtype:
    3160            collate = self.sql(expression, "collate")
    3161            collate = f" COLLATE {collate}" if collate else ""
    3162            using = self.sql(expression, "using")
    3163            using = f" USING {using}" if using else ""
    3164            return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}"
    3165
    3166        default = self.sql(expression, "default")
    3167        if default:
    3168            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    3169
    3170        comment = self.sql(expression, "comment")
    3171        if comment:
    3172            return f"ALTER COLUMN {this} COMMENT {comment}"
    3173
    3174        allow_null = expression.args.get("allow_null")
    3175        drop = expression.args.get("drop")
    3176
    3177        if not drop and not allow_null:
    3178            self.unsupported("Unsupported ALTER COLUMN syntax")
    3179
    3180        if allow_null is not None:
    3181            keyword = "DROP" if drop else "SET"
    3182            return f"ALTER COLUMN {this} {keyword} NOT NULL"
    3183
    3184        return f"ALTER COLUMN {this} DROP DEFAULT"
    3185
    3186    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
    3187        this = self.sql(expression, "this")
    3188        if not isinstance(expression.this, exp.Var):
    3189            this = f"KEY DISTKEY {this}"
    3190        return f"ALTER DISTSTYLE {this}"
    3191
    3192    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
    3193        compound = " COMPOUND" if expression.args.get("compound") else ""
    3194        this = self.sql(expression, "this")
    3195        expressions = self.expressions(expression, flat=True)
    3196        expressions = f"({expressions})" if expressions else ""
    3197        return f"ALTER{compound} SORTKEY {this or expressions}"
    3198
    3199    def renametable_sql(self, expression: exp.RenameTable) -> str:
    3200        if not self.RENAME_TABLE_WITH_DB:
    3201            # Remove db from tables
    3202            expression = expression.transform(
    3203                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    3204            ).assert_is(exp.RenameTable)
    3205        this = self.sql(expression, "this")
    3206        return f"RENAME TO {this}"
    3207
    3208    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    3209        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3210        old_column = self.sql(expression, "this")
    3211        new_column = self.sql(expression, "to")
    3212        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"
    3213
    3214    def alterset_sql(self, expression: exp.AlterSet) -> str:
    3215        exprs = self.expressions(expression, flat=True)
    3216        return f"SET {exprs}"
    3217
    3218    def alter_sql(self, expression: exp.Alter) -> str:
    3219        actions = expression.args["actions"]
    3220
    3221        if isinstance(actions[0], exp.ColumnDef):
    3222            actions = self.add_column_sql(expression)
    3223        elif isinstance(actions[0], exp.Schema):
    3224            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    3225        elif isinstance(actions[0], exp.Delete):
    3226            actions = self.expressions(expression, key="actions", flat=True)
    3227        elif isinstance(actions[0], exp.Query):
    3228            actions = "AS " + self.expressions(expression, key="actions")
    3229        else:
    3230            actions = self.expressions(expression, key="actions", flat=True)
    3231
    3232        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3233        on_cluster = self.sql(expression, "cluster")
    3234        on_cluster = f" {on_cluster}" if on_cluster else ""
    3235        only = " ONLY" if expression.args.get("only") else ""
    3236        options = self.expressions(expression, key="options")
    3237        options = f", {options}" if options else ""
    3238        kind = self.sql(expression, "kind")
    3239        not_valid = " NOT VALID" if expression.args.get("not_valid") else ""
    3240
    3241        return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}"
    3242
    3243    def add_column_sql(self, expression: exp.Alter) -> str:
    3244        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    3245            return self.expressions(
    3246                expression,
    3247                key="actions",
    3248                prefix="ADD COLUMN ",
    3249                skip_first=True,
    3250            )
    3251        return f"ADD {self.expressions(expression, key='actions', flat=True)}"
    3252
    3253    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    3254        expressions = self.expressions(expression)
    3255        exists = " IF EXISTS " if expression.args.get("exists") else " "
    3256        return f"DROP{exists}{expressions}"
    3257
    3258    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
    3259        return f"ADD {self.expressions(expression)}"
    3260
    3261    def distinct_sql(self, expression: exp.Distinct) -> str:
    3262        this = self.expressions(expression, flat=True)
    3263
    3264        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    3265            case = exp.case()
    3266            for arg in expression.expressions:
    3267                case = case.when(arg.is_(exp.null()), exp.null())
    3268            this = self.sql(case.else_(f"({this})"))
    3269
    3270        this = f" {this}" if this else ""
    3271
    3272        on = self.sql(expression, "on")
    3273        on = f" ON {on}" if on else ""
    3274        return f"DISTINCT{this}{on}"
    3275
    3276    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
    3277        return self._embed_ignore_nulls(expression, "IGNORE NULLS")
    3278
    3279    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
    3280        return self._embed_ignore_nulls(expression, "RESPECT NULLS")
    3281
    3282    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    3283        this_sql = self.sql(expression, "this")
    3284        expression_sql = self.sql(expression, "expression")
    3285        kind = "MAX" if expression.args.get("max") else "MIN"
    3286        return f"{this_sql} HAVING {kind} {expression_sql}"
    3287
    3288    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    3289        return self.sql(
    3290            exp.Cast(
    3291                this=exp.Div(this=expression.this, expression=expression.expression),
    3292                to=exp.DataType(this=exp.DataType.Type.INT),
    3293            )
    3294        )
    3295
    3296    def dpipe_sql(self, expression: exp.DPipe) -> str:
    3297        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    3298            return self.func(
    3299                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
    3300            )
    3301        return self.binary(expression, "||")
    3302
    3303    def div_sql(self, expression: exp.Div) -> str:
    3304        l, r = expression.left, expression.right
    3305
    3306        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    3307            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    3308
    3309        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    3310            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
    3311                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    3312
    3313        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    3314            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    3315                return self.sql(
    3316                    exp.cast(
    3317                        l / r,
    3318                        to=exp.DataType.Type.BIGINT,
    3319                    )
    3320                )
    3321
    3322        return self.binary(expression, "/")
    3323
    3324    def overlaps_sql(self, expression: exp.Overlaps) -> str:
    3325        return self.binary(expression, "OVERLAPS")
    3326
    3327    def distance_sql(self, expression: exp.Distance) -> str:
    3328        return self.binary(expression, "<->")
    3329
    3330    def dot_sql(self, expression: exp.Dot) -> str:
    3331        return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}"
    3332
    3333    def eq_sql(self, expression: exp.EQ) -> str:
    3334        return self.binary(expression, "=")
    3335
    3336    def propertyeq_sql(self, expression: exp.PropertyEQ) -> str:
    3337        return self.binary(expression, ":=")
    3338
    3339    def escape_sql(self, expression: exp.Escape) -> str:
    3340        return self.binary(expression, "ESCAPE")
    3341
    3342    def glob_sql(self, expression: exp.Glob) -> str:
    3343        return self.binary(expression, "GLOB")
    3344
    3345    def gt_sql(self, expression: exp.GT) -> str:
    3346        return self.binary(expression, ">")
    3347
    3348    def gte_sql(self, expression: exp.GTE) -> str:
    3349        return self.binary(expression, ">=")
    3350
    3351    def ilike_sql(self, expression: exp.ILike) -> str:
    3352        return self.binary(expression, "ILIKE")
    3353
    3354    def ilikeany_sql(self, expression: exp.ILikeAny) -> str:
    3355        return self.binary(expression, "ILIKE ANY")
    3356
    3357    def is_sql(self, expression: exp.Is) -> str:
    3358        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3359            return self.sql(
    3360                expression.this if expression.expression.this else exp.not_(expression.this)
    3361            )
    3362        return self.binary(expression, "IS")
    3363
    3364    def like_sql(self, expression: exp.Like) -> str:
    3365        return self.binary(expression, "LIKE")
    3366
    3367    def likeany_sql(self, expression: exp.LikeAny) -> str:
    3368        return self.binary(expression, "LIKE ANY")
    3369
    3370    def similarto_sql(self, expression: exp.SimilarTo) -> str:
    3371        return self.binary(expression, "SIMILAR TO")
    3372
    3373    def lt_sql(self, expression: exp.LT) -> str:
    3374        return self.binary(expression, "<")
    3375
    3376    def lte_sql(self, expression: exp.LTE) -> str:
    3377        return self.binary(expression, "<=")
    3378
    3379    def mod_sql(self, expression: exp.Mod) -> str:
    3380        return self.binary(expression, "%")
    3381
    3382    def mul_sql(self, expression: exp.Mul) -> str:
    3383        return self.binary(expression, "*")
    3384
    3385    def neq_sql(self, expression: exp.NEQ) -> str:
    3386        return self.binary(expression, "<>")
    3387
    3388    def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str:
    3389        return self.binary(expression, "IS NOT DISTINCT FROM")
    3390
    3391    def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str:
    3392        return self.binary(expression, "IS DISTINCT FROM")
    3393
    3394    def slice_sql(self, expression: exp.Slice) -> str:
    3395        return self.binary(expression, ":")
    3396
    3397    def sub_sql(self, expression: exp.Sub) -> str:
    3398        return self.binary(expression, "-")
    3399
    3400    def trycast_sql(self, expression: exp.TryCast) -> str:
    3401        return self.cast_sql(expression, safe_prefix="TRY_")
    3402
    3403    def try_sql(self, expression: exp.Try) -> str:
    3404        if not self.TRY_SUPPORTED:
    3405            self.unsupported("Unsupported TRY function")
    3406            return self.sql(expression, "this")
    3407
    3408        return self.func("TRY", expression.this)
    3409
    3410    def log_sql(self, expression: exp.Log) -> str:
    3411        this = expression.this
    3412        expr = expression.expression
    3413
    3414        if self.dialect.LOG_BASE_FIRST is False:
    3415            this, expr = expr, this
    3416        elif self.dialect.LOG_BASE_FIRST is None and expr:
    3417            if this.name in ("2", "10"):
    3418                return self.func(f"LOG{this.name}", expr)
    3419
    3420            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
    3421
    3422        return self.func("LOG", this, expr)
    3423
    3424    def use_sql(self, expression: exp.Use) -> str:
    3425        kind = self.sql(expression, "kind")
    3426        kind = f" {kind}" if kind else ""
    3427        this = self.sql(expression, "this")
    3428        this = f" {this}" if this else ""
    3429        return f"USE{kind}{this}"
    3430
    3431    def binary(self, expression: exp.Binary, op: str) -> str:
    3432        sqls: t.List[str] = []
    3433        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    3434        binary_type = type(expression)
    3435
    3436        while stack:
    3437            node = stack.pop()
    3438
    3439            if type(node) is binary_type:
    3440                op_func = node.args.get("operator")
    3441                if op_func:
    3442                    op = f"OPERATOR({self.sql(op_func)})"
    3443
    3444                stack.append(node.right)
    3445                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
    3446                stack.append(node.left)
    3447            else:
    3448                sqls.append(self.sql(node))
    3449
    3450        return "".join(sqls)
    3451
    3452    def function_fallback_sql(self, expression: exp.Func) -> str:
    3453        args = []
    3454
    3455        for key in expression.arg_types:
    3456            arg_value = expression.args.get(key)
    3457
    3458            if isinstance(arg_value, list):
    3459                for value in arg_value:
    3460                    args.append(value)
    3461            elif arg_value is not None:
    3462                args.append(arg_value)
    3463
    3464        if self.normalize_functions:
    3465            name = expression.sql_name()
    3466        else:
    3467            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3468
    3469        return self.func(name, *args)
    3470
    3471    def func(
    3472        self,
    3473        name: str,
    3474        *args: t.Optional[exp.Expression | str],
    3475        prefix: str = "(",
    3476        suffix: str = ")",
    3477        normalize: bool = True,
    3478    ) -> str:
    3479        name = self.normalize_func(name) if normalize else name
    3480        return f"{name}{prefix}{self.format_args(*args)}{suffix}"
    3481
    3482    def format_args(self, *args: t.Optional[str | exp.Expression]) -> str:
    3483        arg_sqls = tuple(
    3484            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
    3485        )
    3486        if self.pretty and self.too_wide(arg_sqls):
    3487            return self.indent("\n" + ",\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True)
    3488        return ", ".join(arg_sqls)
    3489
    3490    def too_wide(self, args: t.Iterable) -> bool:
    3491        return sum(len(arg) for arg in args) > self.max_text_width
    3492
    3493    def format_time(
    3494        self,
    3495        expression: exp.Expression,
    3496        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
    3497        inverse_time_trie: t.Optional[t.Dict] = None,
    3498    ) -> t.Optional[str]:
    3499        return format_time(
    3500            self.sql(expression, "format"),
    3501            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
    3502            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
    3503        )
    3504
    3505    def expressions(
    3506        self,
    3507        expression: t.Optional[exp.Expression] = None,
    3508        key: t.Optional[str] = None,
    3509        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    3510        flat: bool = False,
    3511        indent: bool = True,
    3512        skip_first: bool = False,
    3513        skip_last: bool = False,
    3514        sep: str = ", ",
    3515        prefix: str = "",
    3516        dynamic: bool = False,
    3517        new_line: bool = False,
    3518    ) -> str:
    3519        expressions = expression.args.get(key or "expressions") if expression else sqls
    3520
    3521        if not expressions:
    3522            return ""
    3523
    3524        if flat:
    3525            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    3526
    3527        num_sqls = len(expressions)
    3528        result_sqls = []
    3529
    3530        for i, e in enumerate(expressions):
    3531            sql = self.sql(e, comment=False)
    3532            if not sql:
    3533                continue
    3534
    3535            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    3536
    3537            if self.pretty:
    3538                if self.leading_comma:
    3539                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
    3540                else:
    3541                    result_sqls.append(
    3542                        f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}"
    3543                    )
    3544            else:
    3545                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    3546
    3547        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
    3548            if new_line:
    3549                result_sqls.insert(0, "")
    3550                result_sqls.append("")
    3551            result_sql = "\n".join(s.rstrip() for s in result_sqls)
    3552        else:
    3553            result_sql = "".join(result_sqls)
    3554
    3555        return (
    3556            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
    3557            if indent
    3558            else result_sql
    3559        )
    3560
    3561    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3562        flat = flat or isinstance(expression.parent, exp.Properties)
    3563        expressions_sql = self.expressions(expression, flat=flat)
    3564        if flat:
    3565            return f"{op} {expressions_sql}"
    3566        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
    3567
    3568    def naked_property(self, expression: exp.Property) -> str:
    3569        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3570        if not property_name:
    3571            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3572        return f"{property_name} {self.sql(expression, 'this')}"
    3573
    3574    def tag_sql(self, expression: exp.Tag) -> str:
    3575        return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}"
    3576
    3577    def token_sql(self, token_type: TokenType) -> str:
    3578        return self.TOKEN_MAPPING.get(token_type, token_type.name)
    3579
    3580    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3581        this = self.sql(expression, "this")
    3582        expressions = self.no_identify(self.expressions, expression)
    3583        expressions = (
    3584            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3585        )
    3586        return f"{this}{expressions}"
    3587
    3588    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3589        this = self.sql(expression, "this")
    3590        expressions = self.expressions(expression, flat=True)
    3591        return f"{this}({expressions})"
    3592
    3593    def kwarg_sql(self, expression: exp.Kwarg) -> str:
    3594        return self.binary(expression, "=>")
    3595
    3596    def when_sql(self, expression: exp.When) -> str:
    3597        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3598        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3599        condition = self.sql(expression, "condition")
    3600        condition = f" AND {condition}" if condition else ""
    3601
    3602        then_expression = expression.args.get("then")
    3603        if isinstance(then_expression, exp.Insert):
    3604            this = self.sql(then_expression, "this")
    3605            this = f"INSERT {this}" if this else "INSERT"
    3606            then = self.sql(then_expression, "expression")
    3607            then = f"{this} VALUES {then}" if then else this
    3608        elif isinstance(then_expression, exp.Update):
    3609            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3610                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3611            else:
    3612                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    3613        else:
    3614            then = self.sql(then_expression)
    3615        return f"WHEN {matched}{source}{condition} THEN {then}"
    3616
    3617    def merge_sql(self, expression: exp.Merge) -> str:
    3618        table = expression.this
    3619        table_alias = ""
    3620
    3621        hints = table.args.get("hints")
    3622        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3623            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3624            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3625
    3626        this = self.sql(table)
    3627        using = f"USING {self.sql(expression, 'using')}"
    3628        on = f"ON {self.sql(expression, 'on')}"
    3629        expressions = self.expressions(expression, sep=" ", indent=False)
    3630        returning = self.sql(expression, "returning")
    3631        if returning:
    3632            expressions = f"{expressions}{returning}"
    3633
    3634        sep = self.sep()
    3635
    3636        return self.prepend_ctes(
    3637            expression,
    3638            f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{expressions}",
    3639        )
    3640
    3641    @unsupported_args("format")
    3642    def tochar_sql(self, expression: exp.ToChar) -> str:
    3643        return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT))
    3644
    3645    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3646        if not self.SUPPORTS_TO_NUMBER:
    3647            self.unsupported("Unsupported TO_NUMBER function")
    3648            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3649
    3650        fmt = expression.args.get("format")
    3651        if not fmt:
    3652            self.unsupported("Conversion format is required for TO_NUMBER")
    3653            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3654
    3655        return self.func("TO_NUMBER", expression.this, fmt)
    3656
    3657    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3658        this = self.sql(expression, "this")
    3659        kind = self.sql(expression, "kind")
    3660        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3661        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3662        return f"{this}({kind}{args})"
    3663
    3664    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3665        this = self.sql(expression, "this")
    3666        max = self.sql(expression, "max")
    3667        min = self.sql(expression, "min")
    3668        return f"{this}(MIN {min} MAX {max})"
    3669
    3670    def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str:
    3671        return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}"
    3672
    3673    def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str:
    3674        return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})"
    3675
    3676    # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc
    3677    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
    3678        expressions = self.expressions(expression, flat=True)
    3679        expressions = f" {self.wrap(expressions)}" if expressions else ""
    3680        buckets = self.sql(expression, "buckets")
    3681        kind = self.sql(expression, "kind")
    3682        buckets = f" BUCKETS {buckets}" if buckets else ""
    3683        order = self.sql(expression, "order")
    3684        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"
    3685
    3686    def oncluster_sql(self, expression: exp.OnCluster) -> str:
    3687        return ""
    3688
    3689    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3690        expressions = self.expressions(expression, key="expressions", flat=True)
    3691        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3692        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3693        buckets = self.sql(expression, "buckets")
    3694        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
    3695
    3696    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3697        this = self.sql(expression, "this")
    3698        having = self.sql(expression, "having")
    3699
    3700        if having:
    3701            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3702
    3703        return self.func("ANY_VALUE", this)
    3704
    3705    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3706        transform = self.func("TRANSFORM", *expression.expressions)
    3707        row_format_before = self.sql(expression, "row_format_before")
    3708        row_format_before = f" {row_format_before}" if row_format_before else ""
    3709        record_writer = self.sql(expression, "record_writer")
    3710        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3711        using = f" USING {self.sql(expression, 'command_script')}"
    3712        schema = self.sql(expression, "schema")
    3713        schema = f" AS {schema}" if schema else ""
    3714        row_format_after = self.sql(expression, "row_format_after")
    3715        row_format_after = f" {row_format_after}" if row_format_after else ""
    3716        record_reader = self.sql(expression, "record_reader")
    3717        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3718        return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"
    3719
    3720    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3721        key_block_size = self.sql(expression, "key_block_size")
    3722        if key_block_size:
    3723            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3724
    3725        using = self.sql(expression, "using")
    3726        if using:
    3727            return f"USING {using}"
    3728
    3729        parser = self.sql(expression, "parser")
    3730        if parser:
    3731            return f"WITH PARSER {parser}"
    3732
    3733        comment = self.sql(expression, "comment")
    3734        if comment:
    3735            return f"COMMENT {comment}"
    3736
    3737        visible = expression.args.get("visible")
    3738        if visible is not None:
    3739            return "VISIBLE" if visible else "INVISIBLE"
    3740
    3741        engine_attr = self.sql(expression, "engine_attr")
    3742        if engine_attr:
    3743            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3744
    3745        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3746        if secondary_engine_attr:
    3747            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3748
    3749        self.unsupported("Unsupported index constraint option.")
    3750        return ""
    3751
    3752    def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str:
    3753        enforced = " ENFORCED" if expression.args.get("enforced") else ""
    3754        return f"CHECK ({self.sql(expression, 'this')}){enforced}"
    3755
    3756    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3757        kind = self.sql(expression, "kind")
    3758        kind = f"{kind} INDEX" if kind else "INDEX"
    3759        this = self.sql(expression, "this")
    3760        this = f" {this}" if this else ""
    3761        index_type = self.sql(expression, "index_type")
    3762        index_type = f" USING {index_type}" if index_type else ""
    3763        expressions = self.expressions(expression, flat=True)
    3764        expressions = f" ({expressions})" if expressions else ""
    3765        options = self.expressions(expression, key="options", sep=" ")
    3766        options = f" {options}" if options else ""
    3767        return f"{kind}{this}{index_type}{expressions}{options}"
    3768
    3769    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3770        if self.NVL2_SUPPORTED:
    3771            return self.function_fallback_sql(expression)
    3772
    3773        case = exp.Case().when(
    3774            expression.this.is_(exp.null()).not_(copy=False),
    3775            expression.args["true"],
    3776            copy=False,
    3777        )
    3778        else_cond = expression.args.get("false")
    3779        if else_cond:
    3780            case.else_(else_cond, copy=False)
    3781
    3782        return self.sql(case)
    3783
    3784    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3785        this = self.sql(expression, "this")
    3786        expr = self.sql(expression, "expression")
    3787        iterator = self.sql(expression, "iterator")
    3788        condition = self.sql(expression, "condition")
    3789        condition = f" IF {condition}" if condition else ""
    3790        return f"{this} FOR {expr} IN {iterator}{condition}"
    3791
    3792    def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str:
    3793        return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})"
    3794
    3795    def opclass_sql(self, expression: exp.Opclass) -> str:
    3796        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
    3797
    3798    def predict_sql(self, expression: exp.Predict) -> str:
    3799        model = self.sql(expression, "this")
    3800        model = f"MODEL {model}"
    3801        table = self.sql(expression, "expression")
    3802        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    3803        parameters = self.sql(expression, "params_struct")
    3804        return self.func("PREDICT", model, table, parameters or None)
    3805
    3806    def forin_sql(self, expression: exp.ForIn) -> str:
    3807        this = self.sql(expression, "this")
    3808        expression_sql = self.sql(expression, "expression")
    3809        return f"FOR {this} DO {expression_sql}"
    3810
    3811    def refresh_sql(self, expression: exp.Refresh) -> str:
    3812        this = self.sql(expression, "this")
    3813        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    3814        return f"REFRESH {table}{this}"
    3815
    3816    def toarray_sql(self, expression: exp.ToArray) -> str:
    3817        arg = expression.this
    3818        if not arg.type:
    3819            from sqlglot.optimizer.annotate_types import annotate_types
    3820
    3821            arg = annotate_types(arg)
    3822
    3823        if arg.is_type(exp.DataType.Type.ARRAY):
    3824            return self.sql(arg)
    3825
    3826        cond_for_null = arg.is_(exp.null())
    3827        return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False)))
    3828
    3829    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    3830        this = expression.this
    3831        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    3832            return self.sql(this)
    3833
    3834        return self.sql(exp.cast(this, exp.DataType.Type.TIME))
    3835
    3836    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
    3837        this = expression.this
    3838        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
    3839            return self.sql(this)
    3840
    3841        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP))
    3842
    3843    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    3844        this = expression.this
    3845        time_format = self.format_time(expression)
    3846
    3847        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    3848            return self.sql(
    3849                exp.cast(
    3850                    exp.StrToTime(this=this, format=expression.args["format"]),
    3851                    exp.DataType.Type.DATE,
    3852                )
    3853            )
    3854
    3855        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    3856            return self.sql(this)
    3857
    3858        return self.sql(exp.cast(this, exp.DataType.Type.DATE))
    3859
    3860    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    3861        return self.sql(
    3862            exp.func(
    3863                "DATEDIFF",
    3864                expression.this,
    3865                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
    3866                "day",
    3867            )
    3868        )
    3869
    3870    def lastday_sql(self, expression: exp.LastDay) -> str:
    3871        if self.LAST_DAY_SUPPORTS_DATE_PART:
    3872            return self.function_fallback_sql(expression)
    3873
    3874        unit = expression.text("unit")
    3875        if unit and unit != "MONTH":
    3876            self.unsupported("Date parts are not supported in LAST_DAY.")
    3877
    3878        return self.func("LAST_DAY", expression.this)
    3879
    3880    def dateadd_sql(self, expression: exp.DateAdd) -> str:
    3881        from sqlglot.dialects.dialect import unit_to_str
    3882
    3883        return self.func(
    3884            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
    3885        )
    3886
    3887    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    3888        if self.CAN_IMPLEMENT_ARRAY_ANY:
    3889            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    3890            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    3891            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    3892            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    3893
    3894        from sqlglot.dialects import Dialect
    3895
    3896        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    3897        if self.dialect.__class__ != Dialect:
    3898            self.unsupported("ARRAY_ANY is unsupported")
    3899
    3900        return self.function_fallback_sql(expression)
    3901
    3902    def struct_sql(self, expression: exp.Struct) -> str:
    3903        expression.set(
    3904            "expressions",
    3905            [
    3906                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    3907                if isinstance(e, exp.PropertyEQ)
    3908                else e
    3909                for e in expression.expressions
    3910            ],
    3911        )
    3912
    3913        return self.function_fallback_sql(expression)
    3914
    3915    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    3916        low = self.sql(expression, "this")
    3917        high = self.sql(expression, "expression")
    3918
    3919        return f"{low} TO {high}"
    3920
    3921    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    3922        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    3923        tables = f" {self.expressions(expression)}"
    3924
    3925        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3926
    3927        on_cluster = self.sql(expression, "cluster")
    3928        on_cluster = f" {on_cluster}" if on_cluster else ""
    3929
    3930        identity = self.sql(expression, "identity")
    3931        identity = f" {identity} IDENTITY" if identity else ""
    3932
    3933        option = self.sql(expression, "option")
    3934        option = f" {option}" if option else ""
    3935
    3936        partition = self.sql(expression, "partition")
    3937        partition = f" {partition}" if partition else ""
    3938
    3939        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"
    3940
    3941    # This transpiles T-SQL's CONVERT function
    3942    # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16
    3943    def convert_sql(self, expression: exp.Convert) -> str:
    3944        to = expression.this
    3945        value = expression.expression
    3946        style = expression.args.get("style")
    3947        safe = expression.args.get("safe")
    3948        strict = expression.args.get("strict")
    3949
    3950        if not to or not value:
    3951            return ""
    3952
    3953        # Retrieve length of datatype and override to default if not specified
    3954        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3955            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    3956
    3957        transformed: t.Optional[exp.Expression] = None
    3958        cast = exp.Cast if strict else exp.TryCast
    3959
    3960        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
    3961        if isinstance(style, exp.Literal) and style.is_int:
    3962            from sqlglot.dialects.tsql import TSQL
    3963
    3964            style_value = style.name
    3965            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
    3966            if not converted_style:
    3967                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
    3968
    3969            fmt = exp.Literal.string(converted_style)
    3970
    3971            if to.this == exp.DataType.Type.DATE:
    3972                transformed = exp.StrToDate(this=value, format=fmt)
    3973            elif to.this == exp.DataType.Type.DATETIME:
    3974                transformed = exp.StrToTime(this=value, format=fmt)
    3975            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3976                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
    3977            elif to.this == exp.DataType.Type.TEXT:
    3978                transformed = exp.TimeToStr(this=value, format=fmt)
    3979
    3980        if not transformed:
    3981            transformed = cast(this=value, to=to, safe=safe)
    3982
    3983        return self.sql(transformed)
    3984
    3985    def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str:
    3986        this = expression.this
    3987        if isinstance(this, exp.JSONPathWildcard):
    3988            this = self.json_path_part(this)
    3989            return f".{this}" if this else ""
    3990
    3991        if exp.SAFE_IDENTIFIER_RE.match(this):
    3992            return f".{this}"
    3993
    3994        this = self.json_path_part(this)
    3995        return f"[{this}]" if self.JSON_PATH_BRACKETED_KEY_SUPPORTED else f".{this}"
    3996
    3997    def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str:
    3998        this = self.json_path_part(expression.this)
    3999        return f"[{this}]" if this else ""
    4000
    4001    def _simplify_unless_literal(self, expression: E) -> E:
    4002        if not isinstance(expression, exp.Literal):
    4003            from sqlglot.optimizer.simplify import simplify
    4004
    4005            expression = simplify(expression, dialect=self.dialect)
    4006
    4007        return expression
    4008
    4009    def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str:
    4010        if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"):
    4011            # The first modifier here will be the one closest to the AggFunc's arg
    4012            mods = sorted(
    4013                expression.find_all(exp.HavingMax, exp.Order, exp.Limit),
    4014                key=lambda x: 0
    4015                if isinstance(x, exp.HavingMax)
    4016                else (1 if isinstance(x, exp.Order) else 2),
    4017            )
    4018
    4019            if mods:
    4020                mod = mods[0]
    4021                this = expression.__class__(this=mod.this.copy())
    4022                this.meta["inline"] = True
    4023                mod.this.replace(this)
    4024                return self.sql(expression.this)
    4025
    4026            agg_func = expression.find(exp.AggFunc)
    4027
    4028            if agg_func:
    4029                return self.sql(agg_func)[:-1] + f" {text})"
    4030
    4031        return f"{self.sql(expression, 'this')} {text}"
    4032
    4033    def _replace_line_breaks(self, string: str) -> str:
    4034        """We don't want to extra indent line breaks so we temporarily replace them with sentinels."""
    4035        if self.pretty:
    4036            return string.replace("\n", self.SENTINEL_LINE_BREAK)
    4037        return string
    4038
    4039    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
    4040        option = self.sql(expression, "this")
    4041
    4042        if expression.expressions:
    4043            upper = option.upper()
    4044
    4045            # Snowflake FILE_FORMAT options are separated by whitespace
    4046            sep = " " if upper == "FILE_FORMAT" else ", "
    4047
    4048            # Databricks copy/format options do not set their list of values with EQ
    4049            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
    4050            values = self.expressions(expression, flat=True, sep=sep)
    4051            return f"{option}{op}({values})"
    4052
    4053        value = self.sql(expression, "expression")
    4054
    4055        if not value:
    4056            return option
    4057
    4058        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
    4059
    4060        return f"{option}{op}{value}"
    4061
    4062    def credentials_sql(self, expression: exp.Credentials) -> str:
    4063        cred_expr = expression.args.get("credentials")
    4064        if isinstance(cred_expr, exp.Literal):
    4065            # Redshift case: CREDENTIALS <string>
    4066            credentials = self.sql(expression, "credentials")
    4067            credentials = f"CREDENTIALS {credentials}" if credentials else ""
    4068        else:
    4069            # Snowflake case: CREDENTIALS = (...)
    4070            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
    4071            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
    4072
    4073        storage = self.sql(expression, "storage")
    4074        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
    4075
    4076        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
    4077        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
    4078
    4079        iam_role = self.sql(expression, "iam_role")
    4080        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
    4081
    4082        region = self.sql(expression, "region")
    4083        region = f" REGION {region}" if region else ""
    4084
    4085        return f"{credentials}{storage}{encryption}{iam_role}{region}"
    4086
    4087    def copy_sql(self, expression: exp.Copy) -> str:
    4088        this = self.sql(expression, "this")
    4089        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
    4090
    4091        credentials = self.sql(expression, "credentials")
    4092        credentials = self.seg(credentials) if credentials else ""
    4093        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
    4094        files = self.expressions(expression, key="files", flat=True)
    4095
    4096        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
    4097        params = self.expressions(
    4098            expression,
    4099            key="params",
    4100            sep=sep,
    4101            new_line=True,
    4102            skip_last=True,
    4103            skip_first=True,
    4104            indent=self.COPY_PARAMS_ARE_WRAPPED,
    4105        )
    4106
    4107        if params:
    4108            if self.COPY_PARAMS_ARE_WRAPPED:
    4109                params = f" WITH ({params})"
    4110            elif not self.pretty:
    4111                params = f" {params}"
    4112
    4113        return f"COPY{this}{kind} {files}{credentials}{params}"
    4114
    4115    def semicolon_sql(self, expression: exp.Semicolon) -> str:
    4116        return ""
    4117
    4118    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
    4119        on_sql = "ON" if expression.args.get("on") else "OFF"
    4120        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
    4121        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
    4122        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    4123        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
    4124
    4125        if filter_col or retention_period:
    4126            on_sql = self.func("ON", filter_col, retention_period)
    4127
    4128        return f"DATA_DELETION={on_sql}"
    4129
    4130    def maskingpolicycolumnconstraint_sql(
    4131        self, expression: exp.MaskingPolicyColumnConstraint
    4132    ) -> str:
    4133        this = self.sql(expression, "this")
    4134        expressions = self.expressions(expression, flat=True)
    4135        expressions = f" USING ({expressions})" if expressions else ""
    4136        return f"MASKING POLICY {this}{expressions}"
    4137
    4138    def gapfill_sql(self, expression: exp.GapFill) -> str:
    4139        this = self.sql(expression, "this")
    4140        this = f"TABLE {this}"
    4141        return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"])
    4142
    4143    def scope_resolution(self, rhs: str, scope_name: str) -> str:
    4144        return self.func("SCOPE_RESOLUTION", scope_name or None, rhs)
    4145
    4146    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
    4147        this = self.sql(expression, "this")
    4148        expr = expression.expression
    4149
    4150        if isinstance(expr, exp.Func):
    4151            # T-SQL's CLR functions are case sensitive
    4152            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
    4153        else:
    4154            expr = self.sql(expression, "expression")
    4155
    4156        return self.scope_resolution(expr, this)
    4157
    4158    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
    4159        if self.PARSE_JSON_NAME is None:
    4160            return self.sql(expression.this)
    4161
    4162        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)
    4163
    4164    def rand_sql(self, expression: exp.Rand) -> str:
    4165        lower = self.sql(expression, "lower")
    4166        upper = self.sql(expression, "upper")
    4167
    4168        if lower and upper:
    4169            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
    4170        return self.func("RAND", expression.this)
    4171
    4172    def changes_sql(self, expression: exp.Changes) -> str:
    4173        information = self.sql(expression, "information")
    4174        information = f"INFORMATION => {information}"
    4175        at_before = self.sql(expression, "at_before")
    4176        at_before = f"{self.seg('')}{at_before}" if at_before else ""
    4177        end = self.sql(expression, "end")
    4178        end = f"{self.seg('')}{end}" if end else ""
    4179
    4180        return f"CHANGES ({information}){at_before}{end}"
    4181
    4182    def pad_sql(self, expression: exp.Pad) -> str:
    4183        prefix = "L" if expression.args.get("is_left") else "R"
    4184
    4185        fill_pattern = self.sql(expression, "fill_pattern") or None
    4186        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
    4187            fill_pattern = "' '"
    4188
    4189        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)
    4190
    4191    def summarize_sql(self, expression: exp.Summarize) -> str:
    4192        table = " TABLE" if expression.args.get("table") else ""
    4193        return f"SUMMARIZE{table} {self.sql(expression.this)}"
    4194
    4195    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
    4196        generate_series = exp.GenerateSeries(**expression.args)
    4197
    4198        parent = expression.parent
    4199        if isinstance(parent, (exp.Alias, exp.TableAlias)):
    4200            parent = parent.parent
    4201
    4202        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
    4203            return self.sql(exp.Unnest(expressions=[generate_series]))
    4204
    4205        if isinstance(parent, exp.Select):
    4206            self.unsupported("GenerateSeries projection unnesting is not supported.")
    4207
    4208        return self.sql(generate_series)
    4209
    4210    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
    4211        exprs = expression.expressions
    4212        if not self.ARRAY_CONCAT_IS_VAR_LEN:
    4213            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
    4214        else:
    4215            rhs = self.expressions(expression)
    4216
    4217        return self.func(name, expression.this, rhs)
    4218
    4219    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
    4220        if self.SUPPORTS_CONVERT_TIMEZONE:
    4221            return self.function_fallback_sql(expression)
    4222
    4223        source_tz = expression.args.get("source_tz")
    4224        target_tz = expression.args.get("target_tz")
    4225        timestamp = expression.args.get("timestamp")
    4226
    4227        if source_tz and timestamp:
    4228            timestamp = exp.AtTimeZone(
    4229                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
    4230            )
    4231
    4232        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
    4233
    4234        return self.sql(expr)
    4235
    4236    def json_sql(self, expression: exp.JSON) -> str:
    4237        this = self.sql(expression, "this")
    4238        this = f" {this}" if this else ""
    4239
    4240        _with = expression.args.get("with")
    4241
    4242        if _with is None:
    4243            with_sql = ""
    4244        elif not _with:
    4245            with_sql = " WITHOUT"
    4246        else:
    4247            with_sql = " WITH"
    4248
    4249        unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else ""
    4250
    4251        return f"JSON{this}{with_sql}{unique_sql}"
    4252
    4253    def jsonvalue_sql(self, expression: exp.JSONValue) -> str:
    4254        def _generate_on_options(arg: t.Any) -> str:
    4255            return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}"
    4256
    4257        path = self.sql(expression, "path")
    4258        returning = self.sql(expression, "returning")
    4259        returning = f" RETURNING {returning}" if returning else ""
    4260
    4261        on_condition = self.sql(expression, "on_condition")
    4262        on_condition = f" {on_condition}" if on_condition else ""
    4263
    4264        return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")
    4265
    4266    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
    4267        else_ = "ELSE " if expression.args.get("else_") else ""
    4268        condition = self.sql(expression, "expression")
    4269        condition = f"WHEN {condition} THEN " if condition else else_
    4270        insert = self.sql(expression, "this")[len("INSERT") :].strip()
    4271        return f"{condition}{insert}"
    4272
    4273    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
    4274        kind = self.sql(expression, "kind")
    4275        expressions = self.seg(self.expressions(expression, sep=" "))
    4276        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
    4277        return res
    4278
    4279    def oncondition_sql(self, expression: exp.OnCondition) -> str:
    4280        # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR"
    4281        empty = expression.args.get("empty")
    4282        empty = (
    4283            f"DEFAULT {empty} ON EMPTY"
    4284            if isinstance(empty, exp.Expression)
    4285            else self.sql(expression, "empty")
    4286        )
    4287
    4288        error = expression.args.get("error")
    4289        error = (
    4290            f"DEFAULT {error} ON ERROR"
    4291            if isinstance(error, exp.Expression)
    4292            else self.sql(expression, "error")
    4293        )
    4294
    4295        if error and empty:
    4296            error = (
    4297                f"{empty} {error}"
    4298                if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR
    4299                else f"{error} {empty}"
    4300            )
    4301            empty = ""
    4302
    4303        null = self.sql(expression, "null")
    4304
    4305        return f"{empty}{error}{null}"
    4306
    4307    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
    4308        this = self.sql(expression, "this")
    4309        path = self.sql(expression, "path")
    4310
    4311        passing = self.expressions(expression, "passing")
    4312        passing = f" PASSING {passing}" if passing else ""
    4313
    4314        on_condition = self.sql(expression, "on_condition")
    4315        on_condition = f" {on_condition}" if on_condition else ""
    4316
    4317        path = f"{path}{passing}{on_condition}"
    4318
    4319        return self.func("JSON_EXISTS", this, path)
    4320
    4321    def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
    4322        array_agg = self.function_fallback_sql(expression)
    4323
    4324        if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"):
    4325            parent = expression.parent
    4326            if isinstance(parent, exp.Filter):
    4327                parent_cond = parent.expression.this
    4328                parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_()))
    4329            else:
    4330                # DISTINCT is already present in the agg function, do not propagate it to FILTER as well
    4331                this = expression.this
    4332                this_sql = (
    4333                    self.expressions(this)
    4334                    if isinstance(this, exp.Distinct)
    4335                    else self.sql(expression, "this")
    4336                )
    4337                array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)"
    4338
    4339        return array_agg
    4340
    4341    def apply_sql(self, expression: exp.Apply) -> str:
    4342        this = self.sql(expression, "this")
    4343        expr = self.sql(expression, "expression")
    4344
    4345        return f"{this} APPLY({expr})"
    4346
    4347    def grant_sql(self, expression: exp.Grant) -> str:
    4348        privileges_sql = self.expressions(expression, key="privileges", flat=True)
    4349
    4350        kind = self.sql(expression, "kind")
    4351        kind = f" {kind}" if kind else ""
    4352
    4353        securable = self.sql(expression, "securable")
    4354        securable = f" {securable}" if securable else ""
    4355
    4356        principals = self.expressions(expression, key="principals", flat=True)
    4357
    4358        grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else ""
    4359
    4360        return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"
    4361
    4362    def grantprivilege_sql(self, expression: exp.GrantPrivilege):
    4363        this = self.sql(expression, "this")
    4364        columns = self.expressions(expression, flat=True)
    4365        columns = f"({columns})" if columns else ""
    4366
    4367        return f"{this}{columns}"
    4368
    4369    def grantprincipal_sql(self, expression: exp.GrantPrincipal):
    4370        this = self.sql(expression, "this")
    4371
    4372        kind = self.sql(expression, "kind")
    4373        kind = f"{kind} " if kind else ""
    4374
    4375        return f"{kind}{this}"

Generator converts a given syntax tree to the corresponding SQL string.

###### Arguments:

- pretty: Whether to format the produced SQL string. Default: False.
- identify: Determines when an identifier should be quoted. Possible values are: False (default): Never quote, except in cases where it's mandatory by the dialect. True or 'always': Always quote. 'safe': Only quote identifiers that are case insensitive.
- normalize: Whether to normalize identifiers to lowercase. Default: False.
- pad: The pad size in a formatted string. For example, this affects the indentation of a projection in a query, relative to its nesting level. Default: 2.
- indent: The indentation size in a formatted string. For example, this affects the indentation of subqueries and filters under a `WHERE` clause. Default: 2.
- normalize_functions: How to normalize function names. Possible values are: "upper" or True (default): Convert names to uppercase. "lower": Convert names to lowercase. False: Disables function name normalization.
- unsupported_level: Determines the generator's behavior when it encounters unsupported expressions. Default ErrorLevel.WARN.
- max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError. This is only relevant if unsupported_level is ErrorLevel.RAISE. Default: 3
- leading_comma: Whether the comma is leading or trailing in select expressions. This is only relevant when generating in pretty mode. Default: False
- max_text_width: The max number of characters in a segment before creating new lines in pretty mode. The default is on the smaller end because the length only represents a segment and not the true line length. Default: 80
- comments: Whether to preserve comments in the output SQL code. Default: True

Generator( pretty: Optional[bool] = None, identify: str | bool = False, normalize: bool = False, pad: int = 2, indent: int = 2, normalize_functions: Union[str, bool, NoneType] = None, unsupported_level: sqlglot.errors.ErrorLevel = <ErrorLevel.WARN: 'WARN'>, max_unsupported: int = 3, leading_comma: bool = False, max_text_width: int = 80, comments: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None) View Source

    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.JSONPathSubscript'>, <class 'sqlglot.expressions.JSONPathUnion'>, <class 'sqlglot.expressions.JSONPathSelector'>, <class 'sqlglot.expressions.JSONPathSlice'>, <class 'sqlglot.expressions.JSONPathScript'>, <class 'sqlglot.expressions.JSONPathRoot'>, <class 'sqlglot.expressions.JSONPathWildcard'>, <class 'sqlglot.expressions.JSONPathRecursive'>, <class 'sqlglot.expressions.JSONPathKey'>, <class 'sqlglot.expressions.JSONPathFilter'>}
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.NVARCHAR: 'NVARCHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.CHAR: 'CHAR'>}
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        cluster = self.sql(expression, "cluster")
    1319        cluster = f" {cluster}" if cluster else ""
    1320        where = self.sql(expression, "where")
    1321        returning = self.sql(expression, "returning")
    1322        limit = self.sql(expression, "limit")
    1323        tables = self.expressions(expression, key="tables")
    1324        tables = f" {tables}" if tables else ""
    1325        if self.RETURNING_END:
    1326            expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}"
    1327        else:
    1328            expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}"
    1329        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2280    def null_sql(self, *_) -> str:
    2281        return "NULL"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2534    def parameter_sql(self, expression: exp.Parameter) -> str:
    2535        this = self.sql(expression, "this")
    2536        return f"{self.PARAMETER_TOKEN}{this}"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3102    def collate_sql(self, expression: exp.Collate) -> str:
    3103        if self.COLLATE_IS_FUNC:
    3104            return self.function_fallback_sql(expression)
    3105        return self.binary(expression, "COLLATE")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3657    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3658        this = self.sql(expression, "this")
    3659        kind = self.sql(expression, "kind")
    3660        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3661        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3662        return f"{this}({kind}{args})"

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

    3664    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3665        this = self.sql(expression, "this")
    3666        max = self.sql(expression, "max")
    3667        min = self.sql(expression, "min")
    3668        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

    3677    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
    3678        expressions = self.expressions(expression, flat=True)
    3679        expressions = f" {self.wrap(expressions)}" if expressions else ""
    3680        buckets = self.sql(expression, "buckets")
    3681        kind = self.sql(expression, "kind")
    3682        buckets = f" BUCKETS {buckets}" if buckets else ""
    3683        order = self.sql(expression, "order")
    3684        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"

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

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

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

    3689    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3690        expressions = self.expressions(expression, key="expressions", flat=True)
    3691        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3692        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3693        buckets = self.sql(expression, "buckets")
    3694        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    3696    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3697        this = self.sql(expression, "this")
    3698        having = self.sql(expression, "having")
    3699
    3700        if having:
    3701            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3702
    3703        return self.func("ANY_VALUE", this)

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

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

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

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

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

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

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

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

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

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

    3784    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3785        this = self.sql(expression, "this")
    3786        expr = self.sql(expression, "expression")
    3787        iterator = self.sql(expression, "iterator")
    3788        condition = self.sql(expression, "condition")
    3789        condition = f" IF {condition}" if condition else ""
    3790        return f"{this} FOR {expr} IN {iterator}{condition}"

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

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

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

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

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

    3798    def predict_sql(self, expression: exp.Predict) -> str:
    3799        model = self.sql(expression, "this")
    3800        model = f"MODEL {model}"
    3801        table = self.sql(expression, "expression")
    3802        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    3803        parameters = self.sql(expression, "params_struct")
    3804        return self.func("PREDICT", model, table, parameters or None)

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

    3806    def forin_sql(self, expression: exp.ForIn) -> str:
    3807        this = self.sql(expression, "this")
    3808        expression_sql = self.sql(expression, "expression")
    3809        return f"FOR {this} DO {expression_sql}"

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

    3811    def refresh_sql(self, expression: exp.Refresh) -> str:
    3812        this = self.sql(expression, "this")
    3813        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    3814        return f"REFRESH {table}{this}"

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

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

    3829    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    3830        this = expression.this
    3831        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    3832            return self.sql(this)
    3833
    3834        return self.sql(exp.cast(this, exp.DataType.Type.TIME))

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

    3836    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
    3837        this = expression.this
    3838        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
    3839            return self.sql(this)
    3840
    3841        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP))

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

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

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

    3860    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    3861        return self.sql(
    3862            exp.func(
    3863                "DATEDIFF",
    3864                expression.this,
    3865                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
    3866                "day",
    3867            )
    3868        )

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

    3870    def lastday_sql(self, expression: exp.LastDay) -> str:
    3871        if self.LAST_DAY_SUPPORTS_DATE_PART:
    3872            return self.function_fallback_sql(expression)
    3873
    3874        unit = expression.text("unit")
    3875        if unit and unit != "MONTH":
    3876            self.unsupported("Date parts are not supported in LAST_DAY.")
    3877
    3878        return self.func("LAST_DAY", expression.this)

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

    3880    def dateadd_sql(self, expression: exp.DateAdd) -> str:
    3881        from sqlglot.dialects.dialect import unit_to_str
    3882
    3883        return self.func(
    3884            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
    3885        )

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

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

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

    3902    def struct_sql(self, expression: exp.Struct) -> str:
    3903        expression.set(
    3904            "expressions",
    3905            [
    3906                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    3907                if isinstance(e, exp.PropertyEQ)
    3908                else e
    3909                for e in expression.expressions
    3910            ],
    3911        )
    3912
    3913        return self.function_fallback_sql(expression)

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

    3915    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    3916        low = self.sql(expression, "this")
    3917        high = self.sql(expression, "expression")
    3918
    3919        return f"{low} TO {high}"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    4130    def maskingpolicycolumnconstraint_sql(
    4131        self, expression: exp.MaskingPolicyColumnConstraint
    4132    ) -> str:
    4133        this = self.sql(expression, "this")
    4134        expressions = self.expressions(expression, flat=True)
    4135        expressions = f" USING ({expressions})" if expressions else ""
    4136        return f"MASKING POLICY {this}{expressions}"

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

    4138    def gapfill_sql(self, expression: exp.GapFill) -> str:
    4139        this = self.sql(expression, "this")
    4140        this = f"TABLE {this}"
    4141        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

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

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

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

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

    4158    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
    4159        if self.PARSE_JSON_NAME is None:
    4160            return self.sql(expression.this)
    4161
    4162        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)

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

    4164    def rand_sql(self, expression: exp.Rand) -> str:
    4165        lower = self.sql(expression, "lower")
    4166        upper = self.sql(expression, "upper")
    4167
    4168        if lower and upper:
    4169            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
    4170        return self.func("RAND", expression.this)

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

    4172    def changes_sql(self, expression: exp.Changes) -> str:
    4173        information = self.sql(expression, "information")
    4174        information = f"INFORMATION => {information}"
    4175        at_before = self.sql(expression, "at_before")
    4176        at_before = f"{self.seg('')}{at_before}" if at_before else ""
    4177        end = self.sql(expression, "end")
    4178        end = f"{self.seg('')}{end}" if end else ""
    4179
    4180        return f"CHANGES ({information}){at_before}{end}"

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

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

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

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

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

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

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

    4210    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
    4211        exprs = expression.expressions
    4212        if not self.ARRAY_CONCAT_IS_VAR_LEN:
    4213            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
    4214        else:
    4215            rhs = self.expressions(expression)
    4216
    4217        return self.func(name, expression.this, rhs)

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

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

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

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

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

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

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

    4266    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
    4267        else_ = "ELSE " if expression.args.get("else_") else ""
    4268        condition = self.sql(expression, "expression")
    4269        condition = f"WHEN {condition} THEN " if condition else else_
    4270        insert = self.sql(expression, "this")[len("INSERT") :].strip()
    4271        return f"{condition}{insert}"

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

    4273    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
    4274        kind = self.sql(expression, "kind")
    4275        expressions = self.seg(self.expressions(expression, sep=" "))
    4276        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
    4277        return res

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

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

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

    4307    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
    4308        this = self.sql(expression, "this")
    4309        path = self.sql(expression, "path")
    4310
    4311        passing = self.expressions(expression, "passing")
    4312        passing = f" PASSING {passing}" if passing else ""
    4313
    4314        on_condition = self.sql(expression, "on_condition")
    4315        on_condition = f" {on_condition}" if on_condition else ""
    4316
    4317        path = f"{path}{passing}{on_condition}"
    4318
    4319        return self.func("JSON_EXISTS", this, path)

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

    4321    def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
    4322        array_agg = self.function_fallback_sql(expression)
    4323
    4324        if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"):
    4325            parent = expression.parent
    4326            if isinstance(parent, exp.Filter):
    4327                parent_cond = parent.expression.this
    4328                parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_()))
    4329            else:
    4330                # DISTINCT is already present in the agg function, do not propagate it to FILTER as well
    4331                this = expression.this
    4332                this_sql = (
    4333                    self.expressions(this)
    4334                    if isinstance(this, exp.Distinct)
    4335                    else self.sql(expression, "this")
    4336                )
    4337                array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)"
    4338
    4339        return array_agg

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

    4341    def apply_sql(self, expression: exp.Apply) -> str:
    4342        this = self.sql(expression, "this")
    4343        expr = self.sql(expression, "expression")
    4344
    4345        return f"{this} APPLY({expr})"

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

    4347    def grant_sql(self, expression: exp.Grant) -> str:
    4348        privileges_sql = self.expressions(expression, key="privileges", flat=True)
    4349
    4350        kind = self.sql(expression, "kind")
    4351        kind = f" {kind}" if kind else ""
    4352
    4353        securable = self.sql(expression, "securable")
    4354        securable = f" {securable}" if securable else ""
    4355
    4356        principals = self.expressions(expression, key="principals", flat=True)
    4357
    4358        grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else ""
    4359
    4360        return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"

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

    4362    def grantprivilege_sql(self, expression: exp.GrantPrivilege):
    4363        this = self.sql(expression, "this")
    4364        columns = self.expressions(expression, flat=True)
    4365        columns = f"({columns})" if columns else ""
    4366
    4367        return f"{this}{columns}"

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

    4369    def grantprincipal_sql(self, expression: exp.GrantPrincipal):
    4370        this = self.sql(expression, "this")
    4371
    4372        kind = self.sql(expression, "kind")
    4373        kind = f"{kind} " if kind else ""
    4374
    4375        return f"{kind}{this}"