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

logger = <Logger sqlglot (WARNING)>
ESCAPED_UNICODE_RE = re.compile('\\\\(\\d+)')
class Generator: View Source

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

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

    590    def __init__(
    591        self,
    592        pretty: t.Optional[bool] = None,
    593        identify: str | bool = False,
    594        normalize: bool = False,
    595        pad: int = 2,
    596        indent: int = 2,
    597        normalize_functions: t.Optional[str | bool] = None,
    598        unsupported_level: ErrorLevel = ErrorLevel.WARN,
    599        max_unsupported: int = 3,
    600        leading_comma: bool = False,
    601        max_text_width: int = 80,
    602        comments: bool = True,
    603        dialect: DialectType = None,
    604    ):
    605        import sqlglot
    606        from sqlglot.dialects import Dialect
    607
    608        self.pretty = pretty if pretty is not None else sqlglot.pretty
    609        self.identify = identify
    610        self.normalize = normalize
    611        self.pad = pad
    612        self._indent = indent
    613        self.unsupported_level = unsupported_level
    614        self.max_unsupported = max_unsupported
    615        self.leading_comma = leading_comma
    616        self.max_text_width = max_text_width
    617        self.comments = comments
    618        self.dialect = Dialect.get_or_raise(dialect)
    619
    620        # This is both a Dialect property and a Generator argument, so we prioritize the latter
    621        self.normalize_functions = (
    622            self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
    623        )
    624
    625        self.unsupported_messages: t.List[str] = []
    626        self._escaped_quote_end: str = (
    627            self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END
    628        )
    629        self._escaped_identifier_end: str = (
    630            self.dialect.tokenizer_class.IDENTIFIER_ESCAPES[0] + self.dialect.IDENTIFIER_END
    631        )
    632
    633        self._next_name = name_sequence("_t")

TRANSFORMS: Dict[Type[sqlglot.expressions.Expression], Callable[..., str]] = {<class 'sqlglot.expressions.JSONPathFilter'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathKey'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRecursive'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRoot'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathScript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSelector'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSlice'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSubscript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathUnion'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathWildcard'>: <function <lambda>>, <class 'sqlglot.expressions.AllowedValuesProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ConnectByRoot'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DynamicProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EmptyProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EphemeralColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExcludeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.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.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.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.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UnloggedProperty'>: <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
EXPLICIT_SET_OP = False
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.JSONPathUnion'>, <class 'sqlglot.expressions.JSONPathSelector'>, <class 'sqlglot.expressions.JSONPathSlice'>, <class 'sqlglot.expressions.JSONPathScript'>, <class 'sqlglot.expressions.JSONPathRoot'>, <class 'sqlglot.expressions.JSONPathRecursive'>, <class 'sqlglot.expressions.JSONPathKey'>, <class 'sqlglot.expressions.JSONPathWildcard'>, <class 'sqlglot.expressions.JSONPathFilter'>, <class 'sqlglot.expressions.JSONPathSubscript'>}
CAN_IMPLEMENT_ARRAY_ANY = False
SUPPORTS_TO_NUMBER = True
SET_OP_MODIFIERS = True
COPY_PARAMS_ARE_WRAPPED = True
COPY_PARAMS_EQ_REQUIRED = False
COPY_HAS_INTO_KEYWORD = True
TRY_SUPPORTED = True
SUPPORTS_UESCAPE = True
STAR_EXCEPT = 'EXCEPT'
HEX_FUNC = 'HEX'
WITH_PROPERTIES_PREFIX = 'WITH'
QUOTE_JSON_PATH = True
PAD_FILL_PATTERN_IS_REQUIRED = False
SUPPORTS_EXPLODING_PROJECTIONS = True
ARRAY_CONCAT_IS_VAR_LEN = True
SUPPORTS_CONVERT_TIMEZONE = False
SUPPORTS_NULLABLE_TYPES = True
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.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.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.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.NCHAR: 'NCHAR'>, <Type.NVARCHAR: 'NVARCHAR'>}
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

    635    def generate(self, expression: exp.Expression, copy: bool = True) -> str:
    636        """
    637        Generates the SQL string corresponding to the given syntax tree.
    638
    639        Args:
    640            expression: The syntax tree.
    641            copy: Whether to copy the expression. The generator performs mutations so
    642                it is safer to copy.
    643
    644        Returns:
    645            The SQL string corresponding to `expression`.
    646        """
    647        if copy:
    648            expression = expression.copy()
    649
    650        expression = self.preprocess(expression)
    651
    652        self.unsupported_messages = []
    653        sql = self.sql(expression).strip()
    654
    655        if self.pretty:
    656            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
    657
    658        if self.unsupported_level == ErrorLevel.IGNORE:
    659            return sql
    660
    661        if self.unsupported_level == ErrorLevel.WARN:
    662            for msg in self.unsupported_messages:
    663                logger.warning(msg)
    664        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
    665            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
    666
    667        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

    669    def preprocess(self, expression: exp.Expression) -> exp.Expression:
    670        """Apply generic preprocessing transformations to a given expression."""
    671        if (
    672            not expression.parent
    673            and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES
    674            and any(node.parent is not expression for node in expression.find_all(exp.With))
    675        ):
    676            from sqlglot.transforms import move_ctes_to_top_level
    677
    678            expression = move_ctes_to_top_level(expression)
    679
    680        if self.ENSURE_BOOLS:
    681            from sqlglot.transforms import ensure_bools
    682
    683            expression = ensure_bools(expression)
    684
    685        return expression

