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

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

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

    639    def __init__(
    640        self,
    641        pretty: t.Optional[bool] = None,
    642        identify: str | bool = False,
    643        normalize: bool = False,
    644        pad: int = 2,
    645        indent: int = 2,
    646        normalize_functions: t.Optional[str | bool] = None,
    647        unsupported_level: ErrorLevel = ErrorLevel.WARN,
    648        max_unsupported: int = 3,
    649        leading_comma: bool = False,
    650        max_text_width: int = 80,
    651        comments: bool = True,
    652        dialect: DialectType = None,
    653    ):
    654        import sqlglot
    655        from sqlglot.dialects import Dialect
    656
    657        self.pretty = pretty if pretty is not None else sqlglot.pretty
    658        self.identify = identify
    659        self.normalize = normalize
    660        self.pad = pad
    661        self._indent = indent
    662        self.unsupported_level = unsupported_level
    663        self.max_unsupported = max_unsupported
    664        self.leading_comma = leading_comma
    665        self.max_text_width = max_text_width
    666        self.comments = comments
    667        self.dialect = Dialect.get_or_raise(dialect)
    668
    669        # This is both a Dialect property and a Generator argument, so we prioritize the latter
    670        self.normalize_functions = (
    671            self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
    672        )
    673
    674        self.unsupported_messages: t.List[str] = []
    675        self._escaped_quote_end: str = (
    676            self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END
    677        )
    678        self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2
    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.ArrayContainsAll'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ArrayOverlaps'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.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.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.JSONPathRecursive'>, <class 'sqlglot.expressions.JSONPathWildcard'>, <class 'sqlglot.expressions.JSONPathKey'>, <class 'sqlglot.expressions.JSONPathFilter'>, <class 'sqlglot.expressions.JSONPathUnion'>, <class 'sqlglot.expressions.JSONPathSubscript'>, <class 'sqlglot.expressions.JSONPathSelector'>, <class 'sqlglot.expressions.JSONPathSlice'>, <class 'sqlglot.expressions.JSONPathScript'>, <class 'sqlglot.expressions.JSONPathRoot'>}
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.VARCHAR: 'VARCHAR'>, <Type.CHAR: 'CHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.NCHAR: 'NCHAR'>}
EXPRESSIONS_WITHOUT_NESTED_CTES: Set[Type[sqlglot.expressions.Expression]] = set()
SENTINEL_LINE_BREAK = '__SQLGLOT__LB__'
pretty
identify
normalize
pad
unsupported_level
max_unsupported
leading_comma
max_text_width
comments
dialect
normalize_functions
unsupported_messages: List[str]
def generate( self, expression: sqlglot.expressions.Expression, copy: bool = True) -> str: View Source

    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        expression = self._move_ctes_to_top_level(expression)
    722
    723        if self.ENSURE_BOOLS:
    724            from sqlglot.transforms import ensure_bools
    725
    726            expression = ensure_bools(expression)
    727
    728        return expression