Apply generic preprocessing transformations to a given expression.

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

    687    def unsupported(self, message: str) -> None:
    688        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    689            raise UnsupportedError(message)
    690        self.unsupported_messages.append(message)

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

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

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

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

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

    698    def pad_comment(self, comment: str) -> str:
    699        comment = " " + comment if comment[0].strip() else comment
    700        comment = comment + " " if comment[-1].strip() else comment
    701        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

    703    def maybe_comment(
    704        self,
    705        sql: str,
    706        expression: t.Optional[exp.Expression] = None,
    707        comments: t.Optional[t.List[str]] = None,
    708        separated: bool = False,
    709    ) -> str:
    710        comments = (
    711            ((expression and expression.comments) if comments is None else comments)  # type: ignore
    712            if self.comments
    713            else None
    714        )
    715
    716        if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
    717            return sql
    718
    719        comments_sql = " ".join(
    720            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
    721        )
    722
    723        if not comments_sql:
    724            return sql
    725
    726        comments_sql = self._replace_line_breaks(comments_sql)
    727
    728        if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS):
    729            return (
    730                f"{self.sep()}{comments_sql}{sql}"
    731                if not sql or sql[0].isspace()
    732                else f"{comments_sql}{self.sep()}{sql}"
    733            )
    734
    735        return f"{sql} {comments_sql}"

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

    737    def wrap(self, expression: exp.Expression | str) -> str:
    738        this_sql = (
    739            self.sql(expression)
    740            if isinstance(expression, exp.UNWRAPPED_QUERIES)
    741            else self.sql(expression, "this")
    742        )
    743        if not this_sql:
    744            return "()"
    745
    746        this_sql = self.indent(this_sql, level=1, pad=0)
    747        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"

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

    749    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    750        original = self.identify
    751        self.identify = False
    752        result = func(*args, **kwargs)
    753        self.identify = original
    754        return result

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

    756    def normalize_func(self, name: str) -> str:
    757        if self.normalize_functions == "upper" or self.normalize_functions is True:
    758            return name.upper()
    759        if self.normalize_functions == "lower":
    760            return name.lower()
    761        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

    763    def indent(
    764        self,
    765        sql: str,
    766        level: int = 0,
    767        pad: t.Optional[int] = None,
    768        skip_first: bool = False,
    769        skip_last: bool = False,
    770    ) -> str:
    771        if not self.pretty or not sql:
    772            return sql
    773
    774        pad = self.pad if pad is None else pad
    775        lines = sql.split("\n")
    776
    777        return "\n".join(
    778            (
    779                line
    780                if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
    781                else f"{' ' * (level * self._indent + pad)}{line}"
    782            )
    783            for i, line in enumerate(lines)
    784        )

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

    786    def sql(
    787        self,
    788        expression: t.Optional[str | exp.Expression],
    789        key: t.Optional[str] = None,
    790        comment: bool = True,
    791    ) -> str:
    792        if not expression:
    793            return ""
    794
    795        if isinstance(expression, str):
    796            return expression
    797
    798        if key:
    799            value = expression.args.get(key)
    800            if value:
    801                return self.sql(value)
    802            return ""
    803
    804        transform = self.TRANSFORMS.get(expression.__class__)
    805
    806        if callable(transform):
    807            sql = transform(self, expression)
    808        elif isinstance(expression, exp.Expression):
    809            exp_handler_name = f"{expression.key}_sql"
    810
    811            if hasattr(self, exp_handler_name):
    812                sql = getattr(self, exp_handler_name)(expression)
    813            elif isinstance(expression, exp.Func):
    814                sql = self.function_fallback_sql(expression)
    815            elif isinstance(expression, exp.Property):
    816                sql = self.property_sql(expression)
    817            else:
    818                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
    819        else:
    820            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
    821
    822        return self.maybe_comment(sql, expression) if self.comments and comment else sql

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

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

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

    829    def cache_sql(self, expression: exp.Cache) -> str:
    830        lazy = " LAZY" if expression.args.get("lazy") else ""
    831        table = self.sql(expression, "this")
    832        options = expression.args.get("options")
    833        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
    834        sql = self.sql(expression, "expression")
    835        sql = f" AS{self.sep()}{sql}" if sql else ""
    836        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
    837        return self.prepend_ctes(expression, sql)

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

    839    def characterset_sql(self, expression: exp.CharacterSet) -> str:
    840        if isinstance(expression.parent, exp.Cast):
    841            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
    842        default = "DEFAULT " if expression.args.get("default") else ""
    843        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"

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

    845    def column_parts(self, expression: exp.Column) -> str:
    846        return ".".join(
    847            self.sql(part)
    848            for part in (
    849                expression.args.get("catalog"),
    850                expression.args.get("db"),
    851                expression.args.get("table"),
    852                expression.args.get("this"),
    853            )
    854            if part
    855        )

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

    857    def column_sql(self, expression: exp.Column) -> str:
    858        join_mark = " (+)" if expression.args.get("join_mark") else ""
    859
    860        if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS:
    861            join_mark = ""
    862            self.unsupported("Outer join syntax using the (+) operator is not supported.")
    863
    864        return f"{self.column_parts(expression)}{join_mark}"

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

    866    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    867        this = self.sql(expression, "this")
    868        this = f" {this}" if this else ""
    869        position = self.sql(expression, "position")
    870        return f"{position}{this}"

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

    872    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
    873        column = self.sql(expression, "this")
    874        kind = self.sql(expression, "kind")
    875        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
    876        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
    877        kind = f"{sep}{kind}" if kind else ""
    878        constraints = f" {constraints}" if constraints else ""
    879        position = self.sql(expression, "position")
    880        position = f" {position}" if position else ""
    881
    882        if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:
    883            kind = ""
    884
    885        return f"{exists}{column}{kind}{constraints}{position}"

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

    887    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    888        this = self.sql(expression, "this")
    889        kind_sql = self.sql(expression, "kind").strip()
    890        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

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

    892    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
    893        this = self.sql(expression, "this")
    894        if expression.args.get("not_null"):
    895            persisted = " PERSISTED NOT NULL"
    896        elif expression.args.get("persisted"):
    897            persisted = " PERSISTED"
    898        else:
    899            persisted = ""
    900        return f"AS {this}{persisted}"

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

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

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

    905    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
    906        if isinstance(expression.this, list):
    907            this = self.wrap(self.expressions(expression, key="this", flat=True))
    908        else:
    909            this = self.sql(expression, "this")
    910
    911        return f"COMPRESS {this}"

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

    913    def generatedasidentitycolumnconstraint_sql(
    914        self, expression: exp.GeneratedAsIdentityColumnConstraint
    915    ) -> str:
    916        this = ""
    917        if expression.this is not None:
    918            on_null = " ON NULL" if expression.args.get("on_null") else ""
    919            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
    920
    921        start = expression.args.get("start")
    922        start = f"START WITH {start}" if start else ""
    923        increment = expression.args.get("increment")
    924        increment = f" INCREMENT BY {increment}" if increment else ""
    925        minvalue = expression.args.get("minvalue")
    926        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    927        maxvalue = expression.args.get("maxvalue")
    928        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    929        cycle = expression.args.get("cycle")
    930        cycle_sql = ""
    931
    932        if cycle is not None:
    933            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
    934            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
    935
    936        sequence_opts = ""
    937        if start or increment or cycle_sql:
    938            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
    939            sequence_opts = f" ({sequence_opts.strip()})"
    940
    941        expr = self.sql(expression, "expression")
    942        expr = f"({expr})" if expr else "IDENTITY"
    943
    944        return f"GENERATED{this} AS {expr}{sequence_opts}"

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

    946    def generatedasrowcolumnconstraint_sql(
    947        self, expression: exp.GeneratedAsRowColumnConstraint
    948    ) -> str:
    949        start = "START" if expression.args.get("start") else "END"
    950        hidden = " HIDDEN" if expression.args.get("hidden") else ""
    951        return f"GENERATED ALWAYS AS ROW {start}{hidden}"

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

    953    def periodforsystemtimeconstraint_sql(
    954        self, expression: exp.PeriodForSystemTimeConstraint
    955    ) -> str:
    956        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

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

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

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

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

    964    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    965        desc = expression.args.get("desc")
    966        if desc is not None:
    967            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    968        return "PRIMARY KEY"

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

    970    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    971        this = self.sql(expression, "this")
    972        this = f" {this}" if this else ""
    973        index_type = expression.args.get("index_type")
    974        index_type = f" USING {index_type}" if index_type else ""
    975        on_conflict = self.sql(expression, "on_conflict")
    976        on_conflict = f" {on_conflict}" if on_conflict else ""
    977        nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else ""
    978        return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}"

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

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

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

     983    def create_sql(self, expression: exp.Create) -> str:
     984        kind = self.sql(expression, "kind")
     985        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
     986        properties = expression.args.get("properties")
     987        properties_locs = self.locate_properties(properties) if properties else defaultdict()
     988
     989        this = self.createable_sql(expression, properties_locs)
     990
     991        properties_sql = ""
     992        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
     993            exp.Properties.Location.POST_WITH
     994        ):
     995            properties_sql = self.sql(
     996                exp.Properties(
     997                    expressions=[
     998                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
     999                        *properties_locs[exp.Properties.Location.POST_WITH],
    1000                    ]
    1001                )
    1002            )
    1003
    1004            if properties_locs.get(exp.Properties.Location.POST_SCHEMA):
    1005                properties_sql = self.sep() + properties_sql
    1006            elif not self.pretty:
    1007                # Standalone POST_WITH properties need a leading whitespace in non-pretty mode
    1008                properties_sql = f" {properties_sql}"
    1009
    1010        begin = " BEGIN" if expression.args.get("begin") else ""
    1011        end = " END" if expression.args.get("end") else ""
    1012
    1013        expression_sql = self.sql(expression, "expression")
    1014        if expression_sql:
    1015            expression_sql = f"{begin}{self.sep()}{expression_sql}{end}"
    1016
    1017            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
    1018                postalias_props_sql = ""
    1019                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
    1020                    postalias_props_sql = self.properties(
    1021                        exp.Properties(
    1022                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
    1023                        ),
    1024                        wrapped=False,
    1025                    )
    1026                postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else ""
    1027                expression_sql = f" AS{postalias_props_sql}{expression_sql}"
    1028
    1029        postindex_props_sql = ""
    1030        if properties_locs.get(exp.Properties.Location.POST_INDEX):
    1031            postindex_props_sql = self.properties(
    1032                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
    1033                wrapped=False,
    1034                prefix=" ",
    1035            )
    1036
    1037        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
    1038        indexes = f" {indexes}" if indexes else ""
    1039        index_sql = indexes + postindex_props_sql
    1040
    1041        replace = " OR REPLACE" if expression.args.get("replace") else ""
    1042        refresh = " OR REFRESH" if expression.args.get("refresh") else ""
    1043        unique = " UNIQUE" if expression.args.get("unique") else ""
    1044
    1045        clustered = expression.args.get("clustered")
    1046        if clustered is None:
    1047            clustered_sql = ""
    1048        elif clustered:
    1049            clustered_sql = " CLUSTERED COLUMNSTORE"
    1050        else:
    1051            clustered_sql = " NONCLUSTERED COLUMNSTORE"
    1052
    1053        postcreate_props_sql = ""
    1054        if properties_locs.get(exp.Properties.Location.POST_CREATE):
    1055            postcreate_props_sql = self.properties(
    1056                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
    1057                sep=" ",
    1058                prefix=" ",
    1059                wrapped=False,
    1060            )
    1061
    1062        modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql))
    1063
    1064        postexpression_props_sql = ""
    1065        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
    1066            postexpression_props_sql = self.properties(
    1067                exp.Properties(
    1068                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
    1069                ),
    1070                sep=" ",
    1071                prefix=" ",
    1072                wrapped=False,
    1073            )
    1074
    1075        concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else ""
    1076        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    1077        no_schema_binding = (
    1078            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
    1079        )
    1080
    1081        clone = self.sql(expression, "clone")
    1082        clone = f" {clone}" if clone else ""
    1083
    1084        expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
    1085        return self.prepend_ctes(expression, expression_sql)

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

    1087    def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str:
    1088        start = self.sql(expression, "start")
    1089        start = f"START WITH {start}" if start else ""
    1090        increment = self.sql(expression, "increment")
    1091        increment = f" INCREMENT BY {increment}" if increment else ""
    1092        minvalue = self.sql(expression, "minvalue")
    1093        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    1094        maxvalue = self.sql(expression, "maxvalue")
    1095        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    1096        owned = self.sql(expression, "owned")
    1097        owned = f" OWNED BY {owned}" if owned else ""
    1098
    1099        cache = expression.args.get("cache")
    1100        if cache is None:
    1101            cache_str = ""
    1102        elif cache is True:
    1103            cache_str = " CACHE"
    1104        else:
    1105            cache_str = f" CACHE {cache}"
    1106
    1107        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1108        options = f" {options}" if options else ""
    1109
    1110        return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()

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

    1112    def clone_sql(self, expression: exp.Clone) -> str:
    1113        this = self.sql(expression, "this")
    1114        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    1115        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
    1116        return f"{shallow}{keyword} {this}"

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

    1118    def describe_sql(self, expression: exp.Describe) -> str:
    1119        style = expression.args.get("style")
    1120        style = f" {style}" if style else ""
    1121        partition = self.sql(expression, "partition")
    1122        partition = f" {partition}" if partition else ""
    1123        return f"DESCRIBE{style} {self.sql(expression, 'this')}{partition}"

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

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

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

    1129    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    1130        with_ = self.sql(expression, "with")
    1131        if with_:
    1132            sql = f"{with_}{self.sep()}{sql}"
    1133        return sql

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

    1135    def with_sql(self, expression: exp.With) -> str:
    1136        sql = self.expressions(expression, flat=True)
    1137        recursive = (
    1138            "RECURSIVE "
    1139            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
    1140            else ""
    1141        )
    1142
    1143        return f"WITH {recursive}{sql}"

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

    1145    def cte_sql(self, expression: exp.CTE) -> str:
    1146        alias = self.sql(expression, "alias")
    1147
    1148        materialized = expression.args.get("materialized")
    1149        if materialized is False:
    1150            materialized = "NOT MATERIALIZED "
    1151        elif materialized:
    1152            materialized = "MATERIALIZED "
    1153
    1154        return f"{alias} AS {materialized or ''}{self.wrap(expression)}"

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

    1156    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    1157        alias = self.sql(expression, "this")
    1158        columns = self.expressions(expression, key="columns", flat=True)
    1159        columns = f"({columns})" if columns else ""
    1160
    1161        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
    1162            columns = ""
    1163            self.unsupported("Named columns are not supported in table alias.")
    1164
    1165        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
    1166            alias = self._next_name()
    1167
    1168        return f"{alias}{columns}"

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

    1170    def bitstring_sql(self, expression: exp.BitString) -> str:
    1171        this = self.sql(expression, "this")
    1172        if self.dialect.BIT_START:
    1173            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    1174        return f"{int(this, 2)}"

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

    1176    def hexstring_sql(self, expression: exp.HexString) -> str:
    1177        this = self.sql(expression, "this")
    1178        if self.dialect.HEX_START:
    1179            return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
    1180        return f"{int(this, 16)}"

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

    1182    def bytestring_sql(self, expression: exp.ByteString) -> str:
    1183        this = self.sql(expression, "this")
    1184        if self.dialect.BYTE_START:
    1185            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    1186        return this

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

    1188    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
    1189        this = self.sql(expression, "this")
    1190        escape = expression.args.get("escape")
    1191
    1192        if self.dialect.UNICODE_START:
    1193            escape_substitute = r"\\\1"
    1194            left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END
    1195        else:
    1196            escape_substitute = r"\\u\1"
    1197            left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END
    1198
    1199        if escape:
    1200            escape_pattern = re.compile(rf"{escape.name}(\d+)")
    1201            escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else ""
    1202        else:
    1203            escape_pattern = ESCAPED_UNICODE_RE
    1204            escape_sql = ""
    1205
    1206        if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE):
    1207            this = escape_pattern.sub(escape_substitute, this)
    1208
    1209        return f"{left_quote}{this}{right_quote}{escape_sql}"

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

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

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

    1215    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    1216        this = self.sql(expression, "this")
    1217        specifier = self.sql(expression, "expression")
    1218        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    1219        return f"{this}{specifier}"

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

    1221    def datatype_sql(self, expression: exp.DataType) -> str:
    1222        nested = ""
    1223        values = ""
    1224        interior = self.expressions(expression, flat=True)
    1225
    1226        type_value = expression.this
    1227        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
    1228            type_sql = self.sql(expression, "kind")
    1229        elif type_value != exp.DataType.Type.NULLABLE or self.SUPPORTS_NULLABLE_TYPES:
    1230            type_sql = (
    1231                self.TYPE_MAPPING.get(type_value, type_value.value)
    1232                if isinstance(type_value, exp.DataType.Type)
    1233                else type_value
    1234            )
    1235        else:
    1236            return interior
    1237
    1238        if interior:
    1239            if expression.args.get("nested"):
    1240                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    1241                if expression.args.get("values") is not None:
    1242                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    1243                    values = self.expressions(expression, key="values", flat=True)
    1244                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    1245            elif type_value == exp.DataType.Type.INTERVAL:
    1246                nested = f" {interior}"
    1247            else:
    1248                nested = f"({interior})"
    1249
    1250        type_sql = f"{type_sql}{nested}{values}"
    1251        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
    1252            exp.DataType.Type.TIMETZ,
    1253            exp.DataType.Type.TIMESTAMPTZ,
    1254        ):
    1255            type_sql = f"{type_sql} WITH TIME ZONE"
    1256
    1257        return type_sql

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

    1259    def directory_sql(self, expression: exp.Directory) -> str:
    1260        local = "LOCAL " if expression.args.get("local") else ""
    1261        row_format = self.sql(expression, "row_format")
    1262        row_format = f" {row_format}" if row_format else ""
    1263        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

    1265    def delete_sql(self, expression: exp.Delete) -> str:
    1266        this = self.sql(expression, "this")
    1267        this = f" FROM {this}" if this else ""
    1268        using = self.sql(expression, "using")
    1269        using = f" USING {using}" if using else ""
    1270        where = self.sql(expression, "where")
    1271        returning = self.sql(expression, "returning")
    1272        limit = self.sql(expression, "limit")
    1273        tables = self.expressions(expression, key="tables")
    1274        tables = f" {tables}" if tables else ""
    1275        if self.RETURNING_END:
    1276            expression_sql = f"{this}{using}{where}{returning}{limit}"
    1277        else:
    1278            expression_sql = f"{returning}{this}{using}{where}{limit}"
    1279        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

    1281    def drop_sql(self, expression: exp.Drop) -> str:
    1282        this = self.sql(expression, "this")
    1283        expressions = self.expressions(expression, flat=True)
    1284        expressions = f" ({expressions})" if expressions else ""
    1285        kind = expression.args["kind"]
    1286        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
    1287        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    1288        on_cluster = self.sql(expression, "cluster")
    1289        on_cluster = f" {on_cluster}" if on_cluster else ""
    1290        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1291        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    1292        cascade = " CASCADE" if expression.args.get("cascade") else ""
    1293        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    1294        purge = " PURGE" if expression.args.get("purge") else ""
    1295        return f"DROP{temporary}{materialized} {kind}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}"

def except_sql(self, expression: sqlglot.expressions.Except) -> str: View Source

    1297    def except_sql(self, expression: exp.Except) -> str:
    1298        return self.set_operations(expression)