Apply generic preprocessing transformations to a given expression.

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

    741    def unsupported(self, message: str) -> None:
    742        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    743            raise UnsupportedError(message)
    744        self.unsupported_messages.append(message)

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

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

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

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

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

    752    def pad_comment(self, comment: str) -> str:
    753        comment = " " + comment if comment[0].strip() else comment
    754        comment = comment + " " if comment[-1].strip() else comment
    755        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

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

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

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

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

    803    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    804        original = self.identify
    805        self.identify = False
    806        result = func(*args, **kwargs)
    807        self.identify = original
    808        return result

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

    810    def normalize_func(self, name: str) -> str:
    811        if self.normalize_functions == "upper" or self.normalize_functions is True:
    812            return name.upper()
    813        if self.normalize_functions == "lower":
    814            return name.lower()
    815        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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    920    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    921        this = self.sql(expression, "this")
    922        this = f" {this}" if this else ""
    923        position = self.sql(expression, "position")
    924        return f"{position}{this}"

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

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

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

    941    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    942        this = self.sql(expression, "this")
    943        kind_sql = self.sql(expression, "kind").strip()
    944        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

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

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

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

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

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

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

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

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

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

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

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

    1007    def periodforsystemtimeconstraint_sql(
    1008        self, expression: exp.PeriodForSystemTimeConstraint
    1009    ) -> str:
    1010        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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    1183    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    1184        with_ = self.sql(expression, "with")
    1185        if with_:
    1186            sql = f"{with_}{self.sep()}{sql}"
    1187        return sql

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

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

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

    1199    def cte_sql(self, expression: exp.CTE) -> str:
    1200        alias = expression.args.get("alias")
    1201        if alias:
    1202            alias.add_comments(expression.pop_comments())
    1203
    1204        alias_sql = self.sql(expression, "alias")
    1205
    1206        materialized = expression.args.get("materialized")
    1207        if materialized is False:
    1208            materialized = "NOT MATERIALIZED "
    1209        elif materialized:
    1210            materialized = "MATERIALIZED "
    1211
    1212        return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}"

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

    1214    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    1215        alias = self.sql(expression, "this")
    1216        columns = self.expressions(expression, key="columns", flat=True)
    1217        columns = f"({columns})" if columns else ""
    1218
    1219        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
    1220            columns = ""
    1221            self.unsupported("Named columns are not supported in table alias.")
    1222
    1223        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
    1224            alias = self._next_name()
    1225
    1226        return f"{alias}{columns}"

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

    1228    def bitstring_sql(self, expression: exp.BitString) -> str:
    1229        this = self.sql(expression, "this")
    1230        if self.dialect.BIT_START:
    1231            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    1232        return f"{int(this, 2)}"

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

    1234    def hexstring_sql(self, expression: exp.HexString) -> str:
    1235        this = self.sql(expression, "this")
    1236        if self.dialect.HEX_START:
    1237            return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
    1238        return f"{int(this, 16)}"

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

    1240    def bytestring_sql(self, expression: exp.ByteString) -> str:
    1241        this = self.sql(expression, "this")
    1242        if self.dialect.BYTE_START:
    1243            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    1244        return this

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

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

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

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

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

    1273    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    1274        this = self.sql(expression, "this")
    1275        specifier = self.sql(expression, "expression")
    1276        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    1277        return f"{this}{specifier}"

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

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

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

    1315    def directory_sql(self, expression: exp.Directory) -> str:
    1316        local = "LOCAL " if expression.args.get("local") else ""
    1317        row_format = self.sql(expression, "row_format")
    1318        row_format = f" {row_format}" if row_format else ""
    1319        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

    1321    def delete_sql(self, expression: exp.Delete) -> str:
    1322        this = self.sql(expression, "this")
    1323        this = f" FROM {this}" if this else ""
    1324        using = self.sql(expression, "using")
    1325        using = f" USING {using}" if using else ""
    1326        cluster = self.sql(expression, "cluster")
    1327        cluster = f" {cluster}" if cluster else ""
    1328        where = self.sql(expression, "where")
    1329        returning = self.sql(expression, "returning")
    1330        limit = self.sql(expression, "limit")
    1331        tables = self.expressions(expression, key="tables")
    1332        tables = f" {tables}" if tables else ""
    1333        if self.RETURNING_END:
    1334            expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}"
    1335        else:
    1336            expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}"
    1337        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

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

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

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

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

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

    1420    def fetch_sql(self, expression: exp.Fetch) -> str:
    1421        direction = expression.args.get("direction")
    1422        direction = f" {direction}" if direction else ""
    1423        count = self.sql(expression, "count")
    1424        count = f" {count}" if count else ""
    1425        if expression.args.get("percent"):
    1426            count = f"{count} PERCENT"
    1427        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    1428        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"

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

    1430    def filter_sql(self, expression: exp.Filter) -> str:
    1431        if self.AGGREGATE_FILTER_SUPPORTED:
    1432            this = self.sql(expression, "this")
    1433            where = self.sql(expression, "expression").strip()
    1434            return f"{this} FILTER({where})"
    1435
    1436        agg = expression.this
    1437        agg_arg = agg.this
    1438        cond = expression.expression.this
    1439        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1440        return self.sql(agg)

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

    1442    def hint_sql(self, expression: exp.Hint) -> str:
    1443        if not self.QUERY_HINTS:
    1444            self.unsupported("Hints are not supported")
    1445            return ""
    1446
    1447        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

    1449    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
    1450        using = self.sql(expression, "using")
    1451        using = f" USING {using}" if using else ""
    1452        columns = self.expressions(expression, key="columns", flat=True)
    1453        columns = f"({columns})" if columns else ""
    1454        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1455        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1456        where = self.sql(expression, "where")
    1457        include = self.expressions(expression, key="include", flat=True)
    1458        if include:
    1459            include = f" INCLUDE ({include})"
    1460        with_storage = self.expressions(expression, key="with_storage", flat=True)
    1461        with_storage = f" WITH ({with_storage})" if with_storage else ""
    1462        tablespace = self.sql(expression, "tablespace")
    1463        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
    1464        on = self.sql(expression, "on")
    1465        on = f" ON {on}" if on else ""
    1466
    1467        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"

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

    1469    def index_sql(self, expression: exp.Index) -> str:
    1470        unique = "UNIQUE " if expression.args.get("unique") else ""
    1471        primary = "PRIMARY " if expression.args.get("primary") else ""
    1472        amp = "AMP " if expression.args.get("amp") else ""
    1473        name = self.sql(expression, "this")
    1474        name = f"{name} " if name else ""
    1475        table = self.sql(expression, "table")
    1476        table = f"{self.INDEX_ON} {table}" if table else ""
    1477
    1478        index = "INDEX " if not table else ""
    1479
    1480        params = self.sql(expression, "params")
    1481        return f"{unique}{primary}{amp}{index}{name}{table}{params}"

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

    1483    def identifier_sql(self, expression: exp.Identifier) -> str:
    1484        text = expression.name
    1485        lower = text.lower()
    1486        text = lower if self.normalize and not expression.quoted else text
    1487        text = text.replace(self._identifier_end, self._escaped_identifier_end)
    1488        if (
    1489            expression.quoted
    1490            or self.dialect.can_identify(text, self.identify)
    1491            or lower in self.RESERVED_KEYWORDS
    1492            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1493        ):
    1494            text = f"{self._identifier_start}{text}{self._identifier_end}"
    1495        return text

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

    1497    def hex_sql(self, expression: exp.Hex) -> str:
    1498        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1499        if self.dialect.HEX_LOWERCASE:
    1500            text = self.func("LOWER", text)
    1501
    1502        return text

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

    1504    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
    1505        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1506        if not self.dialect.HEX_LOWERCASE:
    1507            text = self.func("LOWER", text)
    1508        return text

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

    1510    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1511        input_format = self.sql(expression, "input_format")
    1512        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1513        output_format = self.sql(expression, "output_format")
    1514        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1515        return self.sep().join((input_format, output_format))

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

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

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

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

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

    1524    def properties_sql(self, expression: exp.Properties) -> str:
    1525        root_properties = []
    1526        with_properties = []
    1527
    1528        for p in expression.expressions:
    1529            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1530            if p_loc == exp.Properties.Location.POST_WITH:
    1531                with_properties.append(p)
    1532            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1533                root_properties.append(p)
    1534
    1535        root_props = self.root_properties(exp.Properties(expressions=root_properties))
    1536        with_props = self.with_properties(exp.Properties(expressions=with_properties))
    1537
    1538        if root_props and with_props and not self.pretty:
    1539            with_props = " " + with_props
    1540
    1541        return root_props + with_props

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

    1543    def root_properties(self, properties: exp.Properties) -> str:
    1544        if properties.expressions:
    1545            return self.expressions(properties, indent=False, sep=" ")
    1546        return ""

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

    1548    def properties(
    1549        self,
    1550        properties: exp.Properties,
    1551        prefix: str = "",
    1552        sep: str = ", ",
    1553        suffix: str = "",
    1554        wrapped: bool = True,
    1555    ) -> str:
    1556        if properties.expressions:
    1557            expressions = self.expressions(properties, sep=sep, indent=False)
    1558            if expressions:
    1559                expressions = self.wrap(expressions) if wrapped else expressions
    1560                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1561        return ""

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

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

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

    1566    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1567        properties_locs = defaultdict(list)
    1568        for p in properties.expressions:
    1569            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1570            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1571                properties_locs[p_loc].append(p)
    1572            else:
    1573                self.unsupported(f"Unsupported property {p.key}")
    1574
    1575        return properties_locs

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

    1577    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1578        if isinstance(expression.this, exp.Dot):
    1579            return self.sql(expression, "this")
    1580        return f"'{expression.name}'" if string_key else expression.name

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

    1582    def property_sql(self, expression: exp.Property) -> str:
    1583        property_cls = expression.__class__
    1584        if property_cls == exp.Property:
    1585            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1586
    1587        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1588        if not property_name:
    1589            self.unsupported(f"Unsupported property {expression.key}")
    1590
    1591        return f"{property_name}={self.sql(expression, 'this')}"

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

    1593    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1594        if self.SUPPORTS_CREATE_TABLE_LIKE:
    1595            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1596            options = f" {options}" if options else ""
    1597
    1598            like = f"LIKE {self.sql(expression, 'this')}{options}"
    1599            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
    1600                like = f"({like})"
    1601
    1602            return like
    1603
    1604        if expression.expressions:
    1605            self.unsupported("Transpilation of LIKE property options is unsupported")
    1606
    1607        select = exp.select("*").from_(expression.this).limit(0)
    1608        return f"AS {self.sql(select)}"

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

    1610    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1611        no = "NO " if expression.args.get("no") else ""
    1612        protection = " PROTECTION" if expression.args.get("protection") else ""
    1613        return f"{no}FALLBACK{protection}"

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

    1615    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1616        no = "NO " if expression.args.get("no") else ""
    1617        local = expression.args.get("local")
    1618        local = f"{local} " if local else ""
    1619        dual = "DUAL " if expression.args.get("dual") else ""
    1620        before = "BEFORE " if expression.args.get("before") else ""
    1621        after = "AFTER " if expression.args.get("after") else ""
    1622        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1624    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1625        freespace = self.sql(expression, "this")
    1626        percent = " PERCENT" if expression.args.get("percent") else ""
    1627        return f"FREESPACE={freespace}{percent}"

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

    1629    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1630        if expression.args.get("default"):
    1631            property = "DEFAULT"
    1632        elif expression.args.get("on"):
    1633            property = "ON"
    1634        else:
    1635            property = "OFF"
    1636        return f"CHECKSUM={property}"

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

    1638    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1639        if expression.args.get("no"):
    1640            return "NO MERGEBLOCKRATIO"
    1641        if expression.args.get("default"):
    1642            return "DEFAULT MERGEBLOCKRATIO"
    1643
    1644        percent = " PERCENT" if expression.args.get("percent") else ""
    1645        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1647    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1648        default = expression.args.get("default")
    1649        minimum = expression.args.get("minimum")
    1650        maximum = expression.args.get("maximum")
    1651        if default or minimum or maximum:
    1652            if default:
    1653                prop = "DEFAULT"
    1654            elif minimum:
    1655                prop = "MINIMUM"
    1656            else:
    1657                prop = "MAXIMUM"
    1658            return f"{prop} DATABLOCKSIZE"
    1659        units = expression.args.get("units")
    1660        units = f" {units}" if units else ""
    1661        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1663    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1664        autotemp = expression.args.get("autotemp")
    1665        always = expression.args.get("always")
    1666        default = expression.args.get("default")
    1667        manual = expression.args.get("manual")
    1668        never = expression.args.get("never")
    1669
    1670        if autotemp is not None:
    1671            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1672        elif always:
    1673            prop = "ALWAYS"
    1674        elif default:
    1675            prop = "DEFAULT"
    1676        elif manual:
    1677            prop = "MANUAL"
    1678        elif never:
    1679            prop = "NEVER"
    1680        return f"BLOCKCOMPRESSION={prop}"

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

    1682    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1683        no = expression.args.get("no")
    1684        no = " NO" if no else ""
    1685        concurrent = expression.args.get("concurrent")
    1686        concurrent = " CONCURRENT" if concurrent else ""
    1687        target = self.sql(expression, "target")
    1688        target = f" {target}" if target else ""
    1689        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"

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

    1691    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1692        if isinstance(expression.this, list):
    1693            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1694        if expression.this:
    1695            modulus = self.sql(expression, "this")
    1696            remainder = self.sql(expression, "expression")
    1697            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1698
    1699        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1700        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1701        return f"FROM ({from_expressions}) TO ({to_expressions})"

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

    1703    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1704        this = self.sql(expression, "this")
    1705
    1706        for_values_or_default = expression.expression
    1707        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1708            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1709        else:
    1710            for_values_or_default = " DEFAULT"
    1711
    1712        return f"PARTITION OF {this}{for_values_or_default}"

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

    1714    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1715        kind = expression.args.get("kind")
    1716        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1717        for_or_in = expression.args.get("for_or_in")
    1718        for_or_in = f" {for_or_in}" if for_or_in else ""
    1719        lock_type = expression.args.get("lock_type")
    1720        override = " OVERRIDE" if expression.args.get("override") else ""
    1721        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"

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

    1723    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1724        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1725        statistics = expression.args.get("statistics")
    1726        statistics_sql = ""
    1727        if statistics is not None:
    1728            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1729        return f"{data_sql}{statistics_sql}"

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

    1731    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1732        this = self.sql(expression, "this")
    1733        this = f"HISTORY_TABLE={this}" if this else ""
    1734        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
    1735        data_consistency = (
    1736            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
    1737        )
    1738        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    1739        retention_period = (
    1740            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
    1741        )
    1742
    1743        if this:
    1744            on_sql = self.func("ON", this, data_consistency, retention_period)
    1745        else:
    1746            on_sql = "ON" if expression.args.get("on") else "OFF"
    1747
    1748        sql = f"SYSTEM_VERSIONING={on_sql}"
    1749
    1750        return f"WITH({sql})" if expression.args.get("with") else sql

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

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

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

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

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

    1799    def kill_sql(self, expression: exp.Kill) -> str:
    1800        kind = self.sql(expression, "kind")
    1801        kind = f" {kind}" if kind else ""
    1802        this = self.sql(expression, "this")
    1803        this = f" {this}" if this else ""
    1804        return f"KILL{kind}{this}"

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

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

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

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

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

    1812    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1813        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1814
    1815        constraint = self.sql(expression, "constraint")
    1816        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
    1817
    1818        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
    1819        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
    1820        action = self.sql(expression, "action")
    1821
    1822        expressions = self.expressions(expression, flat=True)
    1823        if expressions:
    1824            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1825            expressions = f" {set_keyword}{expressions}"
    1826
    1827        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}"

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

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

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

    1832    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1833        fields = self.sql(expression, "fields")
    1834        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1835        escaped = self.sql(expression, "escaped")
    1836        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1837        items = self.sql(expression, "collection_items")
    1838        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1839        keys = self.sql(expression, "map_keys")
    1840        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1841        lines = self.sql(expression, "lines")
    1842        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1843        null = self.sql(expression, "null")
    1844        null = f" NULL DEFINED AS {null}" if null else ""
    1845        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1850    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1851        this = f"{self.sql(expression, 'this')} INDEX"
    1852        target = self.sql(expression, "target")
    1853        target = f" FOR {target}" if target else ""
    1854        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1856    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1857        this = self.sql(expression, "this")
    1858        kind = self.sql(expression, "kind")
    1859        expr = self.sql(expression, "expression")
    1860        return f"{this} ({kind} => {expr})"

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

    1862    def table_parts(self, expression: exp.Table) -> str:
    1863        return ".".join(
    1864            self.sql(part)
    1865            for part in (
    1866                expression.args.get("catalog"),
    1867                expression.args.get("db"),
    1868                expression.args.get("this"),
    1869            )
    1870            if part is not None
    1871        )

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

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

    1923    def tablesample_sql(
    1924        self,
    1925        expression: exp.TableSample,
    1926        tablesample_keyword: t.Optional[str] = None,
    1927    ) -> str:
    1928        method = self.sql(expression, "method")
    1929        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1930        numerator = self.sql(expression, "bucket_numerator")
    1931        denominator = self.sql(expression, "bucket_denominator")
    1932        field = self.sql(expression, "bucket_field")
    1933        field = f" ON {field}" if field else ""
    1934        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1935        seed = self.sql(expression, "seed")
    1936        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
    1937
    1938        size = self.sql(expression, "size")
    1939        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
    1940            size = f"{size} ROWS"
    1941
    1942        percent = self.sql(expression, "percent")
    1943        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
    1944            percent = f"{percent} PERCENT"
    1945
    1946        expr = f"{bucket}{percent}{size}"
    1947        if self.TABLESAMPLE_REQUIRES_PARENS:
    1948            expr = f"({expr})"
    1949
    1950        return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"

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

    1952    def pivot_sql(self, expression: exp.Pivot) -> str:
    1953        expressions = self.expressions(expression, flat=True)
    1954
    1955        if expression.this:
    1956            this = self.sql(expression, "this")
    1957            if not expressions:
    1958                return f"UNPIVOT {this}"
    1959
    1960            on = f"{self.seg('ON')} {expressions}"
    1961            using = self.expressions(expression, key="using", flat=True)
    1962            using = f"{self.seg('USING')} {using}" if using else ""
    1963            group = self.sql(expression, "group")
    1964            return f"PIVOT {this}{on}{using}{group}"
    1965
    1966        alias = self.sql(expression, "alias")
    1967        alias = f" AS {alias}" if alias else ""
    1968        direction = self.seg("UNPIVOT" if expression.unpivot else "PIVOT")
    1969
    1970        field = self.sql(expression, "field")
    1971
    1972        include_nulls = expression.args.get("include_nulls")
    1973        if include_nulls is not None:
    1974            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    1975        else:
    1976            nulls = ""
    1977
    1978        default_on_null = self.sql(expression, "default_on_null")
    1979        default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else ""
    1980        return f"{direction}{nulls}({expressions} FOR {field}{default_on_null}){alias}"

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

    1982    def version_sql(self, expression: exp.Version) -> str:
    1983        this = f"FOR {expression.name}"
    1984        kind = expression.text("kind")
    1985        expr = self.sql(expression, "expression")
    1986        return f"{this} {kind} {expr}"

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

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

    1991    def update_sql(self, expression: exp.Update) -> str:
    1992        this = self.sql(expression, "this")
    1993        set_sql = self.expressions(expression, flat=True)
    1994        from_sql = self.sql(expression, "from")
    1995        where_sql = self.sql(expression, "where")
    1996        returning = self.sql(expression, "returning")
    1997        order = self.sql(expression, "order")
    1998        limit = self.sql(expression, "limit")
    1999        if self.RETURNING_END:
    2000            expression_sql = f"{from_sql}{where_sql}{returning}"
    2001        else:
    2002            expression_sql = f"{returning}{from_sql}{where_sql}"
    2003        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    2004        return self.prepend_ctes(expression, sql)

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

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

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

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

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

    2052    @unsupported_args("expressions")
    2053    def into_sql(self, expression: exp.Into) -> str:
    2054        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    2055        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
    2056        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"

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

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

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

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

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

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

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

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

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

    2073    def group_sql(self, expression: exp.Group) -> str:
    2074        group_by_all = expression.args.get("all")
    2075        if group_by_all is True:
    2076            modifier = " ALL"
    2077        elif group_by_all is False:
    2078            modifier = " DISTINCT"
    2079        else:
    2080            modifier = ""
    2081
    2082        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
    2083
    2084        grouping_sets = self.expressions(expression, key="grouping_sets")
    2085        cube = self.expressions(expression, key="cube")
    2086        rollup = self.expressions(expression, key="rollup")
    2087
    2088        groupings = csv(
    2089            self.seg(grouping_sets) if grouping_sets else "",
    2090            self.seg(cube) if cube else "",
    2091            self.seg(rollup) if rollup else "",
    2092            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    2093            sep=self.GROUPINGS_SEP,
    2094        )
    2095
    2096        if (
    2097            expression.expressions
    2098            and groupings
    2099            and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP")
    2100        ):
    2101            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    2102
    2103        return f"{group_by}{groupings}"

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

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

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

    2109    def connect_sql(self, expression: exp.Connect) -> str:
    2110        start = self.sql(expression, "start")
    2111        start = self.seg(f"START WITH {start}") if start else ""
    2112        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
    2113        connect = self.sql(expression, "connect")
    2114        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
    2115        return start + connect

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

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

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

    2120    def join_sql(self, expression: exp.Join) -> str:
    2121        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    2122            side = None
    2123        else:
    2124            side = expression.side
    2125
    2126        op_sql = " ".join(
    2127            op
    2128            for op in (
    2129                expression.method,
    2130                "GLOBAL" if expression.args.get("global") else None,
    2131                side,
    2132                expression.kind,
    2133                expression.hint if self.JOIN_HINTS else None,
    2134            )
    2135            if op
    2136        )
    2137        match_cond = self.sql(expression, "match_condition")
    2138        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
    2139        on_sql = self.sql(expression, "on")
    2140        using = expression.args.get("using")
    2141
    2142        if not on_sql and using:
    2143            on_sql = csv(*(self.sql(column) for column in using))
    2144
    2145        this = expression.this
    2146        this_sql = self.sql(this)
    2147
    2148        exprs = self.expressions(expression)
    2149        if exprs:
    2150            this_sql = f"{this_sql},{self.seg(exprs)}"
    2151
    2152        if on_sql:
    2153            on_sql = self.indent(on_sql, skip_first=True)
    2154            space = self.seg(" " * self.pad) if self.pretty else " "
    2155            if using:
    2156                on_sql = f"{space}USING ({on_sql})"
    2157            else:
    2158                on_sql = f"{space}ON {on_sql}"
    2159        elif not op_sql:
    2160            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
    2161                return f" {this_sql}"
    2162
    2163            return f", {this_sql}"
    2164
    2165        if op_sql != "STRAIGHT_JOIN":
    2166            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    2167
    2168        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

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

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

    2175    def lateral_op(self, expression: exp.Lateral) -> str:
    2176        cross_apply = expression.args.get("cross_apply")
    2177
    2178        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    2179        if cross_apply is True:
    2180            op = "INNER JOIN "
    2181        elif cross_apply is False:
    2182            op = "LEFT JOIN "
    2183        else:
    2184            op = ""
    2185
    2186        return f"{op}LATERAL"

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

    2188    def lateral_sql(self, expression: exp.Lateral) -> str:
    2189        this = self.sql(expression, "this")
    2190
    2191        if expression.args.get("view"):
    2192            alias = expression.args["alias"]
    2193            columns = self.expressions(alias, key="columns", flat=True)
    2194            table = f" {alias.name}" if alias.name else ""
    2195            columns = f" AS {columns}" if columns else ""
    2196            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    2197            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    2198
    2199        alias = self.sql(expression, "alias")
    2200        alias = f" AS {alias}" if alias else ""
    2201        return f"{self.lateral_op(expression)} {this}{alias}"

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

    2203    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    2204        this = self.sql(expression, "this")
    2205
    2206        args = [
    2207            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    2208            for e in (expression.args.get(k) for k in ("offset", "expression"))
    2209            if e
    2210        ]
    2211
    2212        args_sql = ", ".join(self.sql(e) for e in args)
    2213        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
    2214        expressions = self.expressions(expression, flat=True)
    2215        expressions = f" BY {expressions}" if expressions else ""
    2216
    2217        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}"

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

    2219    def offset_sql(self, expression: exp.Offset) -> str:
    2220        this = self.sql(expression, "this")
    2221        value = expression.expression
    2222        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    2223        expressions = self.expressions(expression, flat=True)
    2224        expressions = f" BY {expressions}" if expressions else ""
    2225        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"

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

    2227    def setitem_sql(self, expression: exp.SetItem) -> str:
    2228        kind = self.sql(expression, "kind")
    2229        kind = f"{kind} " if kind else ""
    2230        this = self.sql(expression, "this")
    2231        expressions = self.expressions(expression)
    2232        collate = self.sql(expression, "collate")
    2233        collate = f" COLLATE {collate}" if collate else ""
    2234        global_ = "GLOBAL " if expression.args.get("global") else ""
    2235        return f"{global_}{kind}{this}{expressions}{collate}"

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

    2237    def set_sql(self, expression: exp.Set) -> str:
    2238        expressions = (
    2239            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    2240        )
    2241        tag = " TAG" if expression.args.get("tag") else ""
    2242        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"

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

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

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

    2247    def lock_sql(self, expression: exp.Lock) -> str:
    2248        if not self.LOCKING_READS_SUPPORTED:
    2249            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    2250            return ""
    2251
    2252        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    2253        expressions = self.expressions(expression, flat=True)
    2254        expressions = f" OF {expressions}" if expressions else ""
    2255        wait = expression.args.get("wait")
    2256
    2257        if wait is not None:
    2258            if isinstance(wait, exp.Literal):
    2259                wait = f" WAIT {self.sql(wait)}"
    2260            else:
    2261                wait = " NOWAIT" if wait else " SKIP LOCKED"
    2262
    2263        return f"{lock_type}{expressions}{wait or ''}"

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

    2265    def literal_sql(self, expression: exp.Literal) -> str:
    2266        text = expression.this or ""
    2267        if expression.is_string:
    2268            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    2269        return text

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

    2271    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
    2272        if self.dialect.ESCAPED_SEQUENCES:
    2273            to_escaped = self.dialect.ESCAPED_SEQUENCES
    2274            text = "".join(
    2275                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
    2276            )
    2277
    2278        return self._replace_line_breaks(text).replace(
    2279            self.dialect.QUOTE_END, self._escaped_quote_end
    2280        )

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

    2282    def loaddata_sql(self, expression: exp.LoadData) -> str:
    2283        local = " LOCAL" if expression.args.get("local") else ""
    2284        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    2285        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    2286        this = f" INTO TABLE {self.sql(expression, 'this')}"
    2287        partition = self.sql(expression, "partition")
    2288        partition = f" {partition}" if partition else ""
    2289        input_format = self.sql(expression, "input_format")
    2290        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    2291        serde = self.sql(expression, "serde")
    2292        serde = f" SERDE {serde}" if serde else ""
    2293        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    2295    def null_sql(self, *_) -> str:
    2296        return "NULL"

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

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

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

    2301    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2302        this = self.sql(expression, "this")
    2303        this = f"{this} " if this else this
    2304        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2305        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

    2307    def withfill_sql(self, expression: exp.WithFill) -> str:
    2308        from_sql = self.sql(expression, "from")
    2309        from_sql = f" FROM {from_sql}" if from_sql else ""
    2310        to_sql = self.sql(expression, "to")
    2311        to_sql = f" TO {to_sql}" if to_sql else ""
    2312        step_sql = self.sql(expression, "step")
    2313        step_sql = f" STEP {step_sql}" if step_sql else ""
    2314        interpolated_values = [
    2315            f"{self.sql(named_expression, 'alias')} AS {self.sql(named_expression, 'this')}"
    2316            for named_expression in expression.args.get("interpolate") or []
    2317        ]
    2318        interpolate = (
    2319            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    2320        )
    2321        return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"

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

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

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

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

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

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

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

    2332    def ordered_sql(self, expression: exp.Ordered) -> str:
    2333        desc = expression.args.get("desc")
    2334        asc = not desc
    2335
    2336        nulls_first = expression.args.get("nulls_first")
    2337        nulls_last = not nulls_first
    2338        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
    2339        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
    2340        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
    2341
    2342        this = self.sql(expression, "this")
    2343
    2344        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
    2345        nulls_sort_change = ""
    2346        if nulls_first and (
    2347            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    2348        ):
    2349            nulls_sort_change = " NULLS FIRST"
    2350        elif (
    2351            nulls_last
    2352            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    2353            and not nulls_are_last
    2354        ):
    2355            nulls_sort_change = " NULLS LAST"
    2356
    2357        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
    2358        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    2359            window = expression.find_ancestor(exp.Window, exp.Select)
    2360            if isinstance(window, exp.Window) and window.args.get("spec"):
    2361                self.unsupported(
    2362                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
    2363                )
    2364                nulls_sort_change = ""
    2365            elif (
    2366                self.NULL_ORDERING_SUPPORTED is False
    2367                and (isinstance(expression.find_ancestor(exp.AggFunc, exp.Select), exp.AggFunc))
    2368                and (
    2369                    (asc and nulls_sort_change == " NULLS LAST")
    2370                    or (desc and nulls_sort_change == " NULLS FIRST")
    2371                )
    2372            ):
    2373                self.unsupported(
    2374                    f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order"
    2375                )
    2376                nulls_sort_change = ""
    2377            elif self.NULL_ORDERING_SUPPORTED is None:
    2378                if expression.this.is_int:
    2379                    self.unsupported(
    2380                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
    2381                    )
    2382                elif not isinstance(expression.this, exp.Rand):
    2383                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
    2384                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
    2385                nulls_sort_change = ""
    2386
    2387        with_fill = self.sql(expression, "with_fill")
    2388        with_fill = f" {with_fill}" if with_fill else ""
    2389
    2390        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"

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

    2392    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
    2393        window_frame = self.sql(expression, "window_frame")
    2394        window_frame = f"{window_frame} " if window_frame else ""
    2395
    2396        this = self.sql(expression, "this")
    2397
    2398        return f"{window_frame}{this}"

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

    2400    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    2401        partition = self.partition_by_sql(expression)
    2402        order = self.sql(expression, "order")
    2403        measures = self.expressions(expression, key="measures")
    2404        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    2405        rows = self.sql(expression, "rows")
    2406        rows = self.seg(rows) if rows else ""
    2407        after = self.sql(expression, "after")
    2408        after = self.seg(after) if after else ""
    2409        pattern = self.sql(expression, "pattern")
    2410        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    2411        definition_sqls = [
    2412            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    2413            for definition in expression.args.get("define", [])
    2414        ]
    2415        definitions = self.expressions(sqls=definition_sqls)
    2416        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    2417        body = "".join(
    2418            (
    2419                partition,
    2420                order,
    2421                measures,
    2422                rows,
    2423                after,
    2424                pattern,
    2425                define,
    2426            )
    2427        )
    2428        alias = self.sql(expression, "alias")
    2429        alias = f" {alias}" if alias else ""
    2430        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    2432    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    2433        limit = expression.args.get("limit")
    2434
    2435        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    2436            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    2437        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    2438            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    2439
    2440        return csv(
    2441            *sqls,
    2442            *[self.sql(join) for join in expression.args.get("joins") or []],
    2443            self.sql(expression, "connect"),
    2444            self.sql(expression, "match"),
    2445            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2446            self.sql(expression, "prewhere"),
    2447            self.sql(expression, "where"),
    2448            self.sql(expression, "group"),
    2449            self.sql(expression, "having"),
    2450            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
    2451            self.sql(expression, "order"),
    2452            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
    2453            *self.after_limit_modifiers(expression),
    2454            self.options_modifier(expression),
    2455            sep="",
    2456        )

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

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

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

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

    2465    def offset_limit_modifiers(
    2466        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2467    ) -> t.List[str]:
    2468        return [
    2469            self.sql(expression, "offset") if fetch else self.sql(limit),
    2470            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2471        ]

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

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

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

    2478    def select_sql(self, expression: exp.Select) -> str:
    2479        into = expression.args.get("into")
    2480        if not self.SUPPORTS_SELECT_INTO and into:
    2481            into.pop()
    2482
    2483        hint = self.sql(expression, "hint")
    2484        distinct = self.sql(expression, "distinct")
    2485        distinct = f" {distinct}" if distinct else ""
    2486        kind = self.sql(expression, "kind")
    2487
    2488        limit = expression.args.get("limit")
    2489        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
    2490            top = self.limit_sql(limit, top=True)
    2491            limit.pop()
    2492        else:
    2493            top = ""
    2494
    2495        expressions = self.expressions(expression)
    2496
    2497        if kind:
    2498            if kind in self.SELECT_KINDS:
    2499                kind = f" AS {kind}"
    2500            else:
    2501                if kind == "STRUCT":
    2502                    expressions = self.expressions(
    2503                        sqls=[
    2504                            self.sql(
    2505                                exp.Struct(
    2506                                    expressions=[
    2507                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
    2508                                        if isinstance(e, exp.Alias)
    2509                                        else e
    2510                                        for e in expression.expressions
    2511                                    ]
    2512                                )
    2513                            )
    2514                        ]
    2515                    )
    2516                kind = ""
    2517
    2518        operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ")
    2519        operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else ""
    2520
    2521        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
    2522        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
    2523        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
    2524        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    2525        sql = self.query_modifiers(
    2526            expression,
    2527            f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}",
    2528            self.sql(expression, "into", comment=False),
    2529            self.sql(expression, "from", comment=False),
    2530        )
    2531
    2532        # If both the CTE and SELECT clauses have comments, generate the latter earlier
    2533        if expression.args.get("with"):
    2534            sql = self.maybe_comment(sql, expression)
    2535            expression.pop_comments()
    2536
    2537        sql = self.prepend_ctes(expression, sql)
    2538
    2539        if not self.SUPPORTS_SELECT_INTO and into:
    2540            if into.args.get("temporary"):
    2541                table_kind = " TEMPORARY"
    2542            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
    2543                table_kind = " UNLOGGED"
    2544            else:
    2545                table_kind = ""
    2546            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
    2547
    2548        return sql

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

    2550    def schema_sql(self, expression: exp.Schema) -> str:
    2551        this = self.sql(expression, "this")
    2552        sql = self.schema_columns_sql(expression)
    2553        return f"{this} {sql}" if this and sql else this or sql

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

    2555    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2556        if expression.expressions:
    2557            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2558        return ""

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

    2560    def star_sql(self, expression: exp.Star) -> str:
    2561        except_ = self.expressions(expression, key="except", flat=True)
    2562        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
    2563        replace = self.expressions(expression, key="replace", flat=True)
    2564        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
    2565        rename = self.expressions(expression, key="rename", flat=True)
    2566        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
    2567        return f"*{except_}{replace}{rename}"

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

    2569    def parameter_sql(self, expression: exp.Parameter) -> str:
    2570        this = self.sql(expression, "this")
    2571        return f"{self.PARAMETER_TOKEN}{this}"

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

    2573    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2574        this = self.sql(expression, "this")
    2575        kind = expression.text("kind")
    2576        if kind:
    2577            kind = f"{kind}."
    2578        return f"@@{kind}{this}"

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

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

    2583    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2584        alias = self.sql(expression, "alias")
    2585        alias = f"{sep}{alias}" if alias else ""
    2586        sample = self.sql(expression, "sample")
    2587        if self.dialect.ALIAS_POST_TABLESAMPLE and sample:
    2588            alias = f"{sample}{alias}"
    2589
    2590            # Set to None so it's not generated again by self.query_modifiers()
    2591            expression.set("sample", None)
    2592
    2593        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2594        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2595        return self.prepend_ctes(expression, sql)

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

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

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

    2601    def unnest_sql(self, expression: exp.Unnest) -> str:
    2602        args = self.expressions(expression, flat=True)
    2603
    2604        alias = expression.args.get("alias")
    2605        offset = expression.args.get("offset")
    2606
    2607        if self.UNNEST_WITH_ORDINALITY:
    2608            if alias and isinstance(offset, exp.Expression):
    2609                alias.append("columns", offset)
    2610
    2611        if alias and self.dialect.UNNEST_COLUMN_ONLY:
    2612            columns = alias.columns
    2613            alias = self.sql(columns[0]) if columns else ""
    2614        else:
    2615            alias = self.sql(alias)
    2616
    2617        alias = f" AS {alias}" if alias else alias
    2618        if self.UNNEST_WITH_ORDINALITY:
    2619            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2620        else:
    2621            if isinstance(offset, exp.Expression):
    2622                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2623            elif offset:
    2624                suffix = f"{alias} WITH OFFSET"
    2625            else:
    2626                suffix = alias
    2627
    2628        return f"UNNEST({args}){suffix}"

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

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

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

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

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

    2637    def window_sql(self, expression: exp.Window) -> str:
    2638        this = self.sql(expression, "this")
    2639        partition = self.partition_by_sql(expression)
    2640        order = expression.args.get("order")
    2641        order = self.order_sql(order, flat=True) if order else ""
    2642        spec = self.sql(expression, "spec")
    2643        alias = self.sql(expression, "alias")
    2644        over = self.sql(expression, "over") or "OVER"
    2645
    2646        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2647
    2648        first = expression.args.get("first")
    2649        if first is None:
    2650            first = ""
    2651        else:
    2652            first = "FIRST" if first else "LAST"
    2653
    2654        if not partition and not order and not spec and alias:
    2655            return f"{this} {alias}"
    2656
    2657        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    2658        return f"{this} ({args})"

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

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

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

    2664    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2665        kind = self.sql(expression, "kind")
    2666        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2667        end = (
    2668            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2669            or "CURRENT ROW"
    2670        )
    2671        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    2678    def between_sql(self, expression: exp.Between) -> str:
    2679        this = self.sql(expression, "this")
    2680        low = self.sql(expression, "low")
    2681        high = self.sql(expression, "high")
    2682        return f"{this} BETWEEN {low} AND {high}"

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

    2684    def bracket_offset_expressions(
    2685        self, expression: exp.Bracket, index_offset: t.Optional[int] = None
    2686    ) -> t.List[exp.Expression]:
    2687        return apply_index_offset(
    2688            expression.this,
    2689            expression.expressions,
    2690            (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0),
    2691        )

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

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

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

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

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

    2701    def any_sql(self, expression: exp.Any) -> str:
    2702        this = self.sql(expression, "this")
    2703        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
    2704            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2705                this = self.wrap(this)
    2706            return f"ANY{this}"
    2707        return f"ANY {this}"

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

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

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

    2712    def case_sql(self, expression: exp.Case) -> str:
    2713        this = self.sql(expression, "this")
    2714        statements = [f"CASE {this}" if this else "CASE"]
    2715
    2716        for e in expression.args["ifs"]:
    2717            statements.append(f"WHEN {self.sql(e, 'this')}")
    2718            statements.append(f"THEN {self.sql(e, 'true')}")
    2719
    2720        default = self.sql(expression, "default")
    2721
    2722        if default:
    2723            statements.append(f"ELSE {default}")
    2724
    2725        statements.append("END")
    2726
    2727        if self.pretty and self.too_wide(statements):
    2728            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2729
    2730        return " ".join(statements)

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

    2732    def constraint_sql(self, expression: exp.Constraint) -> str:
    2733        this = self.sql(expression, "this")
    2734        expressions = self.expressions(expression, flat=True)
    2735        return f"CONSTRAINT {this} {expressions}"

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

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

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

    2742    def extract_sql(self, expression: exp.Extract) -> str:
    2743        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2744        expression_sql = self.sql(expression, "expression")
    2745        return f"EXTRACT({this} FROM {expression_sql})"

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

    2747    def trim_sql(self, expression: exp.Trim) -> str:
    2748        trim_type = self.sql(expression, "position")
    2749
    2750        if trim_type == "LEADING":
    2751            func_name = "LTRIM"
    2752        elif trim_type == "TRAILING":
    2753            func_name = "RTRIM"
    2754        else:
    2755            func_name = "TRIM"
    2756
    2757        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

    2759    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2760        args = expression.expressions
    2761        if isinstance(expression, exp.ConcatWs):
    2762            args = args[1:]  # Skip the delimiter
    2763
    2764        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2765            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
    2766
    2767        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2768            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2769
    2770        return args

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

    2772    def concat_sql(self, expression: exp.Concat) -> str:
    2773        expressions = self.convert_concat_args(expression)
    2774
    2775        # Some dialects don't allow a single-argument CONCAT call
    2776        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2777            return self.sql(expressions[0])
    2778
    2779        return self.func("CONCAT", *expressions)

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

    2781    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2782        return self.func(
    2783            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2784        )

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

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

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

    2790    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2791        expressions = self.expressions(expression, flat=True)
    2792        reference = self.sql(expression, "reference")
    2793        reference = f" {reference}" if reference else ""
    2794        delete = self.sql(expression, "delete")
    2795        delete = f" ON DELETE {delete}" if delete else ""
    2796        update = self.sql(expression, "update")
    2797        update = f" ON UPDATE {update}" if update else ""
    2798        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"

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

    2800    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2801        expressions = self.expressions(expression, flat=True)
    2802        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2803        options = f" {options}" if options else ""
    2804        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

    2817    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
    2818        path = self.expressions(expression, sep="", flat=True).lstrip(".")
    2819
    2820        if expression.args.get("escape"):
    2821            path = self.escape_str(path)
    2822
    2823        if self.QUOTE_JSON_PATH:
    2824            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
    2825
    2826        return path

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

    2828    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
    2829        if isinstance(expression, exp.JSONPathPart):
    2830            transform = self.TRANSFORMS.get(expression.__class__)
    2831            if not callable(transform):
    2832                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
    2833                return ""
    2834
    2835            return transform(self, expression)
    2836
    2837        if isinstance(expression, int):
    2838            return str(expression)
    2839
    2840        if self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
    2841            escaped = expression.replace("'", "\\'")
    2842            escaped = f"\\'{expression}\\'"
    2843        else:
    2844            escaped = expression.replace('"', '\\"')
    2845            escaped = f'"{escaped}"'
    2846
    2847        return escaped

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

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

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

    2852    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    2853        null_handling = expression.args.get("null_handling")
    2854        null_handling = f" {null_handling}" if null_handling else ""
    2855
    2856        unique_keys = expression.args.get("unique_keys")
    2857        if unique_keys is not None:
    2858            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2859        else:
    2860            unique_keys = ""
    2861
    2862        return_type = self.sql(expression, "return_type")
    2863        return_type = f" RETURNING {return_type}" if return_type else ""
    2864        encoding = self.sql(expression, "encoding")
    2865        encoding = f" ENCODING {encoding}" if encoding else ""
    2866
    2867        return self.func(
    2868            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    2869            *expression.expressions,
    2870            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2871        )

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

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

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

    2876    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2877        null_handling = expression.args.get("null_handling")
    2878        null_handling = f" {null_handling}" if null_handling else ""
    2879        return_type = self.sql(expression, "return_type")
    2880        return_type = f" RETURNING {return_type}" if return_type else ""
    2881        strict = " STRICT" if expression.args.get("strict") else ""
    2882        return self.func(
    2883            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2884        )

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

    2886    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2887        this = self.sql(expression, "this")
    2888        order = self.sql(expression, "order")
    2889        null_handling = expression.args.get("null_handling")
    2890        null_handling = f" {null_handling}" if null_handling else ""
    2891        return_type = self.sql(expression, "return_type")
    2892        return_type = f" RETURNING {return_type}" if return_type else ""
    2893        strict = " STRICT" if expression.args.get("strict") else ""
    2894        return self.func(
    2895            "JSON_ARRAYAGG",
    2896            this,
    2897            suffix=f"{order}{null_handling}{return_type}{strict})",
    2898        )

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

    2900    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2901        path = self.sql(expression, "path")
    2902        path = f" PATH {path}" if path else ""
    2903        nested_schema = self.sql(expression, "nested_schema")
    2904
    2905        if nested_schema:
    2906            return f"NESTED{path} {nested_schema}"
    2907
    2908        this = self.sql(expression, "this")
    2909        kind = self.sql(expression, "kind")
    2910        kind = f" {kind}" if kind else ""
    2911        return f"{this}{kind}{path}"

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

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

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

    2916    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    2917        this = self.sql(expression, "this")
    2918        path = self.sql(expression, "path")
    2919        path = f", {path}" if path else ""
    2920        error_handling = expression.args.get("error_handling")
    2921        error_handling = f" {error_handling}" if error_handling else ""
    2922        empty_handling = expression.args.get("empty_handling")
    2923        empty_handling = f" {empty_handling}" if empty_handling else ""
    2924        schema = self.sql(expression, "schema")
    2925        return self.func(
    2926            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    2927        )

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

    2929    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    2930        this = self.sql(expression, "this")
    2931        kind = self.sql(expression, "kind")
    2932        path = self.sql(expression, "path")
    2933        path = f" {path}" if path else ""
    2934        as_json = " AS JSON" if expression.args.get("as_json") else ""
    2935        return f"{this} {kind}{path}{as_json}"

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

    2937    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    2938        this = self.sql(expression, "this")
    2939        path = self.sql(expression, "path")
    2940        path = f", {path}" if path else ""
    2941        expressions = self.expressions(expression)
    2942        with_ = (
    2943            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2944            if expressions
    2945            else ""
    2946        )
    2947        return f"OPENJSON({this}{path}){with_}"

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

    2949    def in_sql(self, expression: exp.In) -> str:
    2950        query = expression.args.get("query")
    2951        unnest = expression.args.get("unnest")
    2952        field = expression.args.get("field")
    2953        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    2954
    2955        if query:
    2956            in_sql = self.sql(query)
    2957        elif unnest:
    2958            in_sql = self.in_unnest_op(unnest)
    2959        elif field:
    2960            in_sql = self.sql(field)
    2961        else:
    2962            in_sql = f"({self.expressions(expression, flat=True)})"
    2963
    2964        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    2969    def interval_sql(self, expression: exp.Interval) -> str:
    2970        unit = self.sql(expression, "unit")
    2971        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    2972            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    2973        unit = f" {unit}" if unit else ""
    2974
    2975        if self.SINGLE_STRING_INTERVAL:
    2976            this = expression.this.name if expression.this else ""
    2977            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    2978
    2979        this = self.sql(expression, "this")
    2980        if this:
    2981            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    2982            this = f" {this}" if unwrapped else f" ({this})"
    2983
    2984        return f"INTERVAL{this}{unit}"

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

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

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

    2989    def reference_sql(self, expression: exp.Reference) -> str:
    2990        this = self.sql(expression, "this")
    2991        expressions = self.expressions(expression, flat=True)
    2992        expressions = f"({expressions})" if expressions else ""
    2993        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2994        options = f" {options}" if options else ""
    2995        return f"REFERENCES {this}{expressions}{options}"

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

    2997    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    2998        # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive
    2999        parent = expression.parent
    3000        is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression
    3001        return self.func(
    3002            self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified
    3003        )

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

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

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

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

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

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

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

    3018    def alias_sql(self, expression: exp.Alias) -> str:
    3019        alias = self.sql(expression, "alias")
    3020        alias = f" AS {alias}" if alias else ""
    3021        return f"{self.sql(expression, 'this')}{alias}"

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

    3023    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    3024        alias = expression.args["alias"]
    3025
    3026        identifier_alias = isinstance(alias, exp.Identifier)
    3027        literal_alias = isinstance(alias, exp.Literal)
    3028
    3029        if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3030            alias.replace(exp.Literal.string(alias.output_name))
    3031        elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3032            alias.replace(exp.to_identifier(alias.output_name))
    3033
    3034        return self.alias_sql(expression)

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

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

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

    3039    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    3040        this = self.sql(expression, "this")
    3041        index = self.sql(expression, "expression")
    3042        return f"{this} AT {index}"

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

    3044    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    3045        this = self.sql(expression, "this")
    3046        zone = self.sql(expression, "zone")
    3047        return f"{this} AT TIME ZONE {zone}"

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

    3049    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    3050        this = self.sql(expression, "this")
    3051        zone = self.sql(expression, "zone")
    3052        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"

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

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

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

    3057    def and_sql(
    3058        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
    3059    ) -> str:
    3060        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

    3062    def or_sql(
    3063        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
    3064    ) -> str:
    3065        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

    3067    def xor_sql(
    3068        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
    3069    ) -> str:
    3070        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

    3072    def connector_sql(
    3073        self,
    3074        expression: exp.Connector,
    3075        op: str,
    3076        stack: t.Optional[t.List[str | exp.Expression]] = None,
    3077    ) -> str:
    3078        if stack is not None:
    3079            if expression.expressions:
    3080                stack.append(self.expressions(expression, sep=f" {op} "))
    3081            else:
    3082                stack.append(expression.right)
    3083                if expression.comments and self.comments:
    3084                    for comment in expression.comments:
    3085                        if comment:
    3086                            op += f" /*{self.pad_comment(comment)}*/"
    3087                stack.extend((op, expression.left))
    3088            return op
    3089
    3090        stack = [expression]
    3091        sqls: t.List[str] = []
    3092        ops = set()
    3093
    3094        while stack:
    3095            node = stack.pop()
    3096            if isinstance(node, exp.Connector):
    3097                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
    3098            else:
    3099                sql = self.sql(node)
    3100                if sqls and sqls[-1] in ops:
    3101                    sqls[-1] += f" {sql}"
    3102                else:
    3103                    sqls.append(sql)
    3104
    3105        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
    3106        return sep.join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

    3126    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    3127        format_sql = self.sql(expression, "format")
    3128        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    3129        to_sql = self.sql(expression, "to")
    3130        to_sql = f" {to_sql}" if to_sql else ""
    3131        action = self.sql(expression, "action")
    3132        action = f" {action}" if action else ""
    3133        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

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

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

    3139    def collate_sql(self, expression: exp.Collate) -> str:
    3140        if self.COLLATE_IS_FUNC:
    3141            return self.function_fallback_sql(expression)
    3142        return self.binary(expression, "COLLATE")

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

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

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

    3147    def comment_sql(self, expression: exp.Comment) -> str:
    3148        this = self.sql(expression, "this")
    3149        kind = expression.args["kind"]
    3150        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    3151        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    3152        expression_sql = self.sql(expression, "expression")
    3153        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"

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

    3155    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    3156        this = self.sql(expression, "this")
    3157        delete = " DELETE" if expression.args.get("delete") else ""
    3158        recompress = self.sql(expression, "recompress")
    3159        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    3160        to_disk = self.sql(expression, "to_disk")
    3161        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    3162        to_volume = self.sql(expression, "to_volume")
    3163        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    3164        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    3166    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    3167        where = self.sql(expression, "where")
    3168        group = self.sql(expression, "group")
    3169        aggregates = self.expressions(expression, key="aggregates")
    3170        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    3171
    3172        if not (where or group or aggregates) and len(expression.expressions) == 1:
    3173            return f"TTL {self.expressions(expression, flat=True)}"
    3174
    3175        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    3180    def commit_sql(self, expression: exp.Commit) -> str:
    3181        chain = expression.args.get("chain")
    3182        if chain is not None:
    3183            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    3184
    3185        return f"COMMIT{chain or ''}"

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

    3187    def rollback_sql(self, expression: exp.Rollback) -> str:
    3188        savepoint = expression.args.get("savepoint")
    3189        savepoint = f" TO {savepoint}" if savepoint else ""
    3190        return f"ROLLBACK{savepoint}"

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

    3192    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    3193        this = self.sql(expression, "this")
    3194
    3195        dtype = self.sql(expression, "dtype")
    3196        if dtype:
    3197            collate = self.sql(expression, "collate")
    3198            collate = f" COLLATE {collate}" if collate else ""
    3199            using = self.sql(expression, "using")
    3200            using = f" USING {using}" if using else ""
    3201            return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}"
    3202
    3203        default = self.sql(expression, "default")
    3204        if default:
    3205            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    3206
    3207        comment = self.sql(expression, "comment")
    3208        if comment:
    3209            return f"ALTER COLUMN {this} COMMENT {comment}"
    3210
    3211        allow_null = expression.args.get("allow_null")
    3212        drop = expression.args.get("drop")
    3213
    3214        if not drop and not allow_null:
    3215            self.unsupported("Unsupported ALTER COLUMN syntax")
    3216
    3217        if allow_null is not None:
    3218            keyword = "DROP" if drop else "SET"
    3219            return f"ALTER COLUMN {this} {keyword} NOT NULL"
    3220
    3221        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    3223    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
    3224        this = self.sql(expression, "this")
    3225        if not isinstance(expression.this, exp.Var):
    3226            this = f"KEY DISTKEY {this}"
    3227        return f"ALTER DISTSTYLE {this}"

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

    3229    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
    3230        compound = " COMPOUND" if expression.args.get("compound") else ""
    3231        this = self.sql(expression, "this")
    3232        expressions = self.expressions(expression, flat=True)
    3233        expressions = f"({expressions})" if expressions else ""
    3234        return f"ALTER{compound} SORTKEY {this or expressions}"

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

    3236    def alterrename_sql(self, expression: exp.AlterRename) -> str:
    3237        if not self.RENAME_TABLE_WITH_DB:
    3238            # Remove db from tables
    3239            expression = expression.transform(
    3240                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    3241            ).assert_is(exp.AlterRename)
    3242        this = self.sql(expression, "this")
    3243        return f"RENAME TO {this}"

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

    3245    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    3246        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3247        old_column = self.sql(expression, "this")
    3248        new_column = self.sql(expression, "to")
    3249        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"

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

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

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

    3255    def alter_sql(self, expression: exp.Alter) -> str:
    3256        actions = expression.args["actions"]
    3257
    3258        if isinstance(actions[0], exp.ColumnDef):
    3259            actions = self.add_column_sql(expression)
    3260        elif isinstance(actions[0], exp.Schema):
    3261            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    3262        elif isinstance(actions[0], exp.Delete):
    3263            actions = self.expressions(expression, key="actions", flat=True)
    3264        elif isinstance(actions[0], exp.Query):
    3265            actions = "AS " + self.expressions(expression, key="actions")
    3266        else:
    3267            actions = self.expressions(expression, key="actions", flat=True)
    3268
    3269        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3270        on_cluster = self.sql(expression, "cluster")
    3271        on_cluster = f" {on_cluster}" if on_cluster else ""
    3272        only = " ONLY" if expression.args.get("only") else ""
    3273        options = self.expressions(expression, key="options")
    3274        options = f", {options}" if options else ""
    3275        kind = self.sql(expression, "kind")
    3276        not_valid = " NOT VALID" if expression.args.get("not_valid") else ""
    3277
    3278        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

    3280    def add_column_sql(self, expression: exp.Alter) -> str:
    3281        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    3282            return self.expressions(
    3283                expression,
    3284                key="actions",
    3285                prefix="ADD COLUMN ",
    3286                skip_first=True,
    3287            )
    3288        return f"ADD {self.expressions(expression, key='actions', flat=True)}"

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

    3290    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    3291        expressions = self.expressions(expression)
    3292        exists = " IF EXISTS " if expression.args.get("exists") else " "
    3293        return f"DROP{exists}{expressions}"

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

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

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

    3298    def distinct_sql(self, expression: exp.Distinct) -> str:
    3299        this = self.expressions(expression, flat=True)
    3300
    3301        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    3302            case = exp.case()
    3303            for arg in expression.expressions:
    3304                case = case.when(arg.is_(exp.null()), exp.null())
    3305            this = self.sql(case.else_(f"({this})"))
    3306
    3307        this = f" {this}" if this else ""
    3308
    3309        on = self.sql(expression, "on")
    3310        on = f" ON {on}" if on else ""
    3311        return f"DISTINCT{this}{on}"

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

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

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

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

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

    3319    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    3320        this_sql = self.sql(expression, "this")
    3321        expression_sql = self.sql(expression, "expression")
    3322        kind = "MAX" if expression.args.get("max") else "MIN"
    3323        return f"{this_sql} HAVING {kind} {expression_sql}"

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

    3325    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    3326        return self.sql(
    3327            exp.Cast(
    3328                this=exp.Div(this=expression.this, expression=expression.expression),
    3329                to=exp.DataType(this=exp.DataType.Type.INT),
    3330            )
    3331        )

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

    3333    def dpipe_sql(self, expression: exp.DPipe) -> str:
    3334        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    3335            return self.func(
    3336                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
    3337            )
    3338        return self.binary(expression, "||")

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

    3340    def div_sql(self, expression: exp.Div) -> str:
    3341        l, r = expression.left, expression.right
    3342
    3343        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    3344            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    3345
    3346        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    3347            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
    3348                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    3349
    3350        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    3351            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    3352                return self.sql(
    3353                    exp.cast(
    3354                        l / r,
    3355                        to=exp.DataType.Type.BIGINT,
    3356                    )
    3357                )
    3358
    3359        return self.binary(expression, "/")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3394    def is_sql(self, expression: exp.Is) -> str:
    3395        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3396            return self.sql(
    3397                expression.this if expression.expression.this else exp.not_(expression.this)
    3398            )
    3399        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3440    def try_sql(self, expression: exp.Try) -> str:
    3441        if not self.TRY_SUPPORTED:
    3442            self.unsupported("Unsupported TRY function")
    3443            return self.sql(expression, "this")
    3444
    3445        return self.func("TRY", expression.this)

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

    3447    def log_sql(self, expression: exp.Log) -> str:
    3448        this = expression.this
    3449        expr = expression.expression
    3450
    3451        if self.dialect.LOG_BASE_FIRST is False:
    3452            this, expr = expr, this
    3453        elif self.dialect.LOG_BASE_FIRST is None and expr:
    3454            if this.name in ("2", "10"):
    3455                return self.func(f"LOG{this.name}", expr)
    3456
    3457            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
    3458
    3459        return self.func("LOG", this, expr)

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

    3461    def use_sql(self, expression: exp.Use) -> str:
    3462        kind = self.sql(expression, "kind")
    3463        kind = f" {kind}" if kind else ""
    3464        this = self.sql(expression, "this")
    3465        this = f" {this}" if this else ""
    3466        return f"USE{kind}{this}"

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

    3468    def binary(self, expression: exp.Binary, op: str) -> str:
    3469        sqls: t.List[str] = []
    3470        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    3471        binary_type = type(expression)
    3472
    3473        while stack:
    3474            node = stack.pop()
    3475
    3476            if type(node) is binary_type:
    3477                op_func = node.args.get("operator")
    3478                if op_func:
    3479                    op = f"OPERATOR({self.sql(op_func)})"
    3480
    3481                stack.append(node.right)
    3482                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
    3483                stack.append(node.left)
    3484            else:
    3485                sqls.append(self.sql(node))
    3486
    3487        return "".join(sqls)

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

    3489    def function_fallback_sql(self, expression: exp.Func) -> str:
    3490        args = []
    3491
    3492        for key in expression.arg_types:
    3493            arg_value = expression.args.get(key)
    3494
    3495            if isinstance(arg_value, list):
    3496                for value in arg_value:
    3497                    args.append(value)
    3498            elif arg_value is not None:
    3499                args.append(arg_value)
    3500
    3501        if self.normalize_functions:
    3502            name = expression.sql_name()
    3503        else:
    3504            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3505
    3506        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

    3508    def func(
    3509        self,
    3510        name: str,
    3511        *args: t.Optional[exp.Expression | str],
    3512        prefix: str = "(",
    3513        suffix: str = ")",
    3514        normalize: bool = True,
    3515    ) -> str:
    3516        name = self.normalize_func(name) if normalize else name
    3517        return f"{name}{prefix}{self.format_args(*args)}{suffix}"

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

    3519    def format_args(self, *args: t.Optional[str | exp.Expression]) -> str:
    3520        arg_sqls = tuple(
    3521            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
    3522        )
    3523        if self.pretty and self.too_wide(arg_sqls):
    3524            return self.indent("\n" + ",\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True)
    3525        return ", ".join(arg_sqls)

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

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

    3530    def format_time(
    3531        self,
    3532        expression: exp.Expression,
    3533        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
    3534        inverse_time_trie: t.Optional[t.Dict] = None,
    3535    ) -> t.Optional[str]:
    3536        return format_time(
    3537            self.sql(expression, "format"),
    3538            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
    3539            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
    3540        )

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

    3542    def expressions(
    3543        self,
    3544        expression: t.Optional[exp.Expression] = None,
    3545        key: t.Optional[str] = None,
    3546        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    3547        flat: bool = False,
    3548        indent: bool = True,
    3549        skip_first: bool = False,
    3550        skip_last: bool = False,
    3551        sep: str = ", ",
    3552        prefix: str = "",
    3553        dynamic: bool = False,
    3554        new_line: bool = False,
    3555    ) -> str:
    3556        expressions = expression.args.get(key or "expressions") if expression else sqls
    3557
    3558        if not expressions:
    3559            return ""
    3560
    3561        if flat:
    3562            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    3563
    3564        num_sqls = len(expressions)
    3565        result_sqls = []
    3566
    3567        for i, e in enumerate(expressions):
    3568            sql = self.sql(e, comment=False)
    3569            if not sql:
    3570                continue
    3571
    3572            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    3573
    3574            if self.pretty:
    3575                if self.leading_comma:
    3576                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
    3577                else:
    3578                    result_sqls.append(
    3579                        f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}"
    3580                    )
    3581            else:
    3582                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    3583
    3584        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
    3585            if new_line:
    3586                result_sqls.insert(0, "")
    3587                result_sqls.append("")
    3588            result_sql = "\n".join(s.rstrip() for s in result_sqls)
    3589        else:
    3590            result_sql = "".join(result_sqls)
    3591
    3592        return (
    3593            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
    3594            if indent
    3595            else result_sql
    3596        )

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

    3598    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3599        flat = flat or isinstance(expression.parent, exp.Properties)
    3600        expressions_sql = self.expressions(expression, flat=flat)
    3601        if flat:
    3602            return f"{op} {expressions_sql}"
    3603        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    3605    def naked_property(self, expression: exp.Property) -> str:
    3606        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3607        if not property_name:
    3608            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3609        return f"{property_name} {self.sql(expression, 'this')}"

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

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

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

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

    3617    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3618        this = self.sql(expression, "this")
    3619        expressions = self.no_identify(self.expressions, expression)
    3620        expressions = (
    3621            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3622        )
    3623        return f"{this}{expressions}"

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

    3625    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3626        this = self.sql(expression, "this")
    3627        expressions = self.expressions(expression, flat=True)
    3628        return f"{this}({expressions})"

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

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

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

    3633    def when_sql(self, expression: exp.When) -> str:
    3634        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3635        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3636        condition = self.sql(expression, "condition")
    3637        condition = f" AND {condition}" if condition else ""
    3638
    3639        then_expression = expression.args.get("then")
    3640        if isinstance(then_expression, exp.Insert):
    3641            this = self.sql(then_expression, "this")
    3642            this = f"INSERT {this}" if this else "INSERT"
    3643            then = self.sql(then_expression, "expression")
    3644            then = f"{this} VALUES {then}" if then else this
    3645        elif isinstance(then_expression, exp.Update):
    3646            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3647                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3648            else:
    3649                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    3650        else:
    3651            then = self.sql(then_expression)
    3652        return f"WHEN {matched}{source}{condition} THEN {then}"

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

    3654    def merge_sql(self, expression: exp.Merge) -> str:
    3655        table = expression.this
    3656        table_alias = ""
    3657
    3658        hints = table.args.get("hints")
    3659        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3660            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3661            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3662
    3663        this = self.sql(table)
    3664        using = f"USING {self.sql(expression, 'using')}"
    3665        on = f"ON {self.sql(expression, 'on')}"
    3666        expressions = self.expressions(expression, sep=" ", indent=False)
    3667        returning = self.sql(expression, "returning")
    3668        if returning:
    3669            expressions = f"{expressions}{returning}"
    3670
    3671        sep = self.sep()
    3672
    3673        return self.prepend_ctes(
    3674            expression,
    3675            f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{expressions}",
    3676        )

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

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

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

    3682    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3683        if not self.SUPPORTS_TO_NUMBER:
    3684            self.unsupported("Unsupported TO_NUMBER function")
    3685            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3686
    3687        fmt = expression.args.get("format")
    3688        if not fmt:
    3689            self.unsupported("Conversion format is required for TO_NUMBER")
    3690            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3691
    3692        return self.func("TO_NUMBER", expression.this, fmt)

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

    3694    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3695        this = self.sql(expression, "this")
    3696        kind = self.sql(expression, "kind")
    3697        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3698        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3699        return f"{this}({kind}{args})"

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

    3701    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3702        this = self.sql(expression, "this")
    3703        max = self.sql(expression, "max")
    3704        min = self.sql(expression, "min")
    3705        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

    3714    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
    3715        expressions = self.expressions(expression, flat=True)
    3716        expressions = f" {self.wrap(expressions)}" if expressions else ""
    3717        buckets = self.sql(expression, "buckets")
    3718        kind = self.sql(expression, "kind")
    3719        buckets = f" BUCKETS {buckets}" if buckets else ""
    3720        order = self.sql(expression, "order")
    3721        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"

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

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

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

    3726    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3727        expressions = self.expressions(expression, key="expressions", flat=True)
    3728        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3729        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3730        buckets = self.sql(expression, "buckets")
    3731        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    3733    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3734        this = self.sql(expression, "this")
    3735        having = self.sql(expression, "having")
    3736
    3737        if having:
    3738            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3739
    3740        return self.func("ANY_VALUE", this)

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

    3742    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3743        transform = self.func("TRANSFORM", *expression.expressions)
    3744        row_format_before = self.sql(expression, "row_format_before")
    3745        row_format_before = f" {row_format_before}" if row_format_before else ""
    3746        record_writer = self.sql(expression, "record_writer")
    3747        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3748        using = f" USING {self.sql(expression, 'command_script')}"
    3749        schema = self.sql(expression, "schema")
    3750        schema = f" AS {schema}" if schema else ""
    3751        row_format_after = self.sql(expression, "row_format_after")
    3752        row_format_after = f" {row_format_after}" if row_format_after else ""
    3753        record_reader = self.sql(expression, "record_reader")
    3754        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3755        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

    3757    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3758        key_block_size = self.sql(expression, "key_block_size")
    3759        if key_block_size:
    3760            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3761
    3762        using = self.sql(expression, "using")
    3763        if using:
    3764            return f"USING {using}"
    3765
    3766        parser = self.sql(expression, "parser")
    3767        if parser:
    3768            return f"WITH PARSER {parser}"
    3769
    3770        comment = self.sql(expression, "comment")
    3771        if comment:
    3772            return f"COMMENT {comment}"
    3773
    3774        visible = expression.args.get("visible")
    3775        if visible is not None:
    3776            return "VISIBLE" if visible else "INVISIBLE"
    3777
    3778        engine_attr = self.sql(expression, "engine_attr")
    3779        if engine_attr:
    3780            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3781
    3782        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3783        if secondary_engine_attr:
    3784            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3785
    3786        self.unsupported("Unsupported index constraint option.")
    3787        return ""

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

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

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

    3793    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3794        kind = self.sql(expression, "kind")
    3795        kind = f"{kind} INDEX" if kind else "INDEX"
    3796        this = self.sql(expression, "this")
    3797        this = f" {this}" if this else ""
    3798        index_type = self.sql(expression, "index_type")
    3799        index_type = f" USING {index_type}" if index_type else ""
    3800        expressions = self.expressions(expression, flat=True)
    3801        expressions = f" ({expressions})" if expressions else ""
    3802        options = self.expressions(expression, key="options", sep=" ")
    3803        options = f" {options}" if options else ""
    3804        return f"{kind}{this}{index_type}{expressions}{options}"

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

    3806    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3807        if self.NVL2_SUPPORTED:
    3808            return self.function_fallback_sql(expression)
    3809
    3810        case = exp.Case().when(
    3811            expression.this.is_(exp.null()).not_(copy=False),
    3812            expression.args["true"],
    3813            copy=False,
    3814        )
    3815        else_cond = expression.args.get("false")
    3816        if else_cond:
    3817            case.else_(else_cond, copy=False)
    3818
    3819        return self.sql(case)

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

    3821    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3822        this = self.sql(expression, "this")
    3823        expr = self.sql(expression, "expression")
    3824        iterator = self.sql(expression, "iterator")
    3825        condition = self.sql(expression, "condition")
    3826        condition = f" IF {condition}" if condition else ""
    3827        return f"{this} FOR {expr} IN {iterator}{condition}"

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

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

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

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

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

    3835    def predict_sql(self, expression: exp.Predict) -> str:
    3836        model = self.sql(expression, "this")
    3837        model = f"MODEL {model}"
    3838        table = self.sql(expression, "expression")
    3839        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    3840        parameters = self.sql(expression, "params_struct")
    3841        return self.func("PREDICT", model, table, parameters or None)

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

    3843    def forin_sql(self, expression: exp.ForIn) -> str:
    3844        this = self.sql(expression, "this")
    3845        expression_sql = self.sql(expression, "expression")
    3846        return f"FOR {this} DO {expression_sql}"

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

    3848    def refresh_sql(self, expression: exp.Refresh) -> str:
    3849        this = self.sql(expression, "this")
    3850        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    3851        return f"REFRESH {table}{this}"

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

    3853    def toarray_sql(self, expression: exp.ToArray) -> str:
    3854        arg = expression.this
    3855        if not arg.type:
    3856            from sqlglot.optimizer.annotate_types import annotate_types
    3857
    3858            arg = annotate_types(arg)
    3859
    3860        if arg.is_type(exp.DataType.Type.ARRAY):
    3861            return self.sql(arg)
    3862
    3863        cond_for_null = arg.is_(exp.null())
    3864        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

    3866    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    3867        this = expression.this
    3868        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    3869            return self.sql(this)
    3870
    3871        return self.sql(exp.cast(this, exp.DataType.Type.TIME))

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

    3873    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
    3874        this = expression.this
    3875        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
    3876            return self.sql(this)
    3877
    3878        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP))

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

    3880    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    3881        this = expression.this
    3882        time_format = self.format_time(expression)
    3883
    3884        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    3885            return self.sql(
    3886                exp.cast(
    3887                    exp.StrToTime(this=this, format=expression.args["format"]),
    3888                    exp.DataType.Type.DATE,
    3889                )
    3890            )
    3891
    3892        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    3893            return self.sql(this)
    3894
    3895        return self.sql(exp.cast(this, exp.DataType.Type.DATE))

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

    3897    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    3898        return self.sql(
    3899            exp.func(
    3900                "DATEDIFF",
    3901                expression.this,
    3902                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
    3903                "day",
    3904            )
    3905        )

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

    3907    def lastday_sql(self, expression: exp.LastDay) -> str:
    3908        if self.LAST_DAY_SUPPORTS_DATE_PART:
    3909            return self.function_fallback_sql(expression)
    3910
    3911        unit = expression.text("unit")
    3912        if unit and unit != "MONTH":
    3913            self.unsupported("Date parts are not supported in LAST_DAY.")
    3914
    3915        return self.func("LAST_DAY", expression.this)

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

    3917    def dateadd_sql(self, expression: exp.DateAdd) -> str:
    3918        from sqlglot.dialects.dialect import unit_to_str
    3919
    3920        return self.func(
    3921            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
    3922        )

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

    3924    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    3925        if self.CAN_IMPLEMENT_ARRAY_ANY:
    3926            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    3927            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    3928            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    3929            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    3930
    3931        from sqlglot.dialects import Dialect
    3932
    3933        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    3934        if self.dialect.__class__ != Dialect:
    3935            self.unsupported("ARRAY_ANY is unsupported")
    3936
    3937        return self.function_fallback_sql(expression)

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

    3939    def struct_sql(self, expression: exp.Struct) -> str:
    3940        expression.set(
    3941            "expressions",
    3942            [
    3943                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    3944                if isinstance(e, exp.PropertyEQ)
    3945                else e
    3946                for e in expression.expressions
    3947            ],
    3948        )
    3949
    3950        return self.function_fallback_sql(expression)

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

    3952    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    3953        low = self.sql(expression, "this")
    3954        high = self.sql(expression, "expression")
    3955
    3956        return f"{low} TO {high}"

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

    3958    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    3959        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    3960        tables = f" {self.expressions(expression)}"
    3961
    3962        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3963
    3964        on_cluster = self.sql(expression, "cluster")
    3965        on_cluster = f" {on_cluster}" if on_cluster else ""
    3966
    3967        identity = self.sql(expression, "identity")
    3968        identity = f" {identity} IDENTITY" if identity else ""
    3969
    3970        option = self.sql(expression, "option")
    3971        option = f" {option}" if option else ""
    3972
    3973        partition = self.sql(expression, "partition")
    3974        partition = f" {partition}" if partition else ""
    3975
    3976        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"

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

    3980    def convert_sql(self, expression: exp.Convert) -> str:
    3981        to = expression.this
    3982        value = expression.expression
    3983        style = expression.args.get("style")
    3984        safe = expression.args.get("safe")
    3985        strict = expression.args.get("strict")
    3986
    3987        if not to or not value:
    3988            return ""
    3989
    3990        # Retrieve length of datatype and override to default if not specified
    3991        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3992            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    3993
    3994        transformed: t.Optional[exp.Expression] = None
    3995        cast = exp.Cast if strict else exp.TryCast
    3996
    3997        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
    3998        if isinstance(style, exp.Literal) and style.is_int:
    3999            from sqlglot.dialects.tsql import TSQL
    4000
    4001            style_value = style.name
    4002            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
    4003            if not converted_style:
    4004                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
    4005
    4006            fmt = exp.Literal.string(converted_style)
    4007
    4008            if to.this == exp.DataType.Type.DATE:
    4009                transformed = exp.StrToDate(this=value, format=fmt)
    4010            elif to.this == exp.DataType.Type.DATETIME:
    4011                transformed = exp.StrToTime(this=value, format=fmt)
    4012            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    4013                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
    4014            elif to.this == exp.DataType.Type.TEXT:
    4015                transformed = exp.TimeToStr(this=value, format=fmt)
    4016
    4017        if not transformed:
    4018            transformed = cast(this=value, to=to, safe=safe)
    4019
    4020        return self.sql(transformed)

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

    4076    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
    4077        option = self.sql(expression, "this")
    4078
    4079        if expression.expressions:
    4080            upper = option.upper()
    4081
    4082            # Snowflake FILE_FORMAT options are separated by whitespace
    4083            sep = " " if upper == "FILE_FORMAT" else ", "
    4084
    4085            # Databricks copy/format options do not set their list of values with EQ
    4086            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
    4087            values = self.expressions(expression, flat=True, sep=sep)
    4088            return f"{option}{op}({values})"
    4089
    4090        value = self.sql(expression, "expression")
    4091
    4092        if not value:
    4093            return option
    4094
    4095        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
    4096
    4097        return f"{option}{op}{value}"

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

    4099    def credentials_sql(self, expression: exp.Credentials) -> str:
    4100        cred_expr = expression.args.get("credentials")
    4101        if isinstance(cred_expr, exp.Literal):
    4102            # Redshift case: CREDENTIALS <string>
    4103            credentials = self.sql(expression, "credentials")
    4104            credentials = f"CREDENTIALS {credentials}" if credentials else ""
    4105        else:
    4106            # Snowflake case: CREDENTIALS = (...)
    4107            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
    4108            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
    4109
    4110        storage = self.sql(expression, "storage")
    4111        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
    4112
    4113        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
    4114        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
    4115
    4116        iam_role = self.sql(expression, "iam_role")
    4117        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
    4118
    4119        region = self.sql(expression, "region")
    4120        region = f" REGION {region}" if region else ""
    4121
    4122        return f"{credentials}{storage}{encryption}{iam_role}{region}"

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

    4124    def copy_sql(self, expression: exp.Copy) -> str:
    4125        this = self.sql(expression, "this")
    4126        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
    4127
    4128        credentials = self.sql(expression, "credentials")
    4129        credentials = self.seg(credentials) if credentials else ""
    4130        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
    4131        files = self.expressions(expression, key="files", flat=True)
    4132
    4133        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
    4134        params = self.expressions(
    4135            expression,
    4136            key="params",
    4137            sep=sep,
    4138            new_line=True,
    4139            skip_last=True,
    4140            skip_first=True,
    4141            indent=self.COPY_PARAMS_ARE_WRAPPED,
    4142        )
    4143
    4144        if params:
    4145            if self.COPY_PARAMS_ARE_WRAPPED:
    4146                params = f" WITH ({params})"
    4147            elif not self.pretty:
    4148                params = f" {params}"
    4149
    4150        return f"COPY{this}{kind} {files}{credentials}{params}"

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

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

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

    4155    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
    4156        on_sql = "ON" if expression.args.get("on") else "OFF"
    4157        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
    4158        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
    4159        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    4160        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
    4161
    4162        if filter_col or retention_period:
    4163            on_sql = self.func("ON", filter_col, retention_period)
    4164
    4165        return f"DATA_DELETION={on_sql}"

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

    4167    def maskingpolicycolumnconstraint_sql(
    4168        self, expression: exp.MaskingPolicyColumnConstraint
    4169    ) -> str:
    4170        this = self.sql(expression, "this")
    4171        expressions = self.expressions(expression, flat=True)
    4172        expressions = f" USING ({expressions})" if expressions else ""
    4173        return f"MASKING POLICY {this}{expressions}"

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

    4175    def gapfill_sql(self, expression: exp.GapFill) -> str:
    4176        this = self.sql(expression, "this")
    4177        this = f"TABLE {this}"
    4178        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

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

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

    4183    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
    4184        this = self.sql(expression, "this")
    4185        expr = expression.expression
    4186
    4187        if isinstance(expr, exp.Func):
    4188            # T-SQL's CLR functions are case sensitive
    4189            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
    4190        else:
    4191            expr = self.sql(expression, "expression")
    4192
    4193        return self.scope_resolution(expr, this)

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

    4195    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
    4196        if self.PARSE_JSON_NAME is None:
    4197            return self.sql(expression.this)
    4198
    4199        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)

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

    4201    def rand_sql(self, expression: exp.Rand) -> str:
    4202        lower = self.sql(expression, "lower")
    4203        upper = self.sql(expression, "upper")
    4204
    4205        if lower and upper:
    4206            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
    4207        return self.func("RAND", expression.this)

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

    4209    def changes_sql(self, expression: exp.Changes) -> str:
    4210        information = self.sql(expression, "information")
    4211        information = f"INFORMATION => {information}"
    4212        at_before = self.sql(expression, "at_before")
    4213        at_before = f"{self.seg('')}{at_before}" if at_before else ""
    4214        end = self.sql(expression, "end")
    4215        end = f"{self.seg('')}{end}" if end else ""
    4216
    4217        return f"CHANGES ({information}){at_before}{end}"

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

    4219    def pad_sql(self, expression: exp.Pad) -> str:
    4220        prefix = "L" if expression.args.get("is_left") else "R"
    4221
    4222        fill_pattern = self.sql(expression, "fill_pattern") or None
    4223        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
    4224            fill_pattern = "' '"
    4225
    4226        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)

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

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

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

    4232    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
    4233        generate_series = exp.GenerateSeries(**expression.args)
    4234
    4235        parent = expression.parent
    4236        if isinstance(parent, (exp.Alias, exp.TableAlias)):
    4237            parent = parent.parent
    4238
    4239        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
    4240            return self.sql(exp.Unnest(expressions=[generate_series]))
    4241
    4242        if isinstance(parent, exp.Select):
    4243            self.unsupported("GenerateSeries projection unnesting is not supported.")
    4244
    4245        return self.sql(generate_series)

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

    4247    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
    4248        exprs = expression.expressions
    4249        if not self.ARRAY_CONCAT_IS_VAR_LEN:
    4250            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
    4251        else:
    4252            rhs = self.expressions(expression)
    4253
    4254        return self.func(name, expression.this, rhs)

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

    4256    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
    4257        if self.SUPPORTS_CONVERT_TIMEZONE:
    4258            return self.function_fallback_sql(expression)
    4259
    4260        source_tz = expression.args.get("source_tz")
    4261        target_tz = expression.args.get("target_tz")
    4262        timestamp = expression.args.get("timestamp")
    4263
    4264        if source_tz and timestamp:
    4265            timestamp = exp.AtTimeZone(
    4266                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
    4267            )
    4268
    4269        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
    4270
    4271        return self.sql(expr)

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

    4273    def json_sql(self, expression: exp.JSON) -> str:
    4274        this = self.sql(expression, "this")
    4275        this = f" {this}" if this else ""
    4276
    4277        _with = expression.args.get("with")
    4278
    4279        if _with is None:
    4280            with_sql = ""
    4281        elif not _with:
    4282            with_sql = " WITHOUT"
    4283        else:
    4284            with_sql = " WITH"
    4285
    4286        unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else ""
    4287
    4288        return f"JSON{this}{with_sql}{unique_sql}"

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

    4290    def jsonvalue_sql(self, expression: exp.JSONValue) -> str:
    4291        def _generate_on_options(arg: t.Any) -> str:
    4292            return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}"
    4293
    4294        path = self.sql(expression, "path")
    4295        returning = self.sql(expression, "returning")
    4296        returning = f" RETURNING {returning}" if returning else ""
    4297
    4298        on_condition = self.sql(expression, "on_condition")
    4299        on_condition = f" {on_condition}" if on_condition else ""
    4300
    4301        return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")

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

    4303    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
    4304        else_ = "ELSE " if expression.args.get("else_") else ""
    4305        condition = self.sql(expression, "expression")
    4306        condition = f"WHEN {condition} THEN " if condition else else_
    4307        insert = self.sql(expression, "this")[len("INSERT") :].strip()
    4308        return f"{condition}{insert}"

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

    4310    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
    4311        kind = self.sql(expression, "kind")
    4312        expressions = self.seg(self.expressions(expression, sep=" "))
    4313        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
    4314        return res

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

    4316    def oncondition_sql(self, expression: exp.OnCondition) -> str:
    4317        # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR"
    4318        empty = expression.args.get("empty")
    4319        empty = (
    4320            f"DEFAULT {empty} ON EMPTY"
    4321            if isinstance(empty, exp.Expression)
    4322            else self.sql(expression, "empty")
    4323        )
    4324
    4325        error = expression.args.get("error")
    4326        error = (
    4327            f"DEFAULT {error} ON ERROR"
    4328            if isinstance(error, exp.Expression)
    4329            else self.sql(expression, "error")
    4330        )
    4331
    4332        if error and empty:
    4333            error = (
    4334                f"{empty} {error}"
    4335                if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR
    4336                else f"{error} {empty}"
    4337            )
    4338            empty = ""
    4339
    4340        null = self.sql(expression, "null")
    4341
    4342        return f"{empty}{error}{null}"

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

    4344    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
    4345        this = self.sql(expression, "this")
    4346        path = self.sql(expression, "path")
    4347
    4348        passing = self.expressions(expression, "passing")
    4349        passing = f" PASSING {passing}" if passing else ""
    4350
    4351        on_condition = self.sql(expression, "on_condition")
    4352        on_condition = f" {on_condition}" if on_condition else ""
    4353
    4354        path = f"{path}{passing}{on_condition}"
    4355
    4356        return self.func("JSON_EXISTS", this, path)

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

    4358    def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
    4359        array_agg = self.function_fallback_sql(expression)
    4360
    4361        if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"):
    4362            parent = expression.parent
    4363            if isinstance(parent, exp.Filter):
    4364                parent_cond = parent.expression.this
    4365                parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_()))
    4366            else:
    4367                # DISTINCT is already present in the agg function, do not propagate it to FILTER as well
    4368                this = expression.this
    4369                this_sql = (
    4370                    self.expressions(this)
    4371                    if isinstance(this, exp.Distinct)
    4372                    else self.sql(expression, "this")
    4373                )
    4374                array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)"
    4375
    4376        return array_agg

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

    4378    def apply_sql(self, expression: exp.Apply) -> str:
    4379        this = self.sql(expression, "this")
    4380        expr = self.sql(expression, "expression")
    4381
    4382        return f"{this} APPLY({expr})"

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

    4384    def grant_sql(self, expression: exp.Grant) -> str:
    4385        privileges_sql = self.expressions(expression, key="privileges", flat=True)
    4386
    4387        kind = self.sql(expression, "kind")
    4388        kind = f" {kind}" if kind else ""
    4389
    4390        securable = self.sql(expression, "securable")
    4391        securable = f" {securable}" if securable else ""
    4392
    4393        principals = self.expressions(expression, key="principals", flat=True)
    4394
    4395        grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else ""
    4396
    4397        return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"

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

    4399    def grantprivilege_sql(self, expression: exp.GrantPrivilege):
    4400        this = self.sql(expression, "this")
    4401        columns = self.expressions(expression, flat=True)
    4402        columns = f"({columns})" if columns else ""
    4403
    4404        return f"{this}{columns}"

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

    4406    def grantprincipal_sql(self, expression: exp.GrantPrincipal):
    4407        this = self.sql(expression, "this")
    4408
    4409        kind = self.sql(expression, "kind")
    4410        kind = f"{kind} " if kind else ""
    4411
    4412        return f"{kind}{this}"

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

    4414    def columns_sql(self, expression: exp.Columns):
    4415        func = self.function_fallback_sql(expression)
    4416        if expression.args.get("unpack"):
    4417            func = f"*{func}"
    4418
    4419        return func

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

    4421    def overlay_sql(self, expression: exp.Overlay):
    4422        this = self.sql(expression, "this")
    4423        expr = self.sql(expression, "expression")
    4424        from_sql = self.sql(expression, "from")
    4425        for_sql = self.sql(expression, "for")
    4426        for_sql = f" FOR {for_sql}" if for_sql else ""
    4427
    4428        return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})"