def except_op(self, expression: sqlglot.expressions.Except) -> str: View Source

    1300    def except_op(self, expression: exp.Except) -> str:
    1301        return f"EXCEPT{'' if expression.args.get('distinct') else ' ALL'}"

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

    1303    def fetch_sql(self, expression: exp.Fetch) -> str:
    1304        direction = expression.args.get("direction")
    1305        direction = f" {direction}" if direction else ""
    1306        count = self.sql(expression, "count")
    1307        count = f" {count}" if count else ""
    1308        if expression.args.get("percent"):
    1309            count = f"{count} PERCENT"
    1310        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    1311        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"

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

    1313    def filter_sql(self, expression: exp.Filter) -> str:
    1314        if self.AGGREGATE_FILTER_SUPPORTED:
    1315            this = self.sql(expression, "this")
    1316            where = self.sql(expression, "expression").strip()
    1317            return f"{this} FILTER({where})"
    1318
    1319        agg = expression.this
    1320        agg_arg = agg.this
    1321        cond = expression.expression.this
    1322        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1323        return self.sql(agg)

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

    1325    def hint_sql(self, expression: exp.Hint) -> str:
    1326        if not self.QUERY_HINTS:
    1327            self.unsupported("Hints are not supported")
    1328            return ""
    1329
    1330        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

    1332    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
    1333        using = self.sql(expression, "using")
    1334        using = f" USING {using}" if using else ""
    1335        columns = self.expressions(expression, key="columns", flat=True)
    1336        columns = f"({columns})" if columns else ""
    1337        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1338        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1339        where = self.sql(expression, "where")
    1340        include = self.expressions(expression, key="include", flat=True)
    1341        if include:
    1342            include = f" INCLUDE ({include})"
    1343        with_storage = self.expressions(expression, key="with_storage", flat=True)
    1344        with_storage = f" WITH ({with_storage})" if with_storage else ""
    1345        tablespace = self.sql(expression, "tablespace")
    1346        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
    1347        on = self.sql(expression, "on")
    1348        on = f" ON {on}" if on else ""
    1349
    1350        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"

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

    1352    def index_sql(self, expression: exp.Index) -> str:
    1353        unique = "UNIQUE " if expression.args.get("unique") else ""
    1354        primary = "PRIMARY " if expression.args.get("primary") else ""
    1355        amp = "AMP " if expression.args.get("amp") else ""
    1356        name = self.sql(expression, "this")
    1357        name = f"{name} " if name else ""
    1358        table = self.sql(expression, "table")
    1359        table = f"{self.INDEX_ON} {table}" if table else ""
    1360
    1361        index = "INDEX " if not table else ""
    1362
    1363        params = self.sql(expression, "params")
    1364        return f"{unique}{primary}{amp}{index}{name}{table}{params}"

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

    1366    def identifier_sql(self, expression: exp.Identifier) -> str:
    1367        text = expression.name
    1368        lower = text.lower()
    1369        text = lower if self.normalize and not expression.quoted else text
    1370        text = text.replace(self.dialect.IDENTIFIER_END, self._escaped_identifier_end)
    1371        if (
    1372            expression.quoted
    1373            or self.dialect.can_identify(text, self.identify)
    1374            or lower in self.RESERVED_KEYWORDS
    1375            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1376        ):
    1377            text = f"{self.dialect.IDENTIFIER_START}{text}{self.dialect.IDENTIFIER_END}"
    1378        return text

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

    1380    def hex_sql(self, expression: exp.Hex) -> str:
    1381        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1382        if self.dialect.HEX_LOWERCASE:
    1383            text = self.func("LOWER", text)
    1384
    1385        return text

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

    1387    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
    1388        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1389        if not self.dialect.HEX_LOWERCASE:
    1390            text = self.func("LOWER", text)
    1391        return text

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

    1393    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1394        input_format = self.sql(expression, "input_format")
    1395        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1396        output_format = self.sql(expression, "output_format")
    1397        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1398        return self.sep().join((input_format, output_format))

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

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

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

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

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

    1407    def properties_sql(self, expression: exp.Properties) -> str:
    1408        root_properties = []
    1409        with_properties = []
    1410
    1411        for p in expression.expressions:
    1412            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1413            if p_loc == exp.Properties.Location.POST_WITH:
    1414                with_properties.append(p)
    1415            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1416                root_properties.append(p)
    1417
    1418        root_props = self.root_properties(exp.Properties(expressions=root_properties))
    1419        with_props = self.with_properties(exp.Properties(expressions=with_properties))
    1420
    1421        if root_props and with_props and not self.pretty:
    1422            with_props = " " + with_props
    1423
    1424        return root_props + with_props

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

    1426    def root_properties(self, properties: exp.Properties) -> str:
    1427        if properties.expressions:
    1428            return self.expressions(properties, indent=False, sep=" ")
    1429        return ""

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

    1431    def properties(
    1432        self,
    1433        properties: exp.Properties,
    1434        prefix: str = "",
    1435        sep: str = ", ",
    1436        suffix: str = "",
    1437        wrapped: bool = True,
    1438    ) -> str:
    1439        if properties.expressions:
    1440            expressions = self.expressions(properties, sep=sep, indent=False)
    1441            if expressions:
    1442                expressions = self.wrap(expressions) if wrapped else expressions
    1443                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1444        return ""

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

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

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

    1449    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1450        properties_locs = defaultdict(list)
    1451        for p in properties.expressions:
    1452            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1453            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1454                properties_locs[p_loc].append(p)
    1455            else:
    1456                self.unsupported(f"Unsupported property {p.key}")
    1457
    1458        return properties_locs

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

    1460    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1461        if isinstance(expression.this, exp.Dot):
    1462            return self.sql(expression, "this")
    1463        return f"'{expression.name}'" if string_key else expression.name

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

    1465    def property_sql(self, expression: exp.Property) -> str:
    1466        property_cls = expression.__class__
    1467        if property_cls == exp.Property:
    1468            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1469
    1470        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1471        if not property_name:
    1472            self.unsupported(f"Unsupported property {expression.key}")
    1473
    1474        return f"{property_name}={self.sql(expression, 'this')}"

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

    1476    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1477        if self.SUPPORTS_CREATE_TABLE_LIKE:
    1478            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1479            options = f" {options}" if options else ""
    1480
    1481            like = f"LIKE {self.sql(expression, 'this')}{options}"
    1482            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
    1483                like = f"({like})"
    1484
    1485            return like
    1486
    1487        if expression.expressions:
    1488            self.unsupported("Transpilation of LIKE property options is unsupported")
    1489
    1490        select = exp.select("*").from_(expression.this).limit(0)
    1491        return f"AS {self.sql(select)}"

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

    1493    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1494        no = "NO " if expression.args.get("no") else ""
    1495        protection = " PROTECTION" if expression.args.get("protection") else ""
    1496        return f"{no}FALLBACK{protection}"

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

    1498    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1499        no = "NO " if expression.args.get("no") else ""
    1500        local = expression.args.get("local")
    1501        local = f"{local} " if local else ""
    1502        dual = "DUAL " if expression.args.get("dual") else ""
    1503        before = "BEFORE " if expression.args.get("before") else ""
    1504        after = "AFTER " if expression.args.get("after") else ""
    1505        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1507    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1508        freespace = self.sql(expression, "this")
    1509        percent = " PERCENT" if expression.args.get("percent") else ""
    1510        return f"FREESPACE={freespace}{percent}"

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

    1512    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1513        if expression.args.get("default"):
    1514            property = "DEFAULT"
    1515        elif expression.args.get("on"):
    1516            property = "ON"
    1517        else:
    1518            property = "OFF"
    1519        return f"CHECKSUM={property}"

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

    1521    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1522        if expression.args.get("no"):
    1523            return "NO MERGEBLOCKRATIO"
    1524        if expression.args.get("default"):
    1525            return "DEFAULT MERGEBLOCKRATIO"
    1526
    1527        percent = " PERCENT" if expression.args.get("percent") else ""
    1528        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1530    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1531        default = expression.args.get("default")
    1532        minimum = expression.args.get("minimum")
    1533        maximum = expression.args.get("maximum")
    1534        if default or minimum or maximum:
    1535            if default:
    1536                prop = "DEFAULT"
    1537            elif minimum:
    1538                prop = "MINIMUM"
    1539            else:
    1540                prop = "MAXIMUM"
    1541            return f"{prop} DATABLOCKSIZE"
    1542        units = expression.args.get("units")
    1543        units = f" {units}" if units else ""
    1544        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1546    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1547        autotemp = expression.args.get("autotemp")
    1548        always = expression.args.get("always")
    1549        default = expression.args.get("default")
    1550        manual = expression.args.get("manual")
    1551        never = expression.args.get("never")
    1552
    1553        if autotemp is not None:
    1554            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1555        elif always:
    1556            prop = "ALWAYS"
    1557        elif default:
    1558            prop = "DEFAULT"
    1559        elif manual:
    1560            prop = "MANUAL"
    1561        elif never:
    1562            prop = "NEVER"
    1563        return f"BLOCKCOMPRESSION={prop}"

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

    1565    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1566        no = expression.args.get("no")
    1567        no = " NO" if no else ""
    1568        concurrent = expression.args.get("concurrent")
    1569        concurrent = " CONCURRENT" if concurrent else ""
    1570        target = self.sql(expression, "target")
    1571        target = f" {target}" if target else ""
    1572        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"

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

    1574    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1575        if isinstance(expression.this, list):
    1576            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1577        if expression.this:
    1578            modulus = self.sql(expression, "this")
    1579            remainder = self.sql(expression, "expression")
    1580            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1581
    1582        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1583        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1584        return f"FROM ({from_expressions}) TO ({to_expressions})"

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

    1586    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1587        this = self.sql(expression, "this")
    1588
    1589        for_values_or_default = expression.expression
    1590        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1591            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1592        else:
    1593            for_values_or_default = " DEFAULT"
    1594
    1595        return f"PARTITION OF {this}{for_values_or_default}"

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

    1597    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1598        kind = expression.args.get("kind")
    1599        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1600        for_or_in = expression.args.get("for_or_in")
    1601        for_or_in = f" {for_or_in}" if for_or_in else ""
    1602        lock_type = expression.args.get("lock_type")
    1603        override = " OVERRIDE" if expression.args.get("override") else ""
    1604        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"

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

    1606    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1607        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1608        statistics = expression.args.get("statistics")
    1609        statistics_sql = ""
    1610        if statistics is not None:
    1611            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1612        return f"{data_sql}{statistics_sql}"

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

    1614    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1615        this = self.sql(expression, "this")
    1616        this = f"HISTORY_TABLE={this}" if this else ""
    1617        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
    1618        data_consistency = (
    1619            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
    1620        )
    1621        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    1622        retention_period = (
    1623            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
    1624        )
    1625
    1626        if this:
    1627            on_sql = self.func("ON", this, data_consistency, retention_period)
    1628        else:
    1629            on_sql = "ON" if expression.args.get("on") else "OFF"
    1630
    1631        sql = f"SYSTEM_VERSIONING={on_sql}"
    1632
    1633        return f"WITH({sql})" if expression.args.get("with") else sql

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

    1635    def insert_sql(self, expression: exp.Insert) -> str:
    1636        hint = self.sql(expression, "hint")
    1637        overwrite = expression.args.get("overwrite")
    1638
    1639        if isinstance(expression.this, exp.Directory):
    1640            this = " OVERWRITE" if overwrite else " INTO"
    1641        else:
    1642            this = self.INSERT_OVERWRITE if overwrite else " INTO"
    1643
    1644        stored = self.sql(expression, "stored")
    1645        stored = f" {stored}" if stored else ""
    1646        alternative = expression.args.get("alternative")
    1647        alternative = f" OR {alternative}" if alternative else ""
    1648        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1649        is_function = expression.args.get("is_function")
    1650        if is_function:
    1651            this = f"{this} FUNCTION"
    1652        this = f"{this} {self.sql(expression, 'this')}"
    1653
    1654        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1655        where = self.sql(expression, "where")
    1656        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1657        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1658        on_conflict = self.sql(expression, "conflict")
    1659        on_conflict = f" {on_conflict}" if on_conflict else ""
    1660        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1661        returning = self.sql(expression, "returning")
    1662
    1663        if self.RETURNING_END:
    1664            expression_sql = f"{expression_sql}{on_conflict}{returning}"
    1665        else:
    1666            expression_sql = f"{returning}{expression_sql}{on_conflict}"
    1667
    1668        partition_by = self.sql(expression, "partition")
    1669        partition_by = f" {partition_by}" if partition_by else ""
    1670        settings = self.sql(expression, "settings")
    1671        settings = f" {settings}" if settings else ""
    1672
    1673        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}"
    1674        return self.prepend_ctes(expression, sql)

def intersect_sql(self, expression: sqlglot.expressions.Intersect) -> str: View Source

    1676    def intersect_sql(self, expression: exp.Intersect) -> str:
    1677        return self.set_operations(expression)

def intersect_op(self, expression: sqlglot.expressions.Intersect) -> str: View Source

    1679    def intersect_op(self, expression: exp.Intersect) -> str:
    1680        return f"INTERSECT{'' if expression.args.get('distinct') else ' ALL'}"

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

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

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

    1685    def kill_sql(self, expression: exp.Kill) -> str:
    1686        kind = self.sql(expression, "kind")
    1687        kind = f" {kind}" if kind else ""
    1688        this = self.sql(expression, "this")
    1689        this = f" {this}" if this else ""
    1690        return f"KILL{kind}{this}"

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

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

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

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

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

    1698    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1699        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1700
    1701        constraint = self.sql(expression, "constraint")
    1702        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
    1703
    1704        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
    1705        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
    1706        action = self.sql(expression, "action")
    1707
    1708        expressions = self.expressions(expression, flat=True)
    1709        if expressions:
    1710            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1711            expressions = f" {set_keyword}{expressions}"
    1712
    1713        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}"

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

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

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

    1718    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1719        fields = self.sql(expression, "fields")
    1720        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1721        escaped = self.sql(expression, "escaped")
    1722        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1723        items = self.sql(expression, "collection_items")
    1724        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1725        keys = self.sql(expression, "map_keys")
    1726        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1727        lines = self.sql(expression, "lines")
    1728        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1729        null = self.sql(expression, "null")
    1730        null = f" NULL DEFINED AS {null}" if null else ""
    1731        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1736    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1737        this = f"{self.sql(expression, 'this')} INDEX"
    1738        target = self.sql(expression, "target")
    1739        target = f" FOR {target}" if target else ""
    1740        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1742    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1743        this = self.sql(expression, "this")
    1744        kind = self.sql(expression, "kind")
    1745        expr = self.sql(expression, "expression")
    1746        return f"{this} ({kind} => {expr})"

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

    1748    def table_parts(self, expression: exp.Table) -> str:
    1749        return ".".join(
    1750            self.sql(part)
    1751            for part in (
    1752                expression.args.get("catalog"),
    1753                expression.args.get("db"),
    1754                expression.args.get("this"),
    1755            )
    1756            if part is not None
    1757        )

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

    1759    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1760        table = self.table_parts(expression)
    1761        only = "ONLY " if expression.args.get("only") else ""
    1762        partition = self.sql(expression, "partition")
    1763        partition = f" {partition}" if partition else ""
    1764        version = self.sql(expression, "version")
    1765        version = f" {version}" if version else ""
    1766        alias = self.sql(expression, "alias")
    1767        alias = f"{sep}{alias}" if alias else ""
    1768        hints = self.expressions(expression, key="hints", sep=" ")
    1769        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1770        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    1771        joins = self.indent(
    1772            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    1773        )
    1774        laterals = self.expressions(expression, key="laterals", sep="")
    1775
    1776        file_format = self.sql(expression, "format")
    1777        if file_format:
    1778            pattern = self.sql(expression, "pattern")
    1779            pattern = f", PATTERN => {pattern}" if pattern else ""
    1780            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    1781
    1782        ordinality = expression.args.get("ordinality") or ""
    1783        if ordinality:
    1784            ordinality = f" WITH ORDINALITY{alias}"
    1785            alias = ""
    1786
    1787        when = self.sql(expression, "when")
    1788        if when:
    1789            table = f"{table} {when}"
    1790
    1791        changes = self.sql(expression, "changes")
    1792        changes = f" {changes}" if changes else ""
    1793
    1794        rows_from = self.expressions(expression, key="rows_from")
    1795        if rows_from:
    1796            table = f"ROWS FROM {self.wrap(rows_from)}"
    1797
    1798        return f"{only}{table}{changes}{partition}{version}{file_format}{alias}{hints}{pivots}{joins}{laterals}{ordinality}"

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

    1800    def tablesample_sql(
    1801        self,
    1802        expression: exp.TableSample,
    1803        sep: str = " AS ",
    1804        tablesample_keyword: t.Optional[str] = None,
    1805    ) -> str:
    1806        if self.dialect.ALIAS_POST_TABLESAMPLE and expression.this and expression.this.alias:
    1807            table = expression.this.copy()
    1808            table.set("alias", None)
    1809            this = self.sql(table)
    1810            alias = f"{sep}{self.sql(expression.this, 'alias')}"
    1811        else:
    1812            this = self.sql(expression, "this")
    1813            alias = ""
    1814
    1815        method = self.sql(expression, "method")
    1816        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1817        numerator = self.sql(expression, "bucket_numerator")
    1818        denominator = self.sql(expression, "bucket_denominator")
    1819        field = self.sql(expression, "bucket_field")
    1820        field = f" ON {field}" if field else ""
    1821        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1822        seed = self.sql(expression, "seed")
    1823        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
    1824
    1825        size = self.sql(expression, "size")
    1826        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
    1827            size = f"{size} ROWS"
    1828
    1829        percent = self.sql(expression, "percent")
    1830        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
    1831            percent = f"{percent} PERCENT"
    1832
    1833        expr = f"{bucket}{percent}{size}"
    1834        if self.TABLESAMPLE_REQUIRES_PARENS:
    1835            expr = f"({expr})"
    1836
    1837        return (
    1838            f"{this} {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}{alias}"
    1839        )

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

    1841    def pivot_sql(self, expression: exp.Pivot) -> str:
    1842        expressions = self.expressions(expression, flat=True)
    1843
    1844        if expression.this:
    1845            this = self.sql(expression, "this")
    1846            if not expressions:
    1847                return f"UNPIVOT {this}"
    1848
    1849            on = f"{self.seg('ON')} {expressions}"
    1850            using = self.expressions(expression, key="using", flat=True)
    1851            using = f"{self.seg('USING')} {using}" if using else ""
    1852            group = self.sql(expression, "group")
    1853            return f"PIVOT {this}{on}{using}{group}"
    1854
    1855        alias = self.sql(expression, "alias")
    1856        alias = f" AS {alias}" if alias else ""
    1857        direction = self.seg("UNPIVOT" if expression.unpivot else "PIVOT")
    1858
    1859        field = self.sql(expression, "field")
    1860        if field and isinstance(expression.args.get("field"), exp.PivotAny):
    1861            field = f"IN ({field})"
    1862
    1863        include_nulls = expression.args.get("include_nulls")
    1864        if include_nulls is not None:
    1865            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    1866        else:
    1867            nulls = ""
    1868
    1869        default_on_null = self.sql(expression, "default_on_null")
    1870        default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else ""
    1871        return f"{direction}{nulls}({expressions} FOR {field}{default_on_null}){alias}"

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

    1873    def version_sql(self, expression: exp.Version) -> str:
    1874        this = f"FOR {expression.name}"
    1875        kind = expression.text("kind")
    1876        expr = self.sql(expression, "expression")
    1877        return f"{this} {kind} {expr}"

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

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

    1882    def update_sql(self, expression: exp.Update) -> str:
    1883        this = self.sql(expression, "this")
    1884        set_sql = self.expressions(expression, flat=True)
    1885        from_sql = self.sql(expression, "from")
    1886        where_sql = self.sql(expression, "where")
    1887        returning = self.sql(expression, "returning")
    1888        order = self.sql(expression, "order")
    1889        limit = self.sql(expression, "limit")
    1890        if self.RETURNING_END:
    1891            expression_sql = f"{from_sql}{where_sql}{returning}"
    1892        else:
    1893            expression_sql = f"{returning}{from_sql}{where_sql}"
    1894        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    1895        return self.prepend_ctes(expression, sql)

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

    1897    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
    1898        values_as_table = values_as_table and self.VALUES_AS_TABLE
    1899
    1900        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    1901        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
    1902            args = self.expressions(expression)
    1903            alias = self.sql(expression, "alias")
    1904            values = f"VALUES{self.seg('')}{args}"
    1905            values = (
    1906                f"({values})"
    1907                if self.WRAP_DERIVED_VALUES and (alias or isinstance(expression.parent, exp.From))
    1908                else values
    1909            )
    1910            return f"{values} AS {alias}" if alias else values
    1911
    1912        # Converts `VALUES...` expression into a series of select unions.
    1913        alias_node = expression.args.get("alias")
    1914        column_names = alias_node and alias_node.columns
    1915
    1916        selects: t.List[exp.Query] = []
    1917
    1918        for i, tup in enumerate(expression.expressions):
    1919            row = tup.expressions
    1920
    1921            if i == 0 and column_names:
    1922                row = [
    1923                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    1924                ]
    1925
    1926            selects.append(exp.Select(expressions=row))
    1927
    1928        if self.pretty:
    1929            # This may result in poor performance for large-cardinality `VALUES` tables, due to
    1930            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
    1931            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
    1932            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
    1933            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
    1934
    1935        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
    1936        unions = " UNION ALL ".join(self.sql(select) for select in selects)
    1937        return f"({unions}){alias}"

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

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

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

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

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

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

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

    1950    def group_sql(self, expression: exp.Group) -> str:
    1951        group_by_all = expression.args.get("all")
    1952        if group_by_all is True:
    1953            modifier = " ALL"
    1954        elif group_by_all is False:
    1955            modifier = " DISTINCT"
    1956        else:
    1957            modifier = ""
    1958
    1959        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
    1960
    1961        grouping_sets = self.expressions(expression, key="grouping_sets", indent=False)
    1962        grouping_sets = (
    1963            f"{self.seg('GROUPING SETS')} {self.wrap(grouping_sets)}" if grouping_sets else ""
    1964        )
    1965
    1966        cube = expression.args.get("cube", [])
    1967        if seq_get(cube, 0) is True:
    1968            return f"{group_by}{self.seg('WITH CUBE')}"
    1969        else:
    1970            cube_sql = self.expressions(expression, key="cube", indent=False)
    1971            cube_sql = f"{self.seg('CUBE')} {self.wrap(cube_sql)}" if cube_sql else ""
    1972
    1973        rollup = expression.args.get("rollup", [])
    1974        if seq_get(rollup, 0) is True:
    1975            return f"{group_by}{self.seg('WITH ROLLUP')}"
    1976        else:
    1977            rollup_sql = self.expressions(expression, key="rollup", indent=False)
    1978            rollup_sql = f"{self.seg('ROLLUP')} {self.wrap(rollup_sql)}" if rollup_sql else ""
    1979
    1980        groupings = csv(
    1981            grouping_sets,
    1982            cube_sql,
    1983            rollup_sql,
    1984            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    1985            sep=self.GROUPINGS_SEP,
    1986        )
    1987
    1988        if expression.args.get("expressions") and groupings:
    1989            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    1990
    1991        return f"{group_by}{groupings}"

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

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

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

    1997    def connect_sql(self, expression: exp.Connect) -> str:
    1998        start = self.sql(expression, "start")
    1999        start = self.seg(f"START WITH {start}") if start else ""
    2000        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
    2001        connect = self.sql(expression, "connect")
    2002        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
    2003        return start + connect

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

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

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

    2008    def join_sql(self, expression: exp.Join) -> str:
    2009        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    2010            side = None
    2011        else:
    2012            side = expression.side
    2013
    2014        op_sql = " ".join(
    2015            op
    2016            for op in (
    2017                expression.method,
    2018                "GLOBAL" if expression.args.get("global") else None,
    2019                side,
    2020                expression.kind,
    2021                expression.hint if self.JOIN_HINTS else None,
    2022            )
    2023            if op
    2024        )
    2025        match_cond = self.sql(expression, "match_condition")
    2026        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
    2027        on_sql = self.sql(expression, "on")
    2028        using = expression.args.get("using")
    2029
    2030        if not on_sql and using:
    2031            on_sql = csv(*(self.sql(column) for column in using))
    2032
    2033        this = expression.this
    2034        this_sql = self.sql(this)
    2035
    2036        if on_sql:
    2037            on_sql = self.indent(on_sql, skip_first=True)
    2038            space = self.seg(" " * self.pad) if self.pretty else " "
    2039            if using:
    2040                on_sql = f"{space}USING ({on_sql})"
    2041            else:
    2042                on_sql = f"{space}ON {on_sql}"
    2043        elif not op_sql:
    2044            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
    2045                return f" {this_sql}"
    2046
    2047            return f", {this_sql}"
    2048
    2049        if op_sql != "STRAIGHT_JOIN":
    2050            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    2051
    2052        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

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

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

    2059    def lateral_op(self, expression: exp.Lateral) -> str:
    2060        cross_apply = expression.args.get("cross_apply")
    2061
    2062        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    2063        if cross_apply is True:
    2064            op = "INNER JOIN "
    2065        elif cross_apply is False:
    2066            op = "LEFT JOIN "
    2067        else:
    2068            op = ""
    2069
    2070        return f"{op}LATERAL"

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

    2072    def lateral_sql(self, expression: exp.Lateral) -> str:
    2073        this = self.sql(expression, "this")
    2074
    2075        if expression.args.get("view"):
    2076            alias = expression.args["alias"]
    2077            columns = self.expressions(alias, key="columns", flat=True)
    2078            table = f" {alias.name}" if alias.name else ""
    2079            columns = f" AS {columns}" if columns else ""
    2080            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    2081            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    2082
    2083        alias = self.sql(expression, "alias")
    2084        alias = f" AS {alias}" if alias else ""
    2085        return f"{self.lateral_op(expression)} {this}{alias}"

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

    2087    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    2088        this = self.sql(expression, "this")
    2089
    2090        args = [
    2091            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    2092            for e in (expression.args.get(k) for k in ("offset", "expression"))
    2093            if e
    2094        ]
    2095
    2096        args_sql = ", ".join(self.sql(e) for e in args)
    2097        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
    2098        expressions = self.expressions(expression, flat=True)
    2099        expressions = f" BY {expressions}" if expressions else ""
    2100
    2101        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}"

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

    2103    def offset_sql(self, expression: exp.Offset) -> str:
    2104        this = self.sql(expression, "this")
    2105        value = expression.expression
    2106        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    2107        expressions = self.expressions(expression, flat=True)
    2108        expressions = f" BY {expressions}" if expressions else ""
    2109        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"

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

    2111    def setitem_sql(self, expression: exp.SetItem) -> str:
    2112        kind = self.sql(expression, "kind")
    2113        kind = f"{kind} " if kind else ""
    2114        this = self.sql(expression, "this")
    2115        expressions = self.expressions(expression)
    2116        collate = self.sql(expression, "collate")
    2117        collate = f" COLLATE {collate}" if collate else ""
    2118        global_ = "GLOBAL " if expression.args.get("global") else ""
    2119        return f"{global_}{kind}{this}{expressions}{collate}"

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

    2121    def set_sql(self, expression: exp.Set) -> str:
    2122        expressions = (
    2123            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    2124        )
    2125        tag = " TAG" if expression.args.get("tag") else ""
    2126        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"

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

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

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

    2131    def lock_sql(self, expression: exp.Lock) -> str:
    2132        if not self.LOCKING_READS_SUPPORTED:
    2133            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    2134            return ""
    2135
    2136        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    2137        expressions = self.expressions(expression, flat=True)
    2138        expressions = f" OF {expressions}" if expressions else ""
    2139        wait = expression.args.get("wait")
    2140
    2141        if wait is not None:
    2142            if isinstance(wait, exp.Literal):
    2143                wait = f" WAIT {self.sql(wait)}"
    2144            else:
    2145                wait = " NOWAIT" if wait else " SKIP LOCKED"
    2146
    2147        return f"{lock_type}{expressions}{wait or ''}"

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

    2149    def literal_sql(self, expression: exp.Literal) -> str:
    2150        text = expression.this or ""
    2151        if expression.is_string:
    2152            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    2153        return text

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

    2155    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
    2156        if self.dialect.ESCAPED_SEQUENCES:
    2157            to_escaped = self.dialect.ESCAPED_SEQUENCES
    2158            text = "".join(
    2159                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
    2160            )
    2161
    2162        return self._replace_line_breaks(text).replace(
    2163            self.dialect.QUOTE_END, self._escaped_quote_end
    2164        )

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

    2166    def loaddata_sql(self, expression: exp.LoadData) -> str:
    2167        local = " LOCAL" if expression.args.get("local") else ""
    2168        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    2169        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    2170        this = f" INTO TABLE {self.sql(expression, 'this')}"
    2171        partition = self.sql(expression, "partition")
    2172        partition = f" {partition}" if partition else ""
    2173        input_format = self.sql(expression, "input_format")
    2174        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    2175        serde = self.sql(expression, "serde")
    2176        serde = f" SERDE {serde}" if serde else ""
    2177        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    2179    def null_sql(self, *_) -> str:
    2180        return "NULL"

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

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

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

    2185    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2186        this = self.sql(expression, "this")
    2187        this = f"{this} " if this else this
    2188        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2189        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

    2191    def withfill_sql(self, expression: exp.WithFill) -> str:
    2192        from_sql = self.sql(expression, "from")
    2193        from_sql = f" FROM {from_sql}" if from_sql else ""
    2194        to_sql = self.sql(expression, "to")
    2195        to_sql = f" TO {to_sql}" if to_sql else ""
    2196        step_sql = self.sql(expression, "step")
    2197        step_sql = f" STEP {step_sql}" if step_sql else ""
    2198        interpolated_values = [
    2199            f"{self.sql(named_expression, 'alias')} AS {self.sql(named_expression, 'this')}"
    2200            for named_expression in expression.args.get("interpolate") or []
    2201        ]
    2202        interpolate = (
    2203            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    2204        )
    2205        return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"

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

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

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

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

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

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

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

    2216    def ordered_sql(self, expression: exp.Ordered) -> str:
    2217        desc = expression.args.get("desc")
    2218        asc = not desc
    2219
    2220        nulls_first = expression.args.get("nulls_first")
    2221        nulls_last = not nulls_first
    2222        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
    2223        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
    2224        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
    2225
    2226        this = self.sql(expression, "this")
    2227
    2228        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
    2229        nulls_sort_change = ""
    2230        if nulls_first and (
    2231            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    2232        ):
    2233            nulls_sort_change = " NULLS FIRST"
    2234        elif (
    2235            nulls_last
    2236            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    2237            and not nulls_are_last
    2238        ):
    2239            nulls_sort_change = " NULLS LAST"
    2240
    2241        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
    2242        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    2243            window = expression.find_ancestor(exp.Window, exp.Select)
    2244            if isinstance(window, exp.Window) and window.args.get("spec"):
    2245                self.unsupported(
    2246                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
    2247                )
    2248                nulls_sort_change = ""
    2249            elif self.NULL_ORDERING_SUPPORTED is None:
    2250                if expression.this.is_int:
    2251                    self.unsupported(
    2252                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
    2253                    )
    2254                elif not isinstance(expression.this, exp.Rand):
    2255                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
    2256                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
    2257                nulls_sort_change = ""
    2258
    2259        with_fill = self.sql(expression, "with_fill")
    2260        with_fill = f" {with_fill}" if with_fill else ""
    2261
    2262        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"

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

    2264    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
    2265        window_frame = self.sql(expression, "window_frame")
    2266        window_frame = f"{window_frame} " if window_frame else ""
    2267
    2268        this = self.sql(expression, "this")
    2269
    2270        return f"{window_frame}{this}"

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

    2272    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    2273        partition = self.partition_by_sql(expression)
    2274        order = self.sql(expression, "order")
    2275        measures = self.expressions(expression, key="measures")
    2276        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    2277        rows = self.sql(expression, "rows")
    2278        rows = self.seg(rows) if rows else ""
    2279        after = self.sql(expression, "after")
    2280        after = self.seg(after) if after else ""
    2281        pattern = self.sql(expression, "pattern")
    2282        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    2283        definition_sqls = [
    2284            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    2285            for definition in expression.args.get("define", [])
    2286        ]
    2287        definitions = self.expressions(sqls=definition_sqls)
    2288        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    2289        body = "".join(
    2290            (
    2291                partition,
    2292                order,
    2293                measures,
    2294                rows,
    2295                after,
    2296                pattern,
    2297                define,
    2298            )
    2299        )
    2300        alias = self.sql(expression, "alias")
    2301        alias = f" {alias}" if alias else ""
    2302        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    2304    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    2305        limit = expression.args.get("limit")
    2306
    2307        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    2308            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    2309        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    2310            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    2311
    2312        return csv(
    2313            *sqls,
    2314            *[self.sql(join) for join in expression.args.get("joins") or []],
    2315            self.sql(expression, "connect"),
    2316            self.sql(expression, "match"),
    2317            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2318            self.sql(expression, "prewhere"),
    2319            self.sql(expression, "where"),
    2320            self.sql(expression, "group"),
    2321            self.sql(expression, "having"),
    2322            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
    2323            self.sql(expression, "order"),
    2324            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
    2325            *self.after_limit_modifiers(expression),
    2326            self.options_modifier(expression),
    2327            sep="",
    2328        )

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

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

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

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

    2337    def offset_limit_modifiers(
    2338        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2339    ) -> t.List[str]:
    2340        return [
    2341            self.sql(expression, "offset") if fetch else self.sql(limit),
    2342            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2343        ]

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

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

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

    2350    def select_sql(self, expression: exp.Select) -> str:
    2351        into = expression.args.get("into")
    2352        if not self.SUPPORTS_SELECT_INTO and into:
    2353            into.pop()
    2354
    2355        hint = self.sql(expression, "hint")
    2356        distinct = self.sql(expression, "distinct")
    2357        distinct = f" {distinct}" if distinct else ""
    2358        kind = self.sql(expression, "kind")
    2359
    2360        limit = expression.args.get("limit")
    2361        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
    2362            top = self.limit_sql(limit, top=True)
    2363            limit.pop()
    2364        else:
    2365            top = ""
    2366
    2367        expressions = self.expressions(expression)
    2368
    2369        if kind:
    2370            if kind in self.SELECT_KINDS:
    2371                kind = f" AS {kind}"
    2372            else:
    2373                if kind == "STRUCT":
    2374                    expressions = self.expressions(
    2375                        sqls=[
    2376                            self.sql(
    2377                                exp.Struct(
    2378                                    expressions=[
    2379                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
    2380                                        if isinstance(e, exp.Alias)
    2381                                        else e
    2382                                        for e in expression.expressions
    2383                                    ]
    2384                                )
    2385                            )
    2386                        ]
    2387                    )
    2388                kind = ""
    2389
    2390        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
    2391        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
    2392        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
    2393        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    2394        sql = self.query_modifiers(
    2395            expression,
    2396            f"SELECT{top_distinct}{kind}{expressions}",
    2397            self.sql(expression, "into", comment=False),
    2398            self.sql(expression, "from", comment=False),
    2399        )
    2400
    2401        sql = self.prepend_ctes(expression, sql)
    2402
    2403        if not self.SUPPORTS_SELECT_INTO and into:
    2404            if into.args.get("temporary"):
    2405                table_kind = " TEMPORARY"
    2406            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
    2407                table_kind = " UNLOGGED"
    2408            else:
    2409                table_kind = ""
    2410            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
    2411
    2412        return sql

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

    2414    def schema_sql(self, expression: exp.Schema) -> str:
    2415        this = self.sql(expression, "this")
    2416        sql = self.schema_columns_sql(expression)
    2417        return f"{this} {sql}" if this and sql else this or sql

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

    2419    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2420        if expression.expressions:
    2421            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2422        return ""

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

    2424    def star_sql(self, expression: exp.Star) -> str:
    2425        except_ = self.expressions(expression, key="except", flat=True)
    2426        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
    2427        replace = self.expressions(expression, key="replace", flat=True)
    2428        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
    2429        rename = self.expressions(expression, key="rename", flat=True)
    2430        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
    2431        return f"*{except_}{replace}{rename}"

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

    2433    def parameter_sql(self, expression: exp.Parameter) -> str:
    2434        this = self.sql(expression, "this")
    2435        return f"{self.PARAMETER_TOKEN}{this}"

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

    2437    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2438        this = self.sql(expression, "this")
    2439        kind = expression.text("kind")
    2440        if kind:
    2441            kind = f"{kind}."
    2442        return f"@@{kind}{this}"

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

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

    2447    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2448        alias = self.sql(expression, "alias")
    2449        alias = f"{sep}{alias}" if alias else ""
    2450        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2451        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2452        return self.prepend_ctes(expression, sql)

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

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

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

    2458    def set_operations(self, expression: exp.SetOperation) -> str:
    2459        if not self.SET_OP_MODIFIERS:
    2460            limit = expression.args.get("limit")
    2461            order = expression.args.get("order")
    2462
    2463            if limit or order:
    2464                select = exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
    2465
    2466                if limit:
    2467                    select = select.limit(limit.pop(), copy=False)
    2468                if order:
    2469                    select = select.order_by(order.pop(), copy=False)
    2470                return self.sql(select)
    2471
    2472        sqls: t.List[str] = []
    2473        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    2474
    2475        while stack:
    2476            node = stack.pop()
    2477
    2478            if isinstance(node, exp.SetOperation):
    2479                stack.append(node.expression)
    2480                stack.append(
    2481                    self.maybe_comment(
    2482                        getattr(self, f"{node.key}_op")(node),
    2483                        comments=node.comments,
    2484                        separated=True,
    2485                    )
    2486                )
    2487                stack.append(node.this)
    2488            else:
    2489                sqls.append(self.sql(node))
    2490
    2491        this = self.sep().join(sqls)
    2492        this = self.query_modifiers(expression, this)
    2493        return self.prepend_ctes(expression, this)

def union_sql(self, expression: sqlglot.expressions.Union) -> str: View Source

    2495    def union_sql(self, expression: exp.Union) -> str:
    2496        return self.set_operations(expression)

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

    2498    def union_op(self, expression: exp.SetOperation) -> str:
    2499        kind = " DISTINCT" if self.EXPLICIT_SET_OP else ""
    2500        kind = kind if expression.args.get("distinct") else " ALL"
    2501        by_name = " BY NAME" if expression.args.get("by_name") else ""
    2502        return f"UNION{kind}{by_name}"

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

    2504    def unnest_sql(self, expression: exp.Unnest) -> str:
    2505        args = self.expressions(expression, flat=True)
    2506
    2507        alias = expression.args.get("alias")
    2508        offset = expression.args.get("offset")
    2509
    2510        if self.UNNEST_WITH_ORDINALITY:
    2511            if alias and isinstance(offset, exp.Expression):
    2512                alias.append("columns", offset)
    2513
    2514        if alias and self.dialect.UNNEST_COLUMN_ONLY:
    2515            columns = alias.columns
    2516            alias = self.sql(columns[0]) if columns else ""
    2517        else:
    2518            alias = self.sql(alias)
    2519
    2520        alias = f" AS {alias}" if alias else alias
    2521        if self.UNNEST_WITH_ORDINALITY:
    2522            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2523        else:
    2524            if isinstance(offset, exp.Expression):
    2525                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2526            elif offset:
    2527                suffix = f"{alias} WITH OFFSET"
    2528            else:
    2529                suffix = alias
    2530
    2531        return f"UNNEST({args}){suffix}"

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

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

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

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

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

    2540    def window_sql(self, expression: exp.Window) -> str:
    2541        this = self.sql(expression, "this")
    2542        partition = self.partition_by_sql(expression)
    2543        order = expression.args.get("order")
    2544        order = self.order_sql(order, flat=True) if order else ""
    2545        spec = self.sql(expression, "spec")
    2546        alias = self.sql(expression, "alias")
    2547        over = self.sql(expression, "over") or "OVER"
    2548
    2549        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2550
    2551        first = expression.args.get("first")
    2552        if first is None:
    2553            first = ""
    2554        else:
    2555            first = "FIRST" if first else "LAST"
    2556
    2557        if not partition and not order and not spec and alias:
    2558            return f"{this} {alias}"
    2559
    2560        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    2561        return f"{this} ({args})"

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

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

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

    2567    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2568        kind = self.sql(expression, "kind")
    2569        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2570        end = (
    2571            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2572            or "CURRENT ROW"
    2573        )
    2574        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    2581    def between_sql(self, expression: exp.Between) -> str:
    2582        this = self.sql(expression, "this")
    2583        low = self.sql(expression, "low")
    2584        high = self.sql(expression, "high")
    2585        return f"{this} BETWEEN {low} AND {high}"

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

    2587    def bracket_offset_expressions(self, expression: exp.Bracket) -> t.List[exp.Expression]:
    2588        return apply_index_offset(
    2589            expression.this,
    2590            expression.expressions,
    2591            self.dialect.INDEX_OFFSET - expression.args.get("offset", 0),
    2592        )

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

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

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

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

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

    2602    def any_sql(self, expression: exp.Any) -> str:
    2603        this = self.sql(expression, "this")
    2604        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
    2605            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2606                this = self.wrap(this)
    2607            return f"ANY{this}"
    2608        return f"ANY {this}"

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

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

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

    2613    def case_sql(self, expression: exp.Case) -> str:
    2614        this = self.sql(expression, "this")
    2615        statements = [f"CASE {this}" if this else "CASE"]
    2616
    2617        for e in expression.args["ifs"]:
    2618            statements.append(f"WHEN {self.sql(e, 'this')}")
    2619            statements.append(f"THEN {self.sql(e, 'true')}")
    2620
    2621        default = self.sql(expression, "default")
    2622
    2623        if default:
    2624            statements.append(f"ELSE {default}")
    2625
    2626        statements.append("END")
    2627
    2628        if self.pretty and self.too_wide(statements):
    2629            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2630
    2631        return " ".join(statements)

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

    2633    def constraint_sql(self, expression: exp.Constraint) -> str:
    2634        this = self.sql(expression, "this")
    2635        expressions = self.expressions(expression, flat=True)
    2636        return f"CONSTRAINT {this} {expressions}"

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

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

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

    2643    def extract_sql(self, expression: exp.Extract) -> str:
    2644        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2645        expression_sql = self.sql(expression, "expression")
    2646        return f"EXTRACT({this} FROM {expression_sql})"

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

    2648    def trim_sql(self, expression: exp.Trim) -> str:
    2649        trim_type = self.sql(expression, "position")
    2650
    2651        if trim_type == "LEADING":
    2652            return self.func("LTRIM", expression.this)
    2653        elif trim_type == "TRAILING":
    2654            return self.func("RTRIM", expression.this)
    2655        else:
    2656            return self.func("TRIM", expression.this, expression.expression)

def convert_concat_args( self, expression: sqlglot.expressions.Concat | sqlglot.expressions.ConcatWs) -> List[sqlglot.expressions.Expression]: View Source

    2658    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2659        args = expression.expressions
    2660        if isinstance(expression, exp.ConcatWs):
    2661            args = args[1:]  # Skip the delimiter
    2662
    2663        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2664            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
    2665
    2666        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2667            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2668
    2669        return args

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

    2671    def concat_sql(self, expression: exp.Concat) -> str:
    2672        expressions = self.convert_concat_args(expression)
    2673
    2674        # Some dialects don't allow a single-argument CONCAT call
    2675        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2676            return self.sql(expressions[0])
    2677
    2678        return self.func("CONCAT", *expressions)

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

    2680    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2681        return self.func(
    2682            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2683        )

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

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

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

    2689    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2690        expressions = self.expressions(expression, flat=True)
    2691        reference = self.sql(expression, "reference")
    2692        reference = f" {reference}" if reference else ""
    2693        delete = self.sql(expression, "delete")
    2694        delete = f" ON DELETE {delete}" if delete else ""
    2695        update = self.sql(expression, "update")
    2696        update = f" ON UPDATE {update}" if update else ""
    2697        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"

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

    2699    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2700        expressions = self.expressions(expression, flat=True)
    2701        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2702        options = f" {options}" if options else ""
    2703        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

    2716    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
    2717        path = self.expressions(expression, sep="", flat=True).lstrip(".")
    2718        if self.QUOTE_JSON_PATH:
    2719            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
    2720
    2721        return path

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

    2723    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
    2724        if isinstance(expression, exp.JSONPathPart):
    2725            transform = self.TRANSFORMS.get(expression.__class__)
    2726            if not callable(transform):
    2727                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
    2728                return ""
    2729
    2730            return transform(self, expression)
    2731
    2732        if isinstance(expression, int):
    2733            return str(expression)
    2734
    2735        if self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
    2736            escaped = expression.replace("'", "\\'")
    2737            escaped = f"\\'{expression}\\'"
    2738        else:
    2739            escaped = expression.replace('"', '\\"')
    2740            escaped = f'"{escaped}"'
    2741
    2742        return escaped

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

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

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

    2747    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    2748        null_handling = expression.args.get("null_handling")
    2749        null_handling = f" {null_handling}" if null_handling else ""
    2750
    2751        unique_keys = expression.args.get("unique_keys")
    2752        if unique_keys is not None:
    2753            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2754        else:
    2755            unique_keys = ""
    2756
    2757        return_type = self.sql(expression, "return_type")
    2758        return_type = f" RETURNING {return_type}" if return_type else ""
    2759        encoding = self.sql(expression, "encoding")
    2760        encoding = f" ENCODING {encoding}" if encoding else ""
    2761
    2762        return self.func(
    2763            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    2764            *expression.expressions,
    2765            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2766        )

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

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

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

    2771    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2772        null_handling = expression.args.get("null_handling")
    2773        null_handling = f" {null_handling}" if null_handling else ""
    2774        return_type = self.sql(expression, "return_type")
    2775        return_type = f" RETURNING {return_type}" if return_type else ""
    2776        strict = " STRICT" if expression.args.get("strict") else ""
    2777        return self.func(
    2778            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2779        )

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

    2781    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2782        this = self.sql(expression, "this")
    2783        order = self.sql(expression, "order")
    2784        null_handling = expression.args.get("null_handling")
    2785        null_handling = f" {null_handling}" if null_handling else ""
    2786        return_type = self.sql(expression, "return_type")
    2787        return_type = f" RETURNING {return_type}" if return_type else ""
    2788        strict = " STRICT" if expression.args.get("strict") else ""
    2789        return self.func(
    2790            "JSON_ARRAYAGG",
    2791            this,
    2792            suffix=f"{order}{null_handling}{return_type}{strict})",
    2793        )

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

    2795    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2796        path = self.sql(expression, "path")
    2797        path = f" PATH {path}" if path else ""
    2798        nested_schema = self.sql(expression, "nested_schema")
    2799
    2800        if nested_schema:
    2801            return f"NESTED{path} {nested_schema}"
    2802
    2803        this = self.sql(expression, "this")
    2804        kind = self.sql(expression, "kind")
    2805        kind = f" {kind}" if kind else ""
    2806        return f"{this}{kind}{path}"

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

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

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

    2811    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    2812        this = self.sql(expression, "this")
    2813        path = self.sql(expression, "path")
    2814        path = f", {path}" if path else ""
    2815        error_handling = expression.args.get("error_handling")
    2816        error_handling = f" {error_handling}" if error_handling else ""
    2817        empty_handling = expression.args.get("empty_handling")
    2818        empty_handling = f" {empty_handling}" if empty_handling else ""
    2819        schema = self.sql(expression, "schema")
    2820        return self.func(
    2821            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    2822        )

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

    2824    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    2825        this = self.sql(expression, "this")
    2826        kind = self.sql(expression, "kind")
    2827        path = self.sql(expression, "path")
    2828        path = f" {path}" if path else ""
    2829        as_json = " AS JSON" if expression.args.get("as_json") else ""
    2830        return f"{this} {kind}{path}{as_json}"

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

    2832    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    2833        this = self.sql(expression, "this")
    2834        path = self.sql(expression, "path")
    2835        path = f", {path}" if path else ""
    2836        expressions = self.expressions(expression)
    2837        with_ = (
    2838            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2839            if expressions
    2840            else ""
    2841        )
    2842        return f"OPENJSON({this}{path}){with_}"

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

    2844    def in_sql(self, expression: exp.In) -> str:
    2845        query = expression.args.get("query")
    2846        unnest = expression.args.get("unnest")
    2847        field = expression.args.get("field")
    2848        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    2849
    2850        if query:
    2851            in_sql = self.sql(query)
    2852        elif unnest:
    2853            in_sql = self.in_unnest_op(unnest)
    2854        elif field:
    2855            in_sql = self.sql(field)
    2856        else:
    2857            in_sql = f"({self.expressions(expression, flat=True)})"
    2858
    2859        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    2864    def interval_sql(self, expression: exp.Interval) -> str:
    2865        unit = self.sql(expression, "unit")
    2866        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    2867            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    2868        unit = f" {unit}" if unit else ""
    2869
    2870        if self.SINGLE_STRING_INTERVAL:
    2871            this = expression.this.name if expression.this else ""
    2872            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    2873
    2874        this = self.sql(expression, "this")
    2875        if this:
    2876            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    2877            this = f" {this}" if unwrapped else f" ({this})"
    2878
    2879        return f"INTERVAL{this}{unit}"

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

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

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

    2884    def reference_sql(self, expression: exp.Reference) -> str:
    2885        this = self.sql(expression, "this")
    2886        expressions = self.expressions(expression, flat=True)
    2887        expressions = f"({expressions})" if expressions else ""
    2888        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2889        options = f" {options}" if options else ""
    2890        return f"REFERENCES {this}{expressions}{options}"

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

    2892    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    2893        return self.func(self.sql(expression, "this"), *expression.expressions)

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

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

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

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

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

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

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

    2908    def alias_sql(self, expression: exp.Alias) -> str:
    2909        alias = self.sql(expression, "alias")
    2910        alias = f" AS {alias}" if alias else ""
    2911        return f"{self.sql(expression, 'this')}{alias}"

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

    2913    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    2914        alias = expression.args["alias"]
    2915
    2916        identifier_alias = isinstance(alias, exp.Identifier)
    2917        literal_alias = isinstance(alias, exp.Literal)
    2918
    2919        if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2920            alias.replace(exp.Literal.string(alias.output_name))
    2921        elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2922            alias.replace(exp.to_identifier(alias.output_name))
    2923
    2924        return self.alias_sql(expression)

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

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

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

    2929    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    2930        this = self.sql(expression, "this")
    2931        index = self.sql(expression, "expression")
    2932        return f"{this} AT {index}"

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

    2934    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    2935        this = self.sql(expression, "this")
    2936        zone = self.sql(expression, "zone")
    2937        return f"{this} AT TIME ZONE {zone}"

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

    2939    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    2940        this = self.sql(expression, "this")
    2941        zone = self.sql(expression, "zone")
    2942        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"

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

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

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

    2947    def and_sql(
    2948        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
    2949    ) -> str:
    2950        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

    2952    def or_sql(
    2953        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
    2954    ) -> str:
    2955        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

    2957    def xor_sql(
    2958        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
    2959    ) -> str:
    2960        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

    2962    def connector_sql(
    2963        self,
    2964        expression: exp.Connector,
    2965        op: str,
    2966        stack: t.Optional[t.List[str | exp.Expression]] = None,
    2967    ) -> str:
    2968        if stack is not None:
    2969            if expression.expressions:
    2970                stack.append(self.expressions(expression, sep=f" {op} "))
    2971            else:
    2972                stack.append(expression.right)
    2973                if expression.comments and self.comments:
    2974                    for comment in expression.comments:
    2975                        if comment:
    2976                            op += f" /*{self.pad_comment(comment)}*/"
    2977                stack.extend((op, expression.left))
    2978            return op
    2979
    2980        stack = [expression]
    2981        sqls: t.List[str] = []
    2982        ops = set()
    2983
    2984        while stack:
    2985            node = stack.pop()
    2986            if isinstance(node, exp.Connector):
    2987                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
    2988            else:
    2989                sql = self.sql(node)
    2990                if sqls and sqls[-1] in ops:
    2991                    sqls[-1] += f" {sql}"
    2992                else:
    2993                    sqls.append(sql)
    2994
    2995        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
    2996        return sep.join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

    3016    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    3017        format_sql = self.sql(expression, "format")
    3018        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    3019        to_sql = self.sql(expression, "to")
    3020        to_sql = f" {to_sql}" if to_sql else ""
    3021        action = self.sql(expression, "action")
    3022        action = f" {action}" if action else ""
    3023        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

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

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

    3029    def collate_sql(self, expression: exp.Collate) -> str:
    3030        if self.COLLATE_IS_FUNC:
    3031            return self.function_fallback_sql(expression)
    3032        return self.binary(expression, "COLLATE")

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

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

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

    3037    def comment_sql(self, expression: exp.Comment) -> str:
    3038        this = self.sql(expression, "this")
    3039        kind = expression.args["kind"]
    3040        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    3041        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    3042        expression_sql = self.sql(expression, "expression")
    3043        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"

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

    3045    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    3046        this = self.sql(expression, "this")
    3047        delete = " DELETE" if expression.args.get("delete") else ""
    3048        recompress = self.sql(expression, "recompress")
    3049        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    3050        to_disk = self.sql(expression, "to_disk")
    3051        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    3052        to_volume = self.sql(expression, "to_volume")
    3053        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    3054        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    3056    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    3057        where = self.sql(expression, "where")
    3058        group = self.sql(expression, "group")
    3059        aggregates = self.expressions(expression, key="aggregates")
    3060        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    3061
    3062        if not (where or group or aggregates) and len(expression.expressions) == 1:
    3063            return f"TTL {self.expressions(expression, flat=True)}"
    3064
    3065        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    3070    def commit_sql(self, expression: exp.Commit) -> str:
    3071        chain = expression.args.get("chain")
    3072        if chain is not None:
    3073            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    3074
    3075        return f"COMMIT{chain or ''}"

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

    3077    def rollback_sql(self, expression: exp.Rollback) -> str:
    3078        savepoint = expression.args.get("savepoint")
    3079        savepoint = f" TO {savepoint}" if savepoint else ""
    3080        return f"ROLLBACK{savepoint}"

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

    3082    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    3083        this = self.sql(expression, "this")
    3084
    3085        dtype = self.sql(expression, "dtype")
    3086        if dtype:
    3087            collate = self.sql(expression, "collate")
    3088            collate = f" COLLATE {collate}" if collate else ""
    3089            using = self.sql(expression, "using")
    3090            using = f" USING {using}" if using else ""
    3091            return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}"
    3092
    3093        default = self.sql(expression, "default")
    3094        if default:
    3095            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    3096
    3097        comment = self.sql(expression, "comment")
    3098        if comment:
    3099            return f"ALTER COLUMN {this} COMMENT {comment}"
    3100
    3101        allow_null = expression.args.get("allow_null")
    3102        drop = expression.args.get("drop")
    3103
    3104        if not drop and not allow_null:
    3105            self.unsupported("Unsupported ALTER COLUMN syntax")
    3106
    3107        if allow_null is not None:
    3108            keyword = "DROP" if drop else "SET"
    3109            return f"ALTER COLUMN {this} {keyword} NOT NULL"
    3110
    3111        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    3113    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
    3114        this = self.sql(expression, "this")
    3115        if not isinstance(expression.this, exp.Var):
    3116            this = f"KEY DISTKEY {this}"
    3117        return f"ALTER DISTSTYLE {this}"

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

    3119    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
    3120        compound = " COMPOUND" if expression.args.get("compound") else ""
    3121        this = self.sql(expression, "this")
    3122        expressions = self.expressions(expression, flat=True)
    3123        expressions = f"({expressions})" if expressions else ""
    3124        return f"ALTER{compound} SORTKEY {this or expressions}"

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

    3126    def renametable_sql(self, expression: exp.RenameTable) -> str:
    3127        if not self.RENAME_TABLE_WITH_DB:
    3128            # Remove db from tables
    3129            expression = expression.transform(
    3130                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    3131            ).assert_is(exp.RenameTable)
    3132        this = self.sql(expression, "this")
    3133        return f"RENAME TO {this}"

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

    3135    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    3136        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3137        old_column = self.sql(expression, "this")
    3138        new_column = self.sql(expression, "to")
    3139        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"

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

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

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

    3145    def alter_sql(self, expression: exp.Alter) -> str:
    3146        actions = expression.args["actions"]
    3147
    3148        if isinstance(actions[0], exp.ColumnDef):
    3149            actions = self.add_column_sql(expression)
    3150        elif isinstance(actions[0], exp.Schema):
    3151            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    3152        elif isinstance(actions[0], exp.Delete):
    3153            actions = self.expressions(expression, key="actions", flat=True)
    3154        elif isinstance(actions[0], exp.Query):
    3155            actions = "AS " + self.expressions(expression, key="actions")
    3156        else:
    3157            actions = self.expressions(expression, key="actions", flat=True)
    3158
    3159        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3160        on_cluster = self.sql(expression, "cluster")
    3161        on_cluster = f" {on_cluster}" if on_cluster else ""
    3162        only = " ONLY" if expression.args.get("only") else ""
    3163        options = self.expressions(expression, key="options")
    3164        options = f", {options}" if options else ""
    3165        kind = self.sql(expression, "kind")
    3166        return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{options}"

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

    3168    def add_column_sql(self, expression: exp.Alter) -> str:
    3169        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    3170            return self.expressions(
    3171                expression,
    3172                key="actions",
    3173                prefix="ADD COLUMN ",
    3174                skip_first=True,
    3175            )
    3176        return f"ADD {self.expressions(expression, key='actions', flat=True)}"

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

    3178    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    3179        expressions = self.expressions(expression)
    3180        exists = " IF EXISTS " if expression.args.get("exists") else " "
    3181        return f"DROP{exists}{expressions}"

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

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

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

    3186    def distinct_sql(self, expression: exp.Distinct) -> str:
    3187        this = self.expressions(expression, flat=True)
    3188
    3189        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    3190            case = exp.case()
    3191            for arg in expression.expressions:
    3192                case = case.when(arg.is_(exp.null()), exp.null())
    3193            this = self.sql(case.else_(f"({this})"))
    3194
    3195        this = f" {this}" if this else ""
    3196
    3197        on = self.sql(expression, "on")
    3198        on = f" ON {on}" if on else ""
    3199        return f"DISTINCT{this}{on}"

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

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

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

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

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

    3207    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    3208        this_sql = self.sql(expression, "this")
    3209        expression_sql = self.sql(expression, "expression")
    3210        kind = "MAX" if expression.args.get("max") else "MIN"
    3211        return f"{this_sql} HAVING {kind} {expression_sql}"

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

    3213    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    3214        return self.sql(
    3215            exp.Cast(
    3216                this=exp.Div(this=expression.this, expression=expression.expression),
    3217                to=exp.DataType(this=exp.DataType.Type.INT),
    3218            )
    3219        )

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

    3221    def dpipe_sql(self, expression: exp.DPipe) -> str:
    3222        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    3223            return self.func(
    3224                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
    3225            )
    3226        return self.binary(expression, "||")

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

    3228    def div_sql(self, expression: exp.Div) -> str:
    3229        l, r = expression.left, expression.right
    3230
    3231        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    3232            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    3233
    3234        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    3235            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
    3236                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    3237
    3238        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    3239            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    3240                return self.sql(
    3241                    exp.cast(
    3242                        l / r,
    3243                        to=exp.DataType.Type.BIGINT,
    3244                    )
    3245                )
    3246
    3247        return self.binary(expression, "/")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3282    def is_sql(self, expression: exp.Is) -> str:
    3283        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3284            return self.sql(
    3285                expression.this if expression.expression.this else exp.not_(expression.this)
    3286            )
    3287        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3328    def try_sql(self, expression: exp.Try) -> str:
    3329        if not self.TRY_SUPPORTED:
    3330            self.unsupported("Unsupported TRY function")
    3331            return self.sql(expression, "this")
    3332
    3333        return self.func("TRY", expression.this)

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

    3335    def log_sql(self, expression: exp.Log) -> str:
    3336        this = expression.this
    3337        expr = expression.expression
    3338
    3339        if self.dialect.LOG_BASE_FIRST is False:
    3340            this, expr = expr, this
    3341        elif self.dialect.LOG_BASE_FIRST is None and expr:
    3342            if this.name in ("2", "10"):
    3343                return self.func(f"LOG{this.name}", expr)
    3344
    3345            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
    3346
    3347        return self.func("LOG", this, expr)

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

    3349    def use_sql(self, expression: exp.Use) -> str:
    3350        kind = self.sql(expression, "kind")
    3351        kind = f" {kind}" if kind else ""
    3352        this = self.sql(expression, "this")
    3353        this = f" {this}" if this else ""
    3354        return f"USE{kind}{this}"

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

    3356    def binary(self, expression: exp.Binary, op: str) -> str:
    3357        sqls: t.List[str] = []
    3358        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    3359        binary_type = type(expression)
    3360
    3361        while stack:
    3362            node = stack.pop()
    3363
    3364            if type(node) is binary_type:
    3365                op_func = node.args.get("operator")
    3366                if op_func:
    3367                    op = f"OPERATOR({self.sql(op_func)})"
    3368
    3369                stack.append(node.right)
    3370                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
    3371                stack.append(node.left)
    3372            else:
    3373                sqls.append(self.sql(node))
    3374
    3375        return "".join(sqls)

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

    3377    def function_fallback_sql(self, expression: exp.Func) -> str:
    3378        args = []
    3379
    3380        for key in expression.arg_types:
    3381            arg_value = expression.args.get(key)
    3382
    3383            if isinstance(arg_value, list):
    3384                for value in arg_value:
    3385                    args.append(value)
    3386            elif arg_value is not None:
    3387                args.append(arg_value)
    3388
    3389        if self.normalize_functions:
    3390            name = expression.sql_name()
    3391        else:
    3392            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3393
    3394        return self.func(name, *args)

def func( self, name: str, *args: Union[str, sqlglot.expressions.Expression, NoneType], prefix: str = '(', suffix: str = ')') -> str: View Source

    3396    def func(
    3397        self,
    3398        name: str,
    3399        *args: t.Optional[exp.Expression | str],
    3400        prefix: str = "(",
    3401        suffix: str = ")",
    3402    ) -> str:
    3403        return f"{self.normalize_func(name)}{prefix}{self.format_args(*args)}{suffix}"

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

    3405    def format_args(self, *args: t.Optional[str | exp.Expression]) -> str:
    3406        arg_sqls = tuple(
    3407            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
    3408        )
    3409        if self.pretty and self.too_wide(arg_sqls):
    3410            return self.indent("\n" + ",\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True)
    3411        return ", ".join(arg_sqls)

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

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

    3416    def format_time(
    3417        self,
    3418        expression: exp.Expression,
    3419        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
    3420        inverse_time_trie: t.Optional[t.Dict] = None,
    3421    ) -> t.Optional[str]:
    3422        return format_time(
    3423            self.sql(expression, "format"),
    3424            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
    3425            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
    3426        )

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

    3428    def expressions(
    3429        self,
    3430        expression: t.Optional[exp.Expression] = None,
    3431        key: t.Optional[str] = None,
    3432        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    3433        flat: bool = False,
    3434        indent: bool = True,
    3435        skip_first: bool = False,
    3436        skip_last: bool = False,
    3437        sep: str = ", ",
    3438        prefix: str = "",
    3439        dynamic: bool = False,
    3440        new_line: bool = False,
    3441    ) -> str:
    3442        expressions = expression.args.get(key or "expressions") if expression else sqls
    3443
    3444        if not expressions:
    3445            return ""
    3446
    3447        if flat:
    3448            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    3449
    3450        num_sqls = len(expressions)
    3451        result_sqls = []
    3452
    3453        for i, e in enumerate(expressions):
    3454            sql = self.sql(e, comment=False)
    3455            if not sql:
    3456                continue
    3457
    3458            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    3459
    3460            if self.pretty:
    3461                if self.leading_comma:
    3462                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
    3463                else:
    3464                    result_sqls.append(
    3465                        f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}"
    3466                    )
    3467            else:
    3468                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    3469
    3470        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
    3471            if new_line:
    3472                result_sqls.insert(0, "")
    3473                result_sqls.append("")
    3474            result_sql = "\n".join(s.rstrip() for s in result_sqls)
    3475        else:
    3476            result_sql = "".join(result_sqls)
    3477        return (
    3478            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
    3479            if indent
    3480            else result_sql
    3481        )

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

    3483    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3484        flat = flat or isinstance(expression.parent, exp.Properties)
    3485        expressions_sql = self.expressions(expression, flat=flat)
    3486        if flat:
    3487            return f"{op} {expressions_sql}"
    3488        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    3490    def naked_property(self, expression: exp.Property) -> str:
    3491        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3492        if not property_name:
    3493            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3494        return f"{property_name} {self.sql(expression, 'this')}"

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

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

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

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

    3502    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3503        this = self.sql(expression, "this")
    3504        expressions = self.no_identify(self.expressions, expression)
    3505        expressions = (
    3506            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3507        )
    3508        return f"{this}{expressions}"

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

    3510    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3511        this = self.sql(expression, "this")
    3512        expressions = self.expressions(expression, flat=True)
    3513        return f"{this}({expressions})"

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

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

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

    3518    def when_sql(self, expression: exp.When) -> str:
    3519        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3520        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3521        condition = self.sql(expression, "condition")
    3522        condition = f" AND {condition}" if condition else ""
    3523
    3524        then_expression = expression.args.get("then")
    3525        if isinstance(then_expression, exp.Insert):
    3526            this = self.sql(then_expression, "this")
    3527            this = f"INSERT {this}" if this else "INSERT"
    3528            then = self.sql(then_expression, "expression")
    3529            then = f"{this} VALUES {then}" if then else this
    3530        elif isinstance(then_expression, exp.Update):
    3531            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3532                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3533            else:
    3534                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    3535        else:
    3536            then = self.sql(then_expression)
    3537        return f"WHEN {matched}{source}{condition} THEN {then}"

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

    3539    def merge_sql(self, expression: exp.Merge) -> str:
    3540        table = expression.this
    3541        table_alias = ""
    3542
    3543        hints = table.args.get("hints")
    3544        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3545            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3546            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3547
    3548        this = self.sql(table)
    3549        using = f"USING {self.sql(expression, 'using')}"
    3550        on = f"ON {self.sql(expression, 'on')}"
    3551        expressions = self.expressions(expression, sep=" ", indent=False)
    3552        sep = self.sep()
    3553
    3554        return self.prepend_ctes(
    3555            expression, f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{expressions}"
    3556        )

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

    3558    def tochar_sql(self, expression: exp.ToChar) -> str:
    3559        if expression.args.get("format"):
    3560            self.unsupported("Format argument unsupported for TO_CHAR/TO_VARCHAR function")
    3561
    3562        return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT))

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

    3564    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3565        if not self.SUPPORTS_TO_NUMBER:
    3566            self.unsupported("Unsupported TO_NUMBER function")
    3567            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3568
    3569        fmt = expression.args.get("format")
    3570        if not fmt:
    3571            self.unsupported("Conversion format is required for TO_NUMBER")
    3572            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3573
    3574        return self.func("TO_NUMBER", expression.this, fmt)

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

    3576    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3577        this = self.sql(expression, "this")
    3578        kind = self.sql(expression, "kind")
    3579        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3580        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3581        return f"{this}({kind}{args})"

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

    3583    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3584        this = self.sql(expression, "this")
    3585        max = self.sql(expression, "max")
    3586        min = self.sql(expression, "min")
    3587        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

    3595    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3596        expressions = self.expressions(expression, key="expressions", flat=True)
    3597        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3598        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3599        buckets = self.sql(expression, "buckets")
    3600        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    3602    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3603        this = self.sql(expression, "this")
    3604        having = self.sql(expression, "having")
    3605
    3606        if having:
    3607            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3608
    3609        return self.func("ANY_VALUE", this)

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

    3611    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3612        transform = self.func("TRANSFORM", *expression.expressions)
    3613        row_format_before = self.sql(expression, "row_format_before")
    3614        row_format_before = f" {row_format_before}" if row_format_before else ""
    3615        record_writer = self.sql(expression, "record_writer")
    3616        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3617        using = f" USING {self.sql(expression, 'command_script')}"
    3618        schema = self.sql(expression, "schema")
    3619        schema = f" AS {schema}" if schema else ""
    3620        row_format_after = self.sql(expression, "row_format_after")
    3621        row_format_after = f" {row_format_after}" if row_format_after else ""
    3622        record_reader = self.sql(expression, "record_reader")
    3623        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3624        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

    3626    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3627        key_block_size = self.sql(expression, "key_block_size")
    3628        if key_block_size:
    3629            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3630
    3631        using = self.sql(expression, "using")
    3632        if using:
    3633            return f"USING {using}"
    3634
    3635        parser = self.sql(expression, "parser")
    3636        if parser:
    3637            return f"WITH PARSER {parser}"
    3638
    3639        comment = self.sql(expression, "comment")
    3640        if comment:
    3641            return f"COMMENT {comment}"
    3642
    3643        visible = expression.args.get("visible")
    3644        if visible is not None:
    3645            return "VISIBLE" if visible else "INVISIBLE"
    3646
    3647        engine_attr = self.sql(expression, "engine_attr")
    3648        if engine_attr:
    3649            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3650
    3651        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3652        if secondary_engine_attr:
    3653            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3654
    3655        self.unsupported("Unsupported index constraint option.")
    3656        return ""

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

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

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

    3662    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3663        kind = self.sql(expression, "kind")
    3664        kind = f"{kind} INDEX" if kind else "INDEX"
    3665        this = self.sql(expression, "this")
    3666        this = f" {this}" if this else ""
    3667        index_type = self.sql(expression, "index_type")
    3668        index_type = f" USING {index_type}" if index_type else ""
    3669        expressions = self.expressions(expression, flat=True)
    3670        expressions = f" ({expressions})" if expressions else ""
    3671        options = self.expressions(expression, key="options", sep=" ")
    3672        options = f" {options}" if options else ""
    3673        return f"{kind}{this}{index_type}{expressions}{options}"

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

    3675    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3676        if self.NVL2_SUPPORTED:
    3677            return self.function_fallback_sql(expression)
    3678
    3679        case = exp.Case().when(
    3680            expression.this.is_(exp.null()).not_(copy=False),
    3681            expression.args["true"],
    3682            copy=False,
    3683        )
    3684        else_cond = expression.args.get("false")
    3685        if else_cond:
    3686            case.else_(else_cond, copy=False)
    3687
    3688        return self.sql(case)

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

    3690    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3691        this = self.sql(expression, "this")
    3692        expr = self.sql(expression, "expression")
    3693        iterator = self.sql(expression, "iterator")
    3694        condition = self.sql(expression, "condition")
    3695        condition = f" IF {condition}" if condition else ""
    3696        return f"{this} FOR {expr} IN {iterator}{condition}"

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

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

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

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

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

    3704    def predict_sql(self, expression: exp.Predict) -> str:
    3705        model = self.sql(expression, "this")
    3706        model = f"MODEL {model}"
    3707        table = self.sql(expression, "expression")
    3708        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    3709        parameters = self.sql(expression, "params_struct")
    3710        return self.func("PREDICT", model, table, parameters or None)

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

    3712    def forin_sql(self, expression: exp.ForIn) -> str:
    3713        this = self.sql(expression, "this")
    3714        expression_sql = self.sql(expression, "expression")
    3715        return f"FOR {this} DO {expression_sql}"

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

    3717    def refresh_sql(self, expression: exp.Refresh) -> str:
    3718        this = self.sql(expression, "this")
    3719        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    3720        return f"REFRESH {table}{this}"

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

    3722    def toarray_sql(self, expression: exp.ToArray) -> str:
    3723        arg = expression.this
    3724        if not arg.type:
    3725            from sqlglot.optimizer.annotate_types import annotate_types
    3726
    3727            arg = annotate_types(arg)
    3728
    3729        if arg.is_type(exp.DataType.Type.ARRAY):
    3730            return self.sql(arg)
    3731
    3732        cond_for_null = arg.is_(exp.null())
    3733        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

    3735    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    3736        this = expression.this
    3737        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    3738            return self.sql(this)
    3739
    3740        return self.sql(exp.cast(this, exp.DataType.Type.TIME))

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

    3742    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
    3743        this = expression.this
    3744        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
    3745            return self.sql(this)
    3746
    3747        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP))

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

    3749    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    3750        this = expression.this
    3751        time_format = self.format_time(expression)
    3752
    3753        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    3754            return self.sql(
    3755                exp.cast(
    3756                    exp.StrToTime(this=this, format=expression.args["format"]),
    3757                    exp.DataType.Type.DATE,
    3758                )
    3759            )
    3760
    3761        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    3762            return self.sql(this)
    3763
    3764        return self.sql(exp.cast(this, exp.DataType.Type.DATE))

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

    3766    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    3767        return self.sql(
    3768            exp.func(
    3769                "DATEDIFF",
    3770                expression.this,
    3771                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
    3772                "day",
    3773            )
    3774        )

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

    3776    def lastday_sql(self, expression: exp.LastDay) -> str:
    3777        if self.LAST_DAY_SUPPORTS_DATE_PART:
    3778            return self.function_fallback_sql(expression)
    3779
    3780        unit = expression.text("unit")
    3781        if unit and unit != "MONTH":
    3782            self.unsupported("Date parts are not supported in LAST_DAY.")
    3783
    3784        return self.func("LAST_DAY", expression.this)

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

    3786    def dateadd_sql(self, expression: exp.DateAdd) -> str:
    3787        from sqlglot.dialects.dialect import unit_to_str
    3788
    3789        return self.func(
    3790            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
    3791        )

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

    3793    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    3794        if self.CAN_IMPLEMENT_ARRAY_ANY:
    3795            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    3796            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    3797            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    3798            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    3799
    3800        from sqlglot.dialects import Dialect
    3801
    3802        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    3803        if self.dialect.__class__ != Dialect:
    3804            self.unsupported("ARRAY_ANY is unsupported")
    3805
    3806        return self.function_fallback_sql(expression)

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

    3808    def struct_sql(self, expression: exp.Struct) -> str:
    3809        expression.set(
    3810            "expressions",
    3811            [
    3812                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    3813                if isinstance(e, exp.PropertyEQ)
    3814                else e
    3815                for e in expression.expressions
    3816            ],
    3817        )
    3818
    3819        return self.function_fallback_sql(expression)

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

    3821    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    3822        low = self.sql(expression, "this")
    3823        high = self.sql(expression, "expression")
    3824
    3825        return f"{low} TO {high}"

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

    3827    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    3828        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    3829        tables = f" {self.expressions(expression)}"
    3830
    3831        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3832
    3833        on_cluster = self.sql(expression, "cluster")
    3834        on_cluster = f" {on_cluster}" if on_cluster else ""
    3835
    3836        identity = self.sql(expression, "identity")
    3837        identity = f" {identity} IDENTITY" if identity else ""
    3838
    3839        option = self.sql(expression, "option")
    3840        option = f" {option}" if option else ""
    3841
    3842        partition = self.sql(expression, "partition")
    3843        partition = f" {partition}" if partition else ""
    3844
    3845        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"

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

    3849    def convert_sql(self, expression: exp.Convert) -> str:
    3850        to = expression.this
    3851        value = expression.expression
    3852        style = expression.args.get("style")
    3853        safe = expression.args.get("safe")
    3854        strict = expression.args.get("strict")
    3855
    3856        if not to or not value:
    3857            return ""
    3858
    3859        # Retrieve length of datatype and override to default if not specified
    3860        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3861            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    3862
    3863        transformed: t.Optional[exp.Expression] = None
    3864        cast = exp.Cast if strict else exp.TryCast
    3865
    3866        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
    3867        if isinstance(style, exp.Literal) and style.is_int:
    3868            from sqlglot.dialects.tsql import TSQL
    3869
    3870            style_value = style.name
    3871            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
    3872            if not converted_style:
    3873                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
    3874
    3875            fmt = exp.Literal.string(converted_style)
    3876
    3877            if to.this == exp.DataType.Type.DATE:
    3878                transformed = exp.StrToDate(this=value, format=fmt)
    3879            elif to.this == exp.DataType.Type.DATETIME:
    3880                transformed = exp.StrToTime(this=value, format=fmt)
    3881            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3882                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
    3883            elif to.this == exp.DataType.Type.TEXT:
    3884                transformed = exp.TimeToStr(this=value, format=fmt)
    3885
    3886        if not transformed:
    3887            transformed = cast(this=value, to=to, safe=safe)
    3888
    3889        return self.sql(transformed)

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

    3945    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
    3946        option = self.sql(expression, "this")
    3947
    3948        if expression.expressions:
    3949            upper = option.upper()
    3950
    3951            # Snowflake FILE_FORMAT options are separated by whitespace
    3952            sep = " " if upper == "FILE_FORMAT" else ", "
    3953
    3954            # Databricks copy/format options do not set their list of values with EQ
    3955            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
    3956            values = self.expressions(expression, flat=True, sep=sep)
    3957            return f"{option}{op}({values})"
    3958
    3959        value = self.sql(expression, "expression")
    3960
    3961        if not value:
    3962            return option
    3963
    3964        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
    3965
    3966        return f"{option}{op}{value}"

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

    3968    def credentials_sql(self, expression: exp.Credentials) -> str:
    3969        cred_expr = expression.args.get("credentials")
    3970        if isinstance(cred_expr, exp.Literal):
    3971            # Redshift case: CREDENTIALS <string>
    3972            credentials = self.sql(expression, "credentials")
    3973            credentials = f"CREDENTIALS {credentials}" if credentials else ""
    3974        else:
    3975            # Snowflake case: CREDENTIALS = (...)
    3976            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
    3977            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
    3978
    3979        storage = self.sql(expression, "storage")
    3980        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
    3981
    3982        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
    3983        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
    3984
    3985        iam_role = self.sql(expression, "iam_role")
    3986        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
    3987
    3988        region = self.sql(expression, "region")
    3989        region = f" REGION {region}" if region else ""
    3990
    3991        return f"{credentials}{storage}{encryption}{iam_role}{region}"

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

    3993    def copy_sql(self, expression: exp.Copy) -> str:
    3994        this = self.sql(expression, "this")
    3995        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
    3996
    3997        credentials = self.sql(expression, "credentials")
    3998        credentials = self.seg(credentials) if credentials else ""
    3999        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
    4000        files = self.expressions(expression, key="files", flat=True)
    4001
    4002        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
    4003        params = self.expressions(
    4004            expression,
    4005            key="params",
    4006            sep=sep,
    4007            new_line=True,
    4008            skip_last=True,
    4009            skip_first=True,
    4010            indent=self.COPY_PARAMS_ARE_WRAPPED,
    4011        )
    4012
    4013        if params:
    4014            if self.COPY_PARAMS_ARE_WRAPPED:
    4015                params = f" WITH ({params})"
    4016            elif not self.pretty:
    4017                params = f" {params}"
    4018
    4019        return f"COPY{this}{kind} {files}{credentials}{params}"

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

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

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

    4024    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
    4025        on_sql = "ON" if expression.args.get("on") else "OFF"
    4026        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
    4027        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
    4028        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    4029        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
    4030
    4031        if filter_col or retention_period:
    4032            on_sql = self.func("ON", filter_col, retention_period)
    4033
    4034        return f"DATA_DELETION={on_sql}"

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

    4036    def maskingpolicycolumnconstraint_sql(
    4037        self, expression: exp.MaskingPolicyColumnConstraint
    4038    ) -> str:
    4039        this = self.sql(expression, "this")
    4040        expressions = self.expressions(expression, flat=True)
    4041        expressions = f" USING ({expressions})" if expressions else ""
    4042        return f"MASKING POLICY {this}{expressions}"

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

    4044    def gapfill_sql(self, expression: exp.GapFill) -> str:
    4045        this = self.sql(expression, "this")
    4046        this = f"TABLE {this}"
    4047        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

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

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

    4052    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
    4053        this = self.sql(expression, "this")
    4054        expr = expression.expression
    4055
    4056        if isinstance(expr, exp.Func):
    4057            # T-SQL's CLR functions are case sensitive
    4058            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
    4059        else:
    4060            expr = self.sql(expression, "expression")
    4061
    4062        return self.scope_resolution(expr, this)

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

    4064    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
    4065        if self.PARSE_JSON_NAME is None:
    4066            return self.sql(expression.this)
    4067
    4068        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)

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

    4070    def rand_sql(self, expression: exp.Rand) -> str:
    4071        lower = self.sql(expression, "lower")
    4072        upper = self.sql(expression, "upper")
    4073
    4074        if lower and upper:
    4075            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
    4076        return self.func("RAND", expression.this)

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

    4078    def changes_sql(self, expression: exp.Changes) -> str:
    4079        information = self.sql(expression, "information")
    4080        information = f"INFORMATION => {information}"
    4081        at_before = self.sql(expression, "at_before")
    4082        at_before = f"{self.seg('')}{at_before}" if at_before else ""
    4083        end = self.sql(expression, "end")
    4084        end = f"{self.seg('')}{end}" if end else ""
    4085
    4086        return f"CHANGES ({information}){at_before}{end}"

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

    4088    def pad_sql(self, expression: exp.Pad) -> str:
    4089        prefix = "L" if expression.args.get("is_left") else "R"
    4090
    4091        fill_pattern = self.sql(expression, "fill_pattern") or None
    4092        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
    4093            fill_pattern = "' '"
    4094
    4095        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)

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

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

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

    4101    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
    4102        generate_series = exp.GenerateSeries(**expression.args)
    4103
    4104        parent = expression.parent
    4105        if isinstance(parent, (exp.Alias, exp.TableAlias)):
    4106            parent = parent.parent
    4107
    4108        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
    4109            return self.sql(exp.Unnest(expressions=[generate_series]))
    4110
    4111        if isinstance(parent, exp.Select):
    4112            self.unsupported("GenerateSeries projection unnesting is not supported.")
    4113
    4114        return self.sql(generate_series)

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

    4116    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
    4117        exprs = expression.expressions
    4118        if not self.ARRAY_CONCAT_IS_VAR_LEN:
    4119            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
    4120        else:
    4121            rhs = self.expressions(expression)
    4122
    4123        return self.func(name, expression.this, rhs)

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

    4125    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
    4126        if self.SUPPORTS_CONVERT_TIMEZONE:
    4127            return self.function_fallback_sql(expression)
    4128
    4129        source_tz = expression.args.get("source_tz")
    4130        target_tz = expression.args.get("target_tz")
    4131        timestamp = expression.args.get("timestamp")
    4132
    4133        if source_tz and timestamp:
    4134            timestamp = exp.AtTimeZone(
    4135                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
    4136            )
    4137
    4138        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
    4139
    4140        return self.sql(expr)