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

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

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

    545    def __init__(
    546        self,
    547        pretty: t.Optional[bool] = None,
    548        identify: str | bool = False,
    549        normalize: bool = False,
    550        pad: int = 2,
    551        indent: int = 2,
    552        normalize_functions: t.Optional[str | bool] = None,
    553        unsupported_level: ErrorLevel = ErrorLevel.WARN,
    554        max_unsupported: int = 3,
    555        leading_comma: bool = False,
    556        max_text_width: int = 80,
    557        comments: bool = True,
    558        dialect: DialectType = None,
    559    ):
    560        import sqlglot
    561        from sqlglot.dialects import Dialect
    562
    563        self.pretty = pretty if pretty is not None else sqlglot.pretty
    564        self.identify = identify
    565        self.normalize = normalize
    566        self.pad = pad
    567        self._indent = indent
    568        self.unsupported_level = unsupported_level
    569        self.max_unsupported = max_unsupported
    570        self.leading_comma = leading_comma
    571        self.max_text_width = max_text_width
    572        self.comments = comments
    573        self.dialect = Dialect.get_or_raise(dialect)
    574
    575        # This is both a Dialect property and a Generator argument, so we prioritize the latter
    576        self.normalize_functions = (
    577            self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
    578        )
    579
    580        self.unsupported_messages: t.List[str] = []
    581        self._escaped_quote_end: str = (
    582            self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END
    583        )
    584        self._escaped_identifier_end: str = (
    585            self.dialect.tokenizer_class.IDENTIFIER_ESCAPES[0] + self.dialect.IDENTIFIER_END
    586        )

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.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.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DefaultColumnConstraint'>: <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.JSONExtract'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.JSONExtractScalar'>: <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.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PathColumnConstraint'>: <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.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.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Timestamp'>: <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.WithOperator'>: <function Generator.<lambda>>}
NULL_ORDERING_SUPPORTED: Optional[bool] = True
IGNORE_NULLS_IN_FUNC = False
LOCKING_READS_SUPPORTED = False
EXPLICIT_UNION = 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
COLUMN_JOIN_MARKS_SUPPORTED = False
EXTRACT_ALLOWS_QUOTES = True
TZ_TO_WITH_TIME_ZONE = False
NVL2_SUPPORTED = True
SELECT_KINDS: Tuple[str, ...] = ('STRUCT', 'VALUE')
VALUES_AS_TABLE = True
ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True
UNNEST_WITH_ORDINALITY = True
AGGREGATE_FILTER_SUPPORTED = True
SEMI_ANTI_JOIN_WITH_SIDE = True
COMPUTED_COLUMN_WITH_TYPE = True
SUPPORTS_TABLE_COPY = True
TABLESAMPLE_REQUIRES_PARENS = True
TABLESAMPLE_SIZE_IS_ROWS = True
TABLESAMPLE_KEYWORDS = 'TABLESAMPLE'
TABLESAMPLE_WITH_METHOD = True
TABLESAMPLE_SEED_KEYWORD = 'SEED'
COLLATE_IS_FUNC = False
DATA_TYPE_SPECIFIERS_ALLOWED = False
ENSURE_BOOLS = False
CTE_RECURSIVE_KEYWORD_REQUIRED = True
SUPPORTS_SINGLE_ARG_CONCAT = True
LAST_DAY_SUPPORTS_DATE_PART = True
SUPPORTS_TABLE_ALIAS_COLUMNS = True
UNPIVOT_ALIASES_ARE_IDENTIFIERS = True
JSON_KEY_VALUE_PAIR_SEP = ':'
INSERT_OVERWRITE = ' OVERWRITE TABLE'
SUPPORTS_SELECT_INTO = False
SUPPORTS_UNLOGGED_TABLES = False
SUPPORTS_CREATE_TABLE_LIKE = True
LIKE_PROPERTY_INSIDE_SCHEMA = False
MULTI_ARG_DISTINCT = True
JSON_TYPE_REQUIRED_FOR_EXTRACTION = False
JSON_PATH_BRACKETED_KEY_SUPPORTED = True
JSON_PATH_SINGLE_QUOTE_ESCAPE = False
SUPPORTED_JSON_PATH_PARTS = {<class 'sqlglot.expressions.JSONPathRecursive'>, <class 'sqlglot.expressions.JSONPathKey'>, <class 'sqlglot.expressions.JSONPathWildcard'>, <class 'sqlglot.expressions.JSONPathFilter'>, <class 'sqlglot.expressions.JSONPathUnion'>, <class 'sqlglot.expressions.JSONPathSubscript'>, <class 'sqlglot.expressions.JSONPathSelector'>, <class 'sqlglot.expressions.JSONPathSlice'>, <class 'sqlglot.expressions.JSONPathScript'>, <class 'sqlglot.expressions.JSONPathRoot'>}
CAN_IMPLEMENT_ARRAY_ANY = False
SUPPORTS_TO_NUMBER = True
OUTER_UNION_MODIFIERS = True
COPY_PARAMS_ARE_WRAPPED = True
COPY_PARAMS_EQ_REQUIRED = False
COPY_HAS_INTO_KEYWORD = True
TRY_SUPPORTED = True
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'}
STAR_MAPPING = {'except': 'EXCEPT', 'replace': 'REPLACE'}
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>>, 'qualify': <function Generator.<lambda>>, 'sort': <function Generator.<lambda>>, 'windows': <function Generator.<lambda>>}
TOKEN_MAPPING: Dict[sqlglot.tokens.TokenType, str] = {}
STRUCT_DELIMITER = ('<', '>')
PARAMETER_TOKEN = '@'
NAMED_PLACEHOLDER_TOKEN = ':'
PROPERTIES_LOCATION = {<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.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.DistKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistStyleProperty'>: <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.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.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.WithSystemVersioningProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>}
RESERVED_KEYWORDS: Set[str] = set()
WITH_SEPARATED_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] = (<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.Union'>, <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.Union'>)
UNWRAPPED_INTERVAL_VALUES: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Column'>, <class 'sqlglot.expressions.Literal'>, <class 'sqlglot.expressions.Neg'>, <class 'sqlglot.expressions.Paren'>)
PARAMETERIZABLE_TEXT_TYPES = {<Type.NVARCHAR: 'NVARCHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.CHAR: 'CHAR'>, <Type.VARCHAR: 'VARCHAR'>}
EXPRESSIONS_WITHOUT_NESTED_CTES: Set[Type[sqlglot.expressions.Expression]] = set()
SENTINEL_LINE_BREAK = '__SQLGLOT__LB__'
pretty
identify
normalize
pad
unsupported_level
max_unsupported
leading_comma
max_text_width
comments
dialect
normalize_functions
unsupported_messages: List[str]
def generate( self, expression: sqlglot.expressions.Expression, copy: bool = True) -> str: View Source

    588    def generate(self, expression: exp.Expression, copy: bool = True) -> str:
    589        """
    590        Generates the SQL string corresponding to the given syntax tree.
    591
    592        Args:
    593            expression: The syntax tree.
    594            copy: Whether to copy the expression. The generator performs mutations so
    595                it is safer to copy.
    596
    597        Returns:
    598            The SQL string corresponding to `expression`.
    599        """
    600        if copy:
    601            expression = expression.copy()
    602
    603        expression = self.preprocess(expression)
    604
    605        self.unsupported_messages = []
    606        sql = self.sql(expression).strip()
    607
    608        if self.pretty:
    609            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
    610
    611        if self.unsupported_level == ErrorLevel.IGNORE:
    612            return sql
    613
    614        if self.unsupported_level == ErrorLevel.WARN:
    615            for msg in self.unsupported_messages:
    616                logger.warning(msg)
    617        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
    618            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
    619
    620        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

    622    def preprocess(self, expression: exp.Expression) -> exp.Expression:
    623        """Apply generic preprocessing transformations to a given expression."""
    624        if (
    625            not expression.parent
    626            and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES
    627            and any(node.parent is not expression for node in expression.find_all(exp.With))
    628        ):
    629            from sqlglot.transforms import move_ctes_to_top_level
    630
    631            expression = move_ctes_to_top_level(expression)
    632
    633        if self.ENSURE_BOOLS:
    634            from sqlglot.transforms import ensure_bools
    635
    636            expression = ensure_bools(expression)
    637
    638        return expression

Apply generic preprocessing transformations to a given expression.

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

    640    def unsupported(self, message: str) -> None:
    641        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    642            raise UnsupportedError(message)
    643        self.unsupported_messages.append(message)

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

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

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

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

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

    651    def pad_comment(self, comment: str) -> str:
    652        comment = " " + comment if comment[0].strip() else comment
    653        comment = comment + " " if comment[-1].strip() else comment
    654        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

    656    def maybe_comment(
    657        self,
    658        sql: str,
    659        expression: t.Optional[exp.Expression] = None,
    660        comments: t.Optional[t.List[str]] = None,
    661        separated: bool = False,
    662    ) -> str:
    663        comments = (
    664            ((expression and expression.comments) if comments is None else comments)  # type: ignore
    665            if self.comments
    666            else None
    667        )
    668
    669        if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
    670            return sql
    671
    672        comments_sql = " ".join(
    673            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
    674        )
    675
    676        if not comments_sql:
    677            return sql
    678
    679        comments_sql = self._replace_line_breaks(comments_sql)
    680
    681        if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS):
    682            return (
    683                f"{self.sep()}{comments_sql}{sql}"
    684                if not sql or sql[0].isspace()
    685                else f"{comments_sql}{self.sep()}{sql}"
    686            )
    687
    688        return f"{sql} {comments_sql}"

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

    690    def wrap(self, expression: exp.Expression | str) -> str:
    691        this_sql = self.indent(
    692            (
    693                self.sql(expression)
    694                if isinstance(expression, exp.UNWRAPPED_QUERIES)
    695                else self.sql(expression, "this")
    696            ),
    697            level=1,
    698            pad=0,
    699        )
    700        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"

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

    702    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    703        original = self.identify
    704        self.identify = False
    705        result = func(*args, **kwargs)
    706        self.identify = original
    707        return result

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

    709    def normalize_func(self, name: str) -> str:
    710        if self.normalize_functions == "upper" or self.normalize_functions is True:
    711            return name.upper()
    712        if self.normalize_functions == "lower":
    713            return name.lower()
    714        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

    716    def indent(
    717        self,
    718        sql: str,
    719        level: int = 0,
    720        pad: t.Optional[int] = None,
    721        skip_first: bool = False,
    722        skip_last: bool = False,
    723    ) -> str:
    724        if not self.pretty:
    725            return sql
    726
    727        pad = self.pad if pad is None else pad
    728        lines = sql.split("\n")
    729
    730        return "\n".join(
    731            (
    732                line
    733                if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
    734                else f"{' ' * (level * self._indent + pad)}{line}"
    735            )
    736            for i, line in enumerate(lines)
    737        )

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

    739    def sql(
    740        self,
    741        expression: t.Optional[str | exp.Expression],
    742        key: t.Optional[str] = None,
    743        comment: bool = True,
    744    ) -> str:
    745        if not expression:
    746            return ""
    747
    748        if isinstance(expression, str):
    749            return expression
    750
    751        if key:
    752            value = expression.args.get(key)
    753            if value:
    754                return self.sql(value)
    755            return ""
    756
    757        transform = self.TRANSFORMS.get(expression.__class__)
    758
    759        if callable(transform):
    760            sql = transform(self, expression)
    761        elif isinstance(expression, exp.Expression):
    762            exp_handler_name = f"{expression.key}_sql"
    763
    764            if hasattr(self, exp_handler_name):
    765                sql = getattr(self, exp_handler_name)(expression)
    766            elif isinstance(expression, exp.Func):
    767                sql = self.function_fallback_sql(expression)
    768            elif isinstance(expression, exp.Property):
    769                sql = self.property_sql(expression)
    770            else:
    771                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
    772        else:
    773            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
    774
    775        return self.maybe_comment(sql, expression) if self.comments and comment else sql

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

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

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

    782    def cache_sql(self, expression: exp.Cache) -> str:
    783        lazy = " LAZY" if expression.args.get("lazy") else ""
    784        table = self.sql(expression, "this")
    785        options = expression.args.get("options")
    786        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
    787        sql = self.sql(expression, "expression")
    788        sql = f" AS{self.sep()}{sql}" if sql else ""
    789        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
    790        return self.prepend_ctes(expression, sql)

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

    792    def characterset_sql(self, expression: exp.CharacterSet) -> str:
    793        if isinstance(expression.parent, exp.Cast):
    794            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
    795        default = "DEFAULT " if expression.args.get("default") else ""
    796        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"

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

    798    def column_parts(self, expression: exp.Column) -> str:
    799        return ".".join(
    800            self.sql(part)
    801            for part in (
    802                expression.args.get("catalog"),
    803                expression.args.get("db"),
    804                expression.args.get("table"),
    805                expression.args.get("this"),
    806            )
    807            if part
    808        )

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

    810    def column_sql(self, expression: exp.Column) -> str:
    811        join_mark = " (+)" if expression.args.get("join_mark") else ""
    812
    813        if join_mark and not self.COLUMN_JOIN_MARKS_SUPPORTED:
    814            join_mark = ""
    815            self.unsupported("Outer join syntax using the (+) operator is not supported.")
    816
    817        return f"{self.column_parts(expression)}{join_mark}"

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

    819    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    820        this = self.sql(expression, "this")
    821        this = f" {this}" if this else ""
    822        position = self.sql(expression, "position")
    823        return f"{position}{this}"

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

    825    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
    826        column = self.sql(expression, "this")
    827        kind = self.sql(expression, "kind")
    828        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
    829        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
    830        kind = f"{sep}{kind}" if kind else ""
    831        constraints = f" {constraints}" if constraints else ""
    832        position = self.sql(expression, "position")
    833        position = f" {position}" if position else ""
    834
    835        if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:
    836            kind = ""
    837
    838        return f"{exists}{column}{kind}{constraints}{position}"

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

    840    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    841        this = self.sql(expression, "this")
    842        kind_sql = self.sql(expression, "kind").strip()
    843        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

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

    845    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
    846        this = self.sql(expression, "this")
    847        if expression.args.get("not_null"):
    848            persisted = " PERSISTED NOT NULL"
    849        elif expression.args.get("persisted"):
    850            persisted = " PERSISTED"
    851        else:
    852            persisted = ""
    853        return f"AS {this}{persisted}"

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

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

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

    858    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
    859        if isinstance(expression.this, list):
    860            this = self.wrap(self.expressions(expression, key="this", flat=True))
    861        else:
    862            this = self.sql(expression, "this")
    863
    864        return f"COMPRESS {this}"

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

    866    def generatedasidentitycolumnconstraint_sql(
    867        self, expression: exp.GeneratedAsIdentityColumnConstraint
    868    ) -> str:
    869        this = ""
    870        if expression.this is not None:
    871            on_null = " ON NULL" if expression.args.get("on_null") else ""
    872            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
    873
    874        start = expression.args.get("start")
    875        start = f"START WITH {start}" if start else ""
    876        increment = expression.args.get("increment")
    877        increment = f" INCREMENT BY {increment}" if increment else ""
    878        minvalue = expression.args.get("minvalue")
    879        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    880        maxvalue = expression.args.get("maxvalue")
    881        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    882        cycle = expression.args.get("cycle")
    883        cycle_sql = ""
    884
    885        if cycle is not None:
    886            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
    887            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
    888
    889        sequence_opts = ""
    890        if start or increment or cycle_sql:
    891            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
    892            sequence_opts = f" ({sequence_opts.strip()})"
    893
    894        expr = self.sql(expression, "expression")
    895        expr = f"({expr})" if expr else "IDENTITY"
    896
    897        return f"GENERATED{this} AS {expr}{sequence_opts}"

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

    899    def generatedasrowcolumnconstraint_sql(
    900        self, expression: exp.GeneratedAsRowColumnConstraint
    901    ) -> str:
    902        start = "START" if expression.args.get("start") else "END"
    903        hidden = " HIDDEN" if expression.args.get("hidden") else ""
    904        return f"GENERATED ALWAYS AS ROW {start}{hidden}"

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

    906    def periodforsystemtimeconstraint_sql(
    907        self, expression: exp.PeriodForSystemTimeConstraint
    908    ) -> str:
    909        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

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

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

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

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

    917    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    918        desc = expression.args.get("desc")
    919        if desc is not None:
    920            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    921        return "PRIMARY KEY"

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

    923    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    924        this = self.sql(expression, "this")
    925        this = f" {this}" if this else ""
    926        index_type = expression.args.get("index_type")
    927        index_type = f" USING {index_type}" if index_type else ""
    928        on_conflict = self.sql(expression, "on_conflict")
    929        on_conflict = f" {on_conflict}" if on_conflict else ""
    930        return f"UNIQUE{this}{index_type}{on_conflict}"

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

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

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

     935    def create_sql(self, expression: exp.Create) -> str:
     936        kind = self.sql(expression, "kind")
     937        properties = expression.args.get("properties")
     938        properties_locs = self.locate_properties(properties) if properties else defaultdict()
     939
     940        this = self.createable_sql(expression, properties_locs)
     941
     942        properties_sql = ""
     943        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
     944            exp.Properties.Location.POST_WITH
     945        ):
     946            properties_sql = self.sql(
     947                exp.Properties(
     948                    expressions=[
     949                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
     950                        *properties_locs[exp.Properties.Location.POST_WITH],
     951                    ]
     952                )
     953            )
     954
     955        begin = " BEGIN" if expression.args.get("begin") else ""
     956        end = " END" if expression.args.get("end") else ""
     957
     958        expression_sql = self.sql(expression, "expression")
     959        if expression_sql:
     960            expression_sql = f"{begin}{self.sep()}{expression_sql}{end}"
     961
     962            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
     963                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
     964                    postalias_props_sql = self.properties(
     965                        exp.Properties(
     966                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
     967                        ),
     968                        wrapped=False,
     969                    )
     970                    expression_sql = f" AS {postalias_props_sql}{expression_sql}"
     971                else:
     972                    expression_sql = f" AS{expression_sql}"
     973
     974        postindex_props_sql = ""
     975        if properties_locs.get(exp.Properties.Location.POST_INDEX):
     976            postindex_props_sql = self.properties(
     977                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
     978                wrapped=False,
     979                prefix=" ",
     980            )
     981
     982        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
     983        indexes = f" {indexes}" if indexes else ""
     984        index_sql = indexes + postindex_props_sql
     985
     986        replace = " OR REPLACE" if expression.args.get("replace") else ""
     987        unique = " UNIQUE" if expression.args.get("unique") else ""
     988
     989        postcreate_props_sql = ""
     990        if properties_locs.get(exp.Properties.Location.POST_CREATE):
     991            postcreate_props_sql = self.properties(
     992                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
     993                sep=" ",
     994                prefix=" ",
     995                wrapped=False,
     996            )
     997
     998        modifiers = "".join((replace, unique, postcreate_props_sql))
     999
    1000        postexpression_props_sql = ""
    1001        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
    1002            postexpression_props_sql = self.properties(
    1003                exp.Properties(
    1004                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
    1005                ),
    1006                sep=" ",
    1007                prefix=" ",
    1008                wrapped=False,
    1009            )
    1010
    1011        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    1012        no_schema_binding = (
    1013            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
    1014        )
    1015
    1016        clone = self.sql(expression, "clone")
    1017        clone = f" {clone}" if clone else ""
    1018
    1019        expression_sql = f"CREATE{modifiers} {kind}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
    1020        return self.prepend_ctes(expression, expression_sql)

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

    1022    def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str:
    1023        start = self.sql(expression, "start")
    1024        start = f"START WITH {start}" if start else ""
    1025        increment = self.sql(expression, "increment")
    1026        increment = f" INCREMENT BY {increment}" if increment else ""
    1027        minvalue = self.sql(expression, "minvalue")
    1028        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    1029        maxvalue = self.sql(expression, "maxvalue")
    1030        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    1031        owned = self.sql(expression, "owned")
    1032        owned = f" OWNED BY {owned}" if owned else ""
    1033
    1034        cache = expression.args.get("cache")
    1035        if cache is None:
    1036            cache_str = ""
    1037        elif cache is True:
    1038            cache_str = " CACHE"
    1039        else:
    1040            cache_str = f" CACHE {cache}"
    1041
    1042        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1043        options = f" {options}" if options else ""
    1044
    1045        return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()

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

    1047    def clone_sql(self, expression: exp.Clone) -> str:
    1048        this = self.sql(expression, "this")
    1049        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    1050        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
    1051        return f"{shallow}{keyword} {this}"

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

    1053    def describe_sql(self, expression: exp.Describe) -> str:
    1054        style = expression.args.get("style")
    1055        style = f" {style}" if style else ""
    1056        return f"DESCRIBE{style} {self.sql(expression, 'this')}"

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

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

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

    1062    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    1063        with_ = self.sql(expression, "with")
    1064        if with_:
    1065            sql = f"{with_}{self.sep()}{sql}"
    1066        return sql

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

    1068    def with_sql(self, expression: exp.With) -> str:
    1069        sql = self.expressions(expression, flat=True)
    1070        recursive = (
    1071            "RECURSIVE "
    1072            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
    1073            else ""
    1074        )
    1075
    1076        return f"WITH {recursive}{sql}"

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

    1078    def cte_sql(self, expression: exp.CTE) -> str:
    1079        alias = self.sql(expression, "alias")
    1080
    1081        materialized = expression.args.get("materialized")
    1082        if materialized is False:
    1083            materialized = "NOT MATERIALIZED "
    1084        elif materialized:
    1085            materialized = "MATERIALIZED "
    1086
    1087        return f"{alias} AS {materialized or ''}{self.wrap(expression)}"

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

    1089    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    1090        alias = self.sql(expression, "this")
    1091        columns = self.expressions(expression, key="columns", flat=True)
    1092        columns = f"({columns})" if columns else ""
    1093
    1094        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
    1095            columns = ""
    1096            self.unsupported("Named columns are not supported in table alias.")
    1097
    1098        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
    1099            alias = "_t"
    1100
    1101        return f"{alias}{columns}"

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

    1103    def bitstring_sql(self, expression: exp.BitString) -> str:
    1104        this = self.sql(expression, "this")
    1105        if self.dialect.BIT_START:
    1106            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    1107        return f"{int(this, 2)}"

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

    1109    def hexstring_sql(self, expression: exp.HexString) -> str:
    1110        this = self.sql(expression, "this")
    1111        if self.dialect.HEX_START:
    1112            return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
    1113        return f"{int(this, 16)}"

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

    1115    def bytestring_sql(self, expression: exp.ByteString) -> str:
    1116        this = self.sql(expression, "this")
    1117        if self.dialect.BYTE_START:
    1118            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    1119        return this

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

    1121    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
    1122        this = self.sql(expression, "this")
    1123        escape = expression.args.get("escape")
    1124
    1125        if self.dialect.UNICODE_START:
    1126            escape = f" UESCAPE {self.sql(escape)}" if escape else ""
    1127            return f"{self.dialect.UNICODE_START}{this}{self.dialect.UNICODE_END}{escape}"
    1128
    1129        if escape:
    1130            pattern = re.compile(rf"{escape.name}(\d+)")
    1131        else:
    1132            pattern = ESCAPED_UNICODE_RE
    1133
    1134        this = pattern.sub(r"\\u\1", this)
    1135        return f"{self.dialect.QUOTE_START}{this}{self.dialect.QUOTE_END}"

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

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

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

    1141    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    1142        this = self.sql(expression, "this")
    1143        specifier = self.sql(expression, "expression")
    1144        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    1145        return f"{this}{specifier}"

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

    1147    def datatype_sql(self, expression: exp.DataType) -> str:
    1148        type_value = expression.this
    1149
    1150        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
    1151            type_sql = self.sql(expression, "kind")
    1152        else:
    1153            type_sql = (
    1154                self.TYPE_MAPPING.get(type_value, type_value.value)
    1155                if isinstance(type_value, exp.DataType.Type)
    1156                else type_value
    1157            )
    1158
    1159        nested = ""
    1160        interior = self.expressions(expression, flat=True)
    1161        values = ""
    1162
    1163        if interior:
    1164            if expression.args.get("nested"):
    1165                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    1166                if expression.args.get("values") is not None:
    1167                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    1168                    values = self.expressions(expression, key="values", flat=True)
    1169                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    1170            elif type_value == exp.DataType.Type.INTERVAL:
    1171                nested = f" {interior}"
    1172            else:
    1173                nested = f"({interior})"
    1174
    1175        type_sql = f"{type_sql}{nested}{values}"
    1176        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
    1177            exp.DataType.Type.TIMETZ,
    1178            exp.DataType.Type.TIMESTAMPTZ,
    1179        ):
    1180            type_sql = f"{type_sql} WITH TIME ZONE"
    1181
    1182        return type_sql

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

    1184    def directory_sql(self, expression: exp.Directory) -> str:
    1185        local = "LOCAL " if expression.args.get("local") else ""
    1186        row_format = self.sql(expression, "row_format")
    1187        row_format = f" {row_format}" if row_format else ""
    1188        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

    1190    def delete_sql(self, expression: exp.Delete) -> str:
    1191        this = self.sql(expression, "this")
    1192        this = f" FROM {this}" if this else ""
    1193        using = self.sql(expression, "using")
    1194        using = f" USING {using}" if using else ""
    1195        where = self.sql(expression, "where")
    1196        returning = self.sql(expression, "returning")
    1197        limit = self.sql(expression, "limit")
    1198        tables = self.expressions(expression, key="tables")
    1199        tables = f" {tables}" if tables else ""
    1200        if self.RETURNING_END:
    1201            expression_sql = f"{this}{using}{where}{returning}{limit}"
    1202        else:
    1203            expression_sql = f"{returning}{this}{using}{where}{limit}"
    1204        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

    1206    def drop_sql(self, expression: exp.Drop) -> str:
    1207        this = self.sql(expression, "this")
    1208        expressions = self.expressions(expression, flat=True)
    1209        expressions = f" ({expressions})" if expressions else ""
    1210        kind = expression.args["kind"]
    1211        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    1212        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1213        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    1214        cascade = " CASCADE" if expression.args.get("cascade") else ""
    1215        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    1216        purge = " PURGE" if expression.args.get("purge") else ""
    1217        return f"DROP{temporary}{materialized} {kind}{exists_sql}{this}{expressions}{cascade}{constraints}{purge}"

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

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

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

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

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

    1225    def fetch_sql(self, expression: exp.Fetch) -> str:
    1226        direction = expression.args.get("direction")
    1227        direction = f" {direction}" if direction else ""
    1228        count = expression.args.get("count")
    1229        count = f" {count}" if count else ""
    1230        if expression.args.get("percent"):
    1231            count = f"{count} PERCENT"
    1232        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    1233        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"

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

    1235    def filter_sql(self, expression: exp.Filter) -> str:
    1236        if self.AGGREGATE_FILTER_SUPPORTED:
    1237            this = self.sql(expression, "this")
    1238            where = self.sql(expression, "expression").strip()
    1239            return f"{this} FILTER({where})"
    1240
    1241        agg = expression.this
    1242        agg_arg = agg.this
    1243        cond = expression.expression.this
    1244        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1245        return self.sql(agg)

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

    1247    def hint_sql(self, expression: exp.Hint) -> str:
    1248        if not self.QUERY_HINTS:
    1249            self.unsupported("Hints are not supported")
    1250            return ""
    1251
    1252        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

    1254    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
    1255        using = self.sql(expression, "using")
    1256        using = f" USING {using}" if using else ""
    1257        columns = self.expressions(expression, key="columns", flat=True)
    1258        columns = f"({columns})" if columns else ""
    1259        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1260        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1261        where = self.sql(expression, "where")
    1262        include = self.expressions(expression, key="include", flat=True)
    1263        if include:
    1264            include = f" INCLUDE ({include})"
    1265        with_storage = self.expressions(expression, key="with_storage", flat=True)
    1266        with_storage = f" WITH ({with_storage})" if with_storage else ""
    1267        tablespace = self.sql(expression, "tablespace")
    1268        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
    1269
    1270        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}"

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

    1272    def index_sql(self, expression: exp.Index) -> str:
    1273        unique = "UNIQUE " if expression.args.get("unique") else ""
    1274        primary = "PRIMARY " if expression.args.get("primary") else ""
    1275        amp = "AMP " if expression.args.get("amp") else ""
    1276        name = self.sql(expression, "this")
    1277        name = f"{name} " if name else ""
    1278        table = self.sql(expression, "table")
    1279        table = f"{self.INDEX_ON} {table}" if table else ""
    1280
    1281        index = "INDEX " if not table else ""
    1282
    1283        params = self.sql(expression, "params")
    1284        return f"{unique}{primary}{amp}{index}{name}{table}{params}"

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

    1286    def identifier_sql(self, expression: exp.Identifier) -> str:
    1287        text = expression.name
    1288        lower = text.lower()
    1289        text = lower if self.normalize and not expression.quoted else text
    1290        text = text.replace(self.dialect.IDENTIFIER_END, self._escaped_identifier_end)
    1291        if (
    1292            expression.quoted
    1293            or self.dialect.can_identify(text, self.identify)
    1294            or lower in self.RESERVED_KEYWORDS
    1295            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1296        ):
    1297            text = f"{self.dialect.IDENTIFIER_START}{text}{self.dialect.IDENTIFIER_END}"
    1298        return text

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

    1300    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1301        input_format = self.sql(expression, "input_format")
    1302        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1303        output_format = self.sql(expression, "output_format")
    1304        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1305        return self.sep().join((input_format, output_format))

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

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

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

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

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

    1314    def properties_sql(self, expression: exp.Properties) -> str:
    1315        root_properties = []
    1316        with_properties = []
    1317
    1318        for p in expression.expressions:
    1319            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1320            if p_loc == exp.Properties.Location.POST_WITH:
    1321                with_properties.append(p)
    1322            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1323                root_properties.append(p)
    1324
    1325        return self.root_properties(
    1326            exp.Properties(expressions=root_properties)
    1327        ) + self.with_properties(exp.Properties(expressions=with_properties))

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

    1329    def root_properties(self, properties: exp.Properties) -> str:
    1330        if properties.expressions:
    1331            return self.sep() + self.expressions(properties, indent=False, sep=" ")
    1332        return ""

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

    1334    def properties(
    1335        self,
    1336        properties: exp.Properties,
    1337        prefix: str = "",
    1338        sep: str = ", ",
    1339        suffix: str = "",
    1340        wrapped: bool = True,
    1341    ) -> str:
    1342        if properties.expressions:
    1343            expressions = self.expressions(properties, sep=sep, indent=False)
    1344            if expressions:
    1345                expressions = self.wrap(expressions) if wrapped else expressions
    1346                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1347        return ""

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

    1349    def with_properties(self, properties: exp.Properties) -> str:
    1350        return self.properties(properties, prefix=self.seg("WITH"))

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

    1352    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1353        properties_locs = defaultdict(list)
    1354        for p in properties.expressions:
    1355            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1356            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1357                properties_locs[p_loc].append(p)
    1358            else:
    1359                self.unsupported(f"Unsupported property {p.key}")
    1360
    1361        return properties_locs

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

    1363    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1364        if isinstance(expression.this, exp.Dot):
    1365            return self.sql(expression, "this")
    1366        return f"'{expression.name}'" if string_key else expression.name

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

    1368    def property_sql(self, expression: exp.Property) -> str:
    1369        property_cls = expression.__class__
    1370        if property_cls == exp.Property:
    1371            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1372
    1373        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1374        if not property_name:
    1375            self.unsupported(f"Unsupported property {expression.key}")
    1376
    1377        return f"{property_name}={self.sql(expression, 'this')}"

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

    1379    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1380        if self.SUPPORTS_CREATE_TABLE_LIKE:
    1381            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1382            options = f" {options}" if options else ""
    1383
    1384            like = f"LIKE {self.sql(expression, 'this')}{options}"
    1385            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
    1386                like = f"({like})"
    1387
    1388            return like
    1389
    1390        if expression.expressions:
    1391            self.unsupported("Transpilation of LIKE property options is unsupported")
    1392
    1393        select = exp.select("*").from_(expression.this).limit(0)
    1394        return f"AS {self.sql(select)}"

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

    1396    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1397        no = "NO " if expression.args.get("no") else ""
    1398        protection = " PROTECTION" if expression.args.get("protection") else ""
    1399        return f"{no}FALLBACK{protection}"

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

    1401    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1402        no = "NO " if expression.args.get("no") else ""
    1403        local = expression.args.get("local")
    1404        local = f"{local} " if local else ""
    1405        dual = "DUAL " if expression.args.get("dual") else ""
    1406        before = "BEFORE " if expression.args.get("before") else ""
    1407        after = "AFTER " if expression.args.get("after") else ""
    1408        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1410    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1411        freespace = self.sql(expression, "this")
    1412        percent = " PERCENT" if expression.args.get("percent") else ""
    1413        return f"FREESPACE={freespace}{percent}"

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

    1415    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1416        if expression.args.get("default"):
    1417            property = "DEFAULT"
    1418        elif expression.args.get("on"):
    1419            property = "ON"
    1420        else:
    1421            property = "OFF"
    1422        return f"CHECKSUM={property}"

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

    1424    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1425        if expression.args.get("no"):
    1426            return "NO MERGEBLOCKRATIO"
    1427        if expression.args.get("default"):
    1428            return "DEFAULT MERGEBLOCKRATIO"
    1429
    1430        percent = " PERCENT" if expression.args.get("percent") else ""
    1431        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1433    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1434        default = expression.args.get("default")
    1435        minimum = expression.args.get("minimum")
    1436        maximum = expression.args.get("maximum")
    1437        if default or minimum or maximum:
    1438            if default:
    1439                prop = "DEFAULT"
    1440            elif minimum:
    1441                prop = "MINIMUM"
    1442            else:
    1443                prop = "MAXIMUM"
    1444            return f"{prop} DATABLOCKSIZE"
    1445        units = expression.args.get("units")
    1446        units = f" {units}" if units else ""
    1447        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1449    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1450        autotemp = expression.args.get("autotemp")
    1451        always = expression.args.get("always")
    1452        default = expression.args.get("default")
    1453        manual = expression.args.get("manual")
    1454        never = expression.args.get("never")
    1455
    1456        if autotemp is not None:
    1457            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1458        elif always:
    1459            prop = "ALWAYS"
    1460        elif default:
    1461            prop = "DEFAULT"
    1462        elif manual:
    1463            prop = "MANUAL"
    1464        elif never:
    1465            prop = "NEVER"
    1466        return f"BLOCKCOMPRESSION={prop}"

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

    1468    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1469        no = expression.args.get("no")
    1470        no = " NO" if no else ""
    1471        concurrent = expression.args.get("concurrent")
    1472        concurrent = " CONCURRENT" if concurrent else ""
    1473        target = self.sql(expression, "target")
    1474        target = f" {target}" if target else ""
    1475        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"

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

    1477    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1478        if isinstance(expression.this, list):
    1479            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1480        if expression.this:
    1481            modulus = self.sql(expression, "this")
    1482            remainder = self.sql(expression, "expression")
    1483            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1484
    1485        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1486        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1487        return f"FROM ({from_expressions}) TO ({to_expressions})"

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

    1489    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1490        this = self.sql(expression, "this")
    1491
    1492        for_values_or_default = expression.expression
    1493        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1494            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1495        else:
    1496            for_values_or_default = " DEFAULT"
    1497
    1498        return f"PARTITION OF {this}{for_values_or_default}"

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

    1500    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1501        kind = expression.args.get("kind")
    1502        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1503        for_or_in = expression.args.get("for_or_in")
    1504        for_or_in = f" {for_or_in}" if for_or_in else ""
    1505        lock_type = expression.args.get("lock_type")
    1506        override = " OVERRIDE" if expression.args.get("override") else ""
    1507        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"

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

    1509    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1510        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1511        statistics = expression.args.get("statistics")
    1512        statistics_sql = ""
    1513        if statistics is not None:
    1514            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1515        return f"{data_sql}{statistics_sql}"

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

    1517    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1518        sql = "WITH(SYSTEM_VERSIONING=ON"
    1519
    1520        if expression.this:
    1521            history_table = self.sql(expression, "this")
    1522            sql = f"{sql}(HISTORY_TABLE={history_table}"
    1523
    1524            if expression.expression:
    1525                data_consistency_check = self.sql(expression, "expression")
    1526                sql = f"{sql}, DATA_CONSISTENCY_CHECK={data_consistency_check}"
    1527
    1528            sql = f"{sql})"
    1529
    1530        return f"{sql})"

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

    1532    def insert_sql(self, expression: exp.Insert) -> str:
    1533        hint = self.sql(expression, "hint")
    1534        overwrite = expression.args.get("overwrite")
    1535
    1536        if isinstance(expression.this, exp.Directory):
    1537            this = " OVERWRITE" if overwrite else " INTO"
    1538        else:
    1539            this = self.INSERT_OVERWRITE if overwrite else " INTO"
    1540
    1541        stored = self.sql(expression, "stored")
    1542        stored = f" {stored}" if stored else ""
    1543        alternative = expression.args.get("alternative")
    1544        alternative = f" OR {alternative}" if alternative else ""
    1545        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1546        is_function = expression.args.get("is_function")
    1547        if is_function:
    1548            this = f"{this} FUNCTION"
    1549        this = f"{this} {self.sql(expression, 'this')}"
    1550
    1551        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1552        where = self.sql(expression, "where")
    1553        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1554        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1555        on_conflict = self.sql(expression, "conflict")
    1556        on_conflict = f" {on_conflict}" if on_conflict else ""
    1557        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1558        returning = self.sql(expression, "returning")
    1559
    1560        if self.RETURNING_END:
    1561            expression_sql = f"{expression_sql}{on_conflict}{returning}"
    1562        else:
    1563            expression_sql = f"{returning}{expression_sql}{on_conflict}"
    1564
    1565        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{where}{expression_sql}"
    1566        return self.prepend_ctes(expression, sql)

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

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

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

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

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

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

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

    1577    def kill_sql(self, expression: exp.Kill) -> str:
    1578        kind = self.sql(expression, "kind")
    1579        kind = f" {kind}" if kind else ""
    1580        this = self.sql(expression, "this")
    1581        this = f" {this}" if this else ""
    1582        return f"KILL{kind}{this}"

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

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

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

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

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

    1590    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1591        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1592
    1593        constraint = self.sql(expression, "constraint")
    1594        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
    1595
    1596        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
    1597        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
    1598        action = self.sql(expression, "action")
    1599
    1600        expressions = self.expressions(expression, flat=True)
    1601        if expressions:
    1602            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1603            expressions = f" {set_keyword}{expressions}"
    1604
    1605        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}"

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

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

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

    1610    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1611        fields = self.sql(expression, "fields")
    1612        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1613        escaped = self.sql(expression, "escaped")
    1614        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1615        items = self.sql(expression, "collection_items")
    1616        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1617        keys = self.sql(expression, "map_keys")
    1618        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1619        lines = self.sql(expression, "lines")
    1620        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1621        null = self.sql(expression, "null")
    1622        null = f" NULL DEFINED AS {null}" if null else ""
    1623        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1628    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1629        this = f"{self.sql(expression, 'this')} INDEX"
    1630        target = self.sql(expression, "target")
    1631        target = f" FOR {target}" if target else ""
    1632        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1634    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1635        this = self.sql(expression, "this")
    1636        kind = self.sql(expression, "kind")
    1637        expr = self.sql(expression, "expression")
    1638        return f"{this} ({kind} => {expr})"

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

    1640    def table_parts(self, expression: exp.Table) -> str:
    1641        return ".".join(
    1642            self.sql(part)
    1643            for part in (
    1644                expression.args.get("catalog"),
    1645                expression.args.get("db"),
    1646                expression.args.get("this"),
    1647            )
    1648            if part is not None
    1649        )

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

    1651    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1652        table = self.table_parts(expression)
    1653        only = "ONLY " if expression.args.get("only") else ""
    1654        partition = self.sql(expression, "partition")
    1655        partition = f" {partition}" if partition else ""
    1656        version = self.sql(expression, "version")
    1657        version = f" {version}" if version else ""
    1658        alias = self.sql(expression, "alias")
    1659        alias = f"{sep}{alias}" if alias else ""
    1660        hints = self.expressions(expression, key="hints", sep=" ")
    1661        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1662        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1663        pivots = f" {pivots}" if pivots else ""
    1664        joins = self.indent(
    1665            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    1666        )
    1667        laterals = self.expressions(expression, key="laterals", sep="")
    1668
    1669        file_format = self.sql(expression, "format")
    1670        if file_format:
    1671            pattern = self.sql(expression, "pattern")
    1672            pattern = f", PATTERN => {pattern}" if pattern else ""
    1673            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    1674
    1675        ordinality = expression.args.get("ordinality") or ""
    1676        if ordinality:
    1677            ordinality = f" WITH ORDINALITY{alias}"
    1678            alias = ""
    1679
    1680        when = self.sql(expression, "when")
    1681        if when:
    1682            table = f"{table} {when}"
    1683
    1684        return f"{only}{table}{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

    1686    def tablesample_sql(
    1687        self,
    1688        expression: exp.TableSample,
    1689        sep: str = " AS ",
    1690        tablesample_keyword: t.Optional[str] = None,
    1691    ) -> str:
    1692        if self.dialect.ALIAS_POST_TABLESAMPLE and expression.this and expression.this.alias:
    1693            table = expression.this.copy()
    1694            table.set("alias", None)
    1695            this = self.sql(table)
    1696            alias = f"{sep}{self.sql(expression.this, 'alias')}"
    1697        else:
    1698            this = self.sql(expression, "this")
    1699            alias = ""
    1700
    1701        method = self.sql(expression, "method")
    1702        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1703        numerator = self.sql(expression, "bucket_numerator")
    1704        denominator = self.sql(expression, "bucket_denominator")
    1705        field = self.sql(expression, "bucket_field")
    1706        field = f" ON {field}" if field else ""
    1707        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1708        seed = self.sql(expression, "seed")
    1709        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
    1710
    1711        size = self.sql(expression, "size")
    1712        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
    1713            size = f"{size} ROWS"
    1714
    1715        percent = self.sql(expression, "percent")
    1716        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
    1717            percent = f"{percent} PERCENT"
    1718
    1719        expr = f"{bucket}{percent}{size}"
    1720        if self.TABLESAMPLE_REQUIRES_PARENS:
    1721            expr = f"({expr})"
    1722
    1723        return (
    1724            f"{this} {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}{alias}"
    1725        )

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

    1727    def pivot_sql(self, expression: exp.Pivot) -> str:
    1728        expressions = self.expressions(expression, flat=True)
    1729
    1730        if expression.this:
    1731            this = self.sql(expression, "this")
    1732            if not expressions:
    1733                return f"UNPIVOT {this}"
    1734
    1735            on = f"{self.seg('ON')} {expressions}"
    1736            using = self.expressions(expression, key="using", flat=True)
    1737            using = f"{self.seg('USING')} {using}" if using else ""
    1738            group = self.sql(expression, "group")
    1739            return f"PIVOT {this}{on}{using}{group}"
    1740
    1741        alias = self.sql(expression, "alias")
    1742        alias = f" AS {alias}" if alias else ""
    1743        direction = "UNPIVOT" if expression.unpivot else "PIVOT"
    1744        field = self.sql(expression, "field")
    1745        include_nulls = expression.args.get("include_nulls")
    1746        if include_nulls is not None:
    1747            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    1748        else:
    1749            nulls = ""
    1750        return f"{direction}{nulls}({expressions} FOR {field}){alias}"

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

    1752    def version_sql(self, expression: exp.Version) -> str:
    1753        this = f"FOR {expression.name}"
    1754        kind = expression.text("kind")
    1755        expr = self.sql(expression, "expression")
    1756        return f"{this} {kind} {expr}"

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

    1758    def tuple_sql(self, expression: exp.Tuple) -> str:
    1759        return f"({self.expressions(expression, flat=True)})"

def update_sql(self, expression: sqlglot.expressions.Update) -> str: View Source

    1761    def update_sql(self, expression: exp.Update) -> str:
    1762        this = self.sql(expression, "this")
    1763        set_sql = self.expressions(expression, flat=True)
    1764        from_sql = self.sql(expression, "from")
    1765        where_sql = self.sql(expression, "where")
    1766        returning = self.sql(expression, "returning")
    1767        order = self.sql(expression, "order")
    1768        limit = self.sql(expression, "limit")
    1769        if self.RETURNING_END:
    1770            expression_sql = f"{from_sql}{where_sql}{returning}"
    1771        else:
    1772            expression_sql = f"{returning}{from_sql}{where_sql}"
    1773        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    1774        return self.prepend_ctes(expression, sql)

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

    1776    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
    1777        values_as_table = values_as_table and self.VALUES_AS_TABLE
    1778
    1779        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    1780        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
    1781            args = self.expressions(expression)
    1782            alias = self.sql(expression, "alias")
    1783            values = f"VALUES{self.seg('')}{args}"
    1784            values = (
    1785                f"({values})"
    1786                if self.WRAP_DERIVED_VALUES and (alias or isinstance(expression.parent, exp.From))
    1787                else values
    1788            )
    1789            return f"{values} AS {alias}" if alias else values
    1790
    1791        # Converts `VALUES...` expression into a series of select unions.
    1792        alias_node = expression.args.get("alias")
    1793        column_names = alias_node and alias_node.columns
    1794
    1795        selects: t.List[exp.Query] = []
    1796
    1797        for i, tup in enumerate(expression.expressions):
    1798            row = tup.expressions
    1799
    1800            if i == 0 and column_names:
    1801                row = [
    1802                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    1803                ]
    1804
    1805            selects.append(exp.Select(expressions=row))
    1806
    1807        if self.pretty:
    1808            # This may result in poor performance for large-cardinality `VALUES` tables, due to
    1809            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
    1810            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
    1811            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
    1812            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
    1813
    1814        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
    1815        unions = " UNION ALL ".join(self.sql(select) for select in selects)
    1816        return f"({unions}){alias}"

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

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

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

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

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

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

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

    1829    def group_sql(self, expression: exp.Group) -> str:
    1830        group_by_all = expression.args.get("all")
    1831        if group_by_all is True:
    1832            modifier = " ALL"
    1833        elif group_by_all is False:
    1834            modifier = " DISTINCT"
    1835        else:
    1836            modifier = ""
    1837
    1838        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
    1839
    1840        grouping_sets = self.expressions(expression, key="grouping_sets", indent=False)
    1841        grouping_sets = (
    1842            f"{self.seg('GROUPING SETS')} {self.wrap(grouping_sets)}" if grouping_sets else ""
    1843        )
    1844
    1845        cube = expression.args.get("cube", [])
    1846        if seq_get(cube, 0) is True:
    1847            return f"{group_by}{self.seg('WITH CUBE')}"
    1848        else:
    1849            cube_sql = self.expressions(expression, key="cube", indent=False)
    1850            cube_sql = f"{self.seg('CUBE')} {self.wrap(cube_sql)}" if cube_sql else ""
    1851
    1852        rollup = expression.args.get("rollup", [])
    1853        if seq_get(rollup, 0) is True:
    1854            return f"{group_by}{self.seg('WITH ROLLUP')}"
    1855        else:
    1856            rollup_sql = self.expressions(expression, key="rollup", indent=False)
    1857            rollup_sql = f"{self.seg('ROLLUP')} {self.wrap(rollup_sql)}" if rollup_sql else ""
    1858
    1859        groupings = csv(
    1860            grouping_sets,
    1861            cube_sql,
    1862            rollup_sql,
    1863            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    1864            sep=self.GROUPINGS_SEP,
    1865        )
    1866
    1867        if expression.args.get("expressions") and groupings:
    1868            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    1869
    1870        return f"{group_by}{groupings}"

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

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

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

    1876    def connect_sql(self, expression: exp.Connect) -> str:
    1877        start = self.sql(expression, "start")
    1878        start = self.seg(f"START WITH {start}") if start else ""
    1879        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
    1880        connect = self.sql(expression, "connect")
    1881        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
    1882        return start + connect

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

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

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

    1887    def join_sql(self, expression: exp.Join) -> str:
    1888        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    1889            side = None
    1890        else:
    1891            side = expression.side
    1892
    1893        op_sql = " ".join(
    1894            op
    1895            for op in (
    1896                expression.method,
    1897                "GLOBAL" if expression.args.get("global") else None,
    1898                side,
    1899                expression.kind,
    1900                expression.hint if self.JOIN_HINTS else None,
    1901            )
    1902            if op
    1903        )
    1904        match_cond = self.sql(expression, "match_condition")
    1905        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
    1906        on_sql = self.sql(expression, "on")
    1907        using = expression.args.get("using")
    1908
    1909        if not on_sql and using:
    1910            on_sql = csv(*(self.sql(column) for column in using))
    1911
    1912        this = expression.this
    1913        this_sql = self.sql(this)
    1914
    1915        if on_sql:
    1916            on_sql = self.indent(on_sql, skip_first=True)
    1917            space = self.seg(" " * self.pad) if self.pretty else " "
    1918            if using:
    1919                on_sql = f"{space}USING ({on_sql})"
    1920            else:
    1921                on_sql = f"{space}ON {on_sql}"
    1922        elif not op_sql:
    1923            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
    1924                return f" {this_sql}"
    1925
    1926            return f", {this_sql}"
    1927
    1928        op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    1929        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

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

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

    1936    def lateral_op(self, expression: exp.Lateral) -> str:
    1937        cross_apply = expression.args.get("cross_apply")
    1938
    1939        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    1940        if cross_apply is True:
    1941            op = "INNER JOIN "
    1942        elif cross_apply is False:
    1943            op = "LEFT JOIN "
    1944        else:
    1945            op = ""
    1946
    1947        return f"{op}LATERAL"

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

    1949    def lateral_sql(self, expression: exp.Lateral) -> str:
    1950        this = self.sql(expression, "this")
    1951
    1952        if expression.args.get("view"):
    1953            alias = expression.args["alias"]
    1954            columns = self.expressions(alias, key="columns", flat=True)
    1955            table = f" {alias.name}" if alias.name else ""
    1956            columns = f" AS {columns}" if columns else ""
    1957            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    1958            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    1959
    1960        alias = self.sql(expression, "alias")
    1961        alias = f" AS {alias}" if alias else ""
    1962        return f"{self.lateral_op(expression)} {this}{alias}"

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

    1964    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    1965        this = self.sql(expression, "this")
    1966
    1967        args = [
    1968            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    1969            for e in (expression.args.get(k) for k in ("offset", "expression"))
    1970            if e
    1971        ]
    1972
    1973        args_sql = ", ".join(self.sql(e) for e in args)
    1974        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
    1975        expressions = self.expressions(expression, flat=True)
    1976        expressions = f" BY {expressions}" if expressions else ""
    1977
    1978        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}"

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

    1980    def offset_sql(self, expression: exp.Offset) -> str:
    1981        this = self.sql(expression, "this")
    1982        value = expression.expression
    1983        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    1984        expressions = self.expressions(expression, flat=True)
    1985        expressions = f" BY {expressions}" if expressions else ""
    1986        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"

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

    1988    def setitem_sql(self, expression: exp.SetItem) -> str:
    1989        kind = self.sql(expression, "kind")
    1990        kind = f"{kind} " if kind else ""
    1991        this = self.sql(expression, "this")
    1992        expressions = self.expressions(expression)
    1993        collate = self.sql(expression, "collate")
    1994        collate = f" COLLATE {collate}" if collate else ""
    1995        global_ = "GLOBAL " if expression.args.get("global") else ""
    1996        return f"{global_}{kind}{this}{expressions}{collate}"

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

    1998    def set_sql(self, expression: exp.Set) -> str:
    1999        expressions = (
    2000            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    2001        )
    2002        tag = " TAG" if expression.args.get("tag") else ""
    2003        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"

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

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

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

    2008    def lock_sql(self, expression: exp.Lock) -> str:
    2009        if not self.LOCKING_READS_SUPPORTED:
    2010            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    2011            return ""
    2012
    2013        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    2014        expressions = self.expressions(expression, flat=True)
    2015        expressions = f" OF {expressions}" if expressions else ""
    2016        wait = expression.args.get("wait")
    2017
    2018        if wait is not None:
    2019            if isinstance(wait, exp.Literal):
    2020                wait = f" WAIT {self.sql(wait)}"
    2021            else:
    2022                wait = " NOWAIT" if wait else " SKIP LOCKED"
    2023
    2024        return f"{lock_type}{expressions}{wait or ''}"

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

    2026    def literal_sql(self, expression: exp.Literal) -> str:
    2027        text = expression.this or ""
    2028        if expression.is_string:
    2029            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    2030        return text

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

    2032    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
    2033        if self.dialect.ESCAPED_SEQUENCES:
    2034            to_escaped = self.dialect.ESCAPED_SEQUENCES
    2035            text = "".join(
    2036                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
    2037            )
    2038
    2039        return self._replace_line_breaks(text).replace(
    2040            self.dialect.QUOTE_END, self._escaped_quote_end
    2041        )

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

    2043    def loaddata_sql(self, expression: exp.LoadData) -> str:
    2044        local = " LOCAL" if expression.args.get("local") else ""
    2045        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    2046        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    2047        this = f" INTO TABLE {self.sql(expression, 'this')}"
    2048        partition = self.sql(expression, "partition")
    2049        partition = f" {partition}" if partition else ""
    2050        input_format = self.sql(expression, "input_format")
    2051        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    2052        serde = self.sql(expression, "serde")
    2053        serde = f" SERDE {serde}" if serde else ""
    2054        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    2056    def null_sql(self, *_) -> str:
    2057        return "NULL"

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

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

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

    2062    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2063        this = self.sql(expression, "this")
    2064        this = f"{this} " if this else this
    2065        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2066        order = self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat)  # type: ignore
    2067        interpolated_values = [
    2068            f"{self.sql(named_expression, 'alias')} AS {self.sql(named_expression, 'this')}"
    2069            for named_expression in expression.args.get("interpolate") or []
    2070        ]
    2071        interpolate = (
    2072            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    2073        )
    2074        return f"{order}{interpolate}"

def withfill_sql(self, expression: sqlglot.expressions.WithFill) -> str: View Source

    2076    def withfill_sql(self, expression: exp.WithFill) -> str:
    2077        from_sql = self.sql(expression, "from")
    2078        from_sql = f" FROM {from_sql}" if from_sql else ""
    2079        to_sql = self.sql(expression, "to")
    2080        to_sql = f" TO {to_sql}" if to_sql else ""
    2081        step_sql = self.sql(expression, "step")
    2082        step_sql = f" STEP {step_sql}" if step_sql else ""
    2083        return f"WITH FILL{from_sql}{to_sql}{step_sql}"

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

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

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

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

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

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

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

    2094    def ordered_sql(self, expression: exp.Ordered) -> str:
    2095        desc = expression.args.get("desc")
    2096        asc = not desc
    2097
    2098        nulls_first = expression.args.get("nulls_first")
    2099        nulls_last = not nulls_first
    2100        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
    2101        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
    2102        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
    2103
    2104        this = self.sql(expression, "this")
    2105
    2106        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
    2107        nulls_sort_change = ""
    2108        if nulls_first and (
    2109            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    2110        ):
    2111            nulls_sort_change = " NULLS FIRST"
    2112        elif (
    2113            nulls_last
    2114            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    2115            and not nulls_are_last
    2116        ):
    2117            nulls_sort_change = " NULLS LAST"
    2118
    2119        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
    2120        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    2121            window = expression.find_ancestor(exp.Window, exp.Select)
    2122            if isinstance(window, exp.Window) and window.args.get("spec"):
    2123                self.unsupported(
    2124                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
    2125                )
    2126                nulls_sort_change = ""
    2127            elif self.NULL_ORDERING_SUPPORTED is None:
    2128                if expression.this.is_int:
    2129                    self.unsupported(
    2130                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
    2131                    )
    2132                elif not isinstance(expression.this, exp.Rand):
    2133                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
    2134                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
    2135                nulls_sort_change = ""
    2136
    2137        with_fill = self.sql(expression, "with_fill")
    2138        with_fill = f" {with_fill}" if with_fill else ""
    2139
    2140        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"

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

    2142    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
    2143        window_frame = self.sql(expression, "window_frame")
    2144        window_frame = f"{window_frame} " if window_frame else ""
    2145
    2146        this = self.sql(expression, "this")
    2147
    2148        return f"{window_frame}{this}"

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

    2150    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    2151        partition = self.partition_by_sql(expression)
    2152        order = self.sql(expression, "order")
    2153        measures = self.expressions(expression, key="measures")
    2154        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    2155        rows = self.sql(expression, "rows")
    2156        rows = self.seg(rows) if rows else ""
    2157        after = self.sql(expression, "after")
    2158        after = self.seg(after) if after else ""
    2159        pattern = self.sql(expression, "pattern")
    2160        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    2161        definition_sqls = [
    2162            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    2163            for definition in expression.args.get("define", [])
    2164        ]
    2165        definitions = self.expressions(sqls=definition_sqls)
    2166        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    2167        body = "".join(
    2168            (
    2169                partition,
    2170                order,
    2171                measures,
    2172                rows,
    2173                after,
    2174                pattern,
    2175                define,
    2176            )
    2177        )
    2178        alias = self.sql(expression, "alias")
    2179        alias = f" {alias}" if alias else ""
    2180        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    2182    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    2183        limit = expression.args.get("limit")
    2184
    2185        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    2186            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    2187        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    2188            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    2189
    2190        options = self.expressions(expression, key="options")
    2191        if options:
    2192            options = f" OPTION{self.wrap(options)}"
    2193
    2194        return csv(
    2195            *sqls,
    2196            *[self.sql(join) for join in expression.args.get("joins") or []],
    2197            self.sql(expression, "connect"),
    2198            self.sql(expression, "match"),
    2199            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2200            self.sql(expression, "prewhere"),
    2201            self.sql(expression, "where"),
    2202            self.sql(expression, "group"),
    2203            self.sql(expression, "having"),
    2204            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
    2205            self.sql(expression, "order"),
    2206            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
    2207            *self.after_limit_modifiers(expression),
    2208            options,
    2209            sep="",
    2210        )

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

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

    2215    def offset_limit_modifiers(
    2216        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2217    ) -> t.List[str]:
    2218        return [
    2219            self.sql(expression, "offset") if fetch else self.sql(limit),
    2220            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2221        ]

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

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

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

    2228    def select_sql(self, expression: exp.Select) -> str:
    2229        into = expression.args.get("into")
    2230        if not self.SUPPORTS_SELECT_INTO and into:
    2231            into.pop()
    2232
    2233        hint = self.sql(expression, "hint")
    2234        distinct = self.sql(expression, "distinct")
    2235        distinct = f" {distinct}" if distinct else ""
    2236        kind = self.sql(expression, "kind")
    2237
    2238        limit = expression.args.get("limit")
    2239        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
    2240            top = self.limit_sql(limit, top=True)
    2241            limit.pop()
    2242        else:
    2243            top = ""
    2244
    2245        expressions = self.expressions(expression)
    2246
    2247        if kind:
    2248            if kind in self.SELECT_KINDS:
    2249                kind = f" AS {kind}"
    2250            else:
    2251                if kind == "STRUCT":
    2252                    expressions = self.expressions(
    2253                        sqls=[
    2254                            self.sql(
    2255                                exp.Struct(
    2256                                    expressions=[
    2257                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
    2258                                        if isinstance(e, exp.Alias)
    2259                                        else e
    2260                                        for e in expression.expressions
    2261                                    ]
    2262                                )
    2263                            )
    2264                        ]
    2265                    )
    2266                kind = ""
    2267
    2268        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
    2269        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
    2270        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
    2271        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    2272        sql = self.query_modifiers(
    2273            expression,
    2274            f"SELECT{top_distinct}{kind}{expressions}",
    2275            self.sql(expression, "into", comment=False),
    2276            self.sql(expression, "from", comment=False),
    2277        )
    2278
    2279        sql = self.prepend_ctes(expression, sql)
    2280
    2281        if not self.SUPPORTS_SELECT_INTO and into:
    2282            if into.args.get("temporary"):
    2283                table_kind = " TEMPORARY"
    2284            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
    2285                table_kind = " UNLOGGED"
    2286            else:
    2287                table_kind = ""
    2288            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
    2289
    2290        return sql

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

    2292    def schema_sql(self, expression: exp.Schema) -> str:
    2293        this = self.sql(expression, "this")
    2294        sql = self.schema_columns_sql(expression)
    2295        return f"{this} {sql}" if this and sql else this or sql

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

    2297    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2298        if expression.expressions:
    2299            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2300        return ""

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

    2302    def star_sql(self, expression: exp.Star) -> str:
    2303        except_ = self.expressions(expression, key="except", flat=True)
    2304        except_ = f"{self.seg(self.STAR_MAPPING['except'])} ({except_})" if except_ else ""
    2305        replace = self.expressions(expression, key="replace", flat=True)
    2306        replace = f"{self.seg(self.STAR_MAPPING['replace'])} ({replace})" if replace else ""
    2307        return f"*{except_}{replace}"

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

    2309    def parameter_sql(self, expression: exp.Parameter) -> str:
    2310        this = self.sql(expression, "this")
    2311        return f"{self.PARAMETER_TOKEN}{this}"

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

    2313    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2314        this = self.sql(expression, "this")
    2315        kind = expression.text("kind")
    2316        if kind:
    2317            kind = f"{kind}."
    2318        return f"@@{kind}{this}"

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

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

    2323    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2324        alias = self.sql(expression, "alias")
    2325        alias = f"{sep}{alias}" if alias else ""
    2326
    2327        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    2328        pivots = f" {pivots}" if pivots else ""
    2329
    2330        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2331        return self.prepend_ctes(expression, sql)

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

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

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

    2337    def set_operations(self, expression: exp.Union) -> str:
    2338        if not self.OUTER_UNION_MODIFIERS:
    2339            limit = expression.args.get("limit")
    2340            order = expression.args.get("order")
    2341
    2342            if limit or order:
    2343                select = exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
    2344
    2345                if limit:
    2346                    select = select.limit(limit.pop(), copy=False)
    2347                if order:
    2348                    select = select.order_by(order.pop(), copy=False)
    2349                return self.sql(select)
    2350
    2351        sqls: t.List[str] = []
    2352        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    2353
    2354        while stack:
    2355            node = stack.pop()
    2356
    2357            if isinstance(node, exp.Union):
    2358                stack.append(node.expression)
    2359                stack.append(
    2360                    self.maybe_comment(
    2361                        getattr(self, f"{node.key}_op")(node),
    2362                        comments=node.comments,
    2363                        separated=True,
    2364                    )
    2365                )
    2366                stack.append(node.this)
    2367            else:
    2368                sqls.append(self.sql(node))
    2369
    2370        this = self.sep().join(sqls)
    2371        this = self.query_modifiers(expression, this)
    2372        return self.prepend_ctes(expression, this)

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

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

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

    2377    def union_op(self, expression: exp.Union) -> str:
    2378        kind = " DISTINCT" if self.EXPLICIT_UNION else ""
    2379        kind = kind if expression.args.get("distinct") else " ALL"
    2380        by_name = " BY NAME" if expression.args.get("by_name") else ""
    2381        return f"UNION{kind}{by_name}"

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

    2383    def unnest_sql(self, expression: exp.Unnest) -> str:
    2384        args = self.expressions(expression, flat=True)
    2385
    2386        alias = expression.args.get("alias")
    2387        offset = expression.args.get("offset")
    2388
    2389        if self.UNNEST_WITH_ORDINALITY:
    2390            if alias and isinstance(offset, exp.Expression):
    2391                alias.append("columns", offset)
    2392
    2393        if alias and self.dialect.UNNEST_COLUMN_ONLY:
    2394            columns = alias.columns
    2395            alias = self.sql(columns[0]) if columns else ""
    2396        else:
    2397            alias = self.sql(alias)
    2398
    2399        alias = f" AS {alias}" if alias else alias
    2400        if self.UNNEST_WITH_ORDINALITY:
    2401            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2402        else:
    2403            if isinstance(offset, exp.Expression):
    2404                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2405            elif offset:
    2406                suffix = f"{alias} WITH OFFSET"
    2407            else:
    2408                suffix = alias
    2409
    2410        return f"UNNEST({args}){suffix}"

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

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

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

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

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

    2419    def window_sql(self, expression: exp.Window) -> str:
    2420        this = self.sql(expression, "this")
    2421        partition = self.partition_by_sql(expression)
    2422        order = expression.args.get("order")
    2423        order = self.order_sql(order, flat=True) if order else ""
    2424        spec = self.sql(expression, "spec")
    2425        alias = self.sql(expression, "alias")
    2426        over = self.sql(expression, "over") or "OVER"
    2427
    2428        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2429
    2430        first = expression.args.get("first")
    2431        if first is None:
    2432            first = ""
    2433        else:
    2434            first = "FIRST" if first else "LAST"
    2435
    2436        if not partition and not order and not spec and alias:
    2437            return f"{this} {alias}"
    2438
    2439        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    2440        return f"{this} ({args})"

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

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

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

    2446    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2447        kind = self.sql(expression, "kind")
    2448        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2449        end = (
    2450            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2451            or "CURRENT ROW"
    2452        )
    2453        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    2460    def between_sql(self, expression: exp.Between) -> str:
    2461        this = self.sql(expression, "this")
    2462        low = self.sql(expression, "low")
    2463        high = self.sql(expression, "high")
    2464        return f"{this} BETWEEN {low} AND {high}"

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

    2466    def bracket_offset_expressions(self, expression: exp.Bracket) -> t.List[exp.Expression]:
    2467        return apply_index_offset(
    2468            expression.this,
    2469            expression.expressions,
    2470            self.dialect.INDEX_OFFSET - expression.args.get("offset", 0),
    2471        )

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

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

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

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

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

    2481    def any_sql(self, expression: exp.Any) -> str:
    2482        this = self.sql(expression, "this")
    2483        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
    2484            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2485                this = self.wrap(this)
    2486            return f"ANY{this}"
    2487        return f"ANY {this}"

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

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

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

    2492    def case_sql(self, expression: exp.Case) -> str:
    2493        this = self.sql(expression, "this")
    2494        statements = [f"CASE {this}" if this else "CASE"]
    2495
    2496        for e in expression.args["ifs"]:
    2497            statements.append(f"WHEN {self.sql(e, 'this')}")
    2498            statements.append(f"THEN {self.sql(e, 'true')}")
    2499
    2500        default = self.sql(expression, "default")
    2501
    2502        if default:
    2503            statements.append(f"ELSE {default}")
    2504
    2505        statements.append("END")
    2506
    2507        if self.pretty and self.too_wide(statements):
    2508            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2509
    2510        return " ".join(statements)

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

    2512    def constraint_sql(self, expression: exp.Constraint) -> str:
    2513        this = self.sql(expression, "this")
    2514        expressions = self.expressions(expression, flat=True)
    2515        return f"CONSTRAINT {this} {expressions}"

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

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

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

    2522    def extract_sql(self, expression: exp.Extract) -> str:
    2523        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2524        expression_sql = self.sql(expression, "expression")
    2525        return f"EXTRACT({this} FROM {expression_sql})"

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

    2527    def trim_sql(self, expression: exp.Trim) -> str:
    2528        trim_type = self.sql(expression, "position")
    2529
    2530        if trim_type == "LEADING":
    2531            return self.func("LTRIM", expression.this)
    2532        elif trim_type == "TRAILING":
    2533            return self.func("RTRIM", expression.this)
    2534        else:
    2535            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

    2537    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2538        args = expression.expressions
    2539        if isinstance(expression, exp.ConcatWs):
    2540            args = args[1:]  # Skip the delimiter
    2541
    2542        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2543            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
    2544
    2545        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2546            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2547
    2548        return args

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

    2550    def concat_sql(self, expression: exp.Concat) -> str:
    2551        expressions = self.convert_concat_args(expression)
    2552
    2553        # Some dialects don't allow a single-argument CONCAT call
    2554        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2555            return self.sql(expressions[0])
    2556
    2557        return self.func("CONCAT", *expressions)

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

    2559    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2560        return self.func(
    2561            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2562        )

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

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

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

    2568    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2569        expressions = self.expressions(expression, flat=True)
    2570        reference = self.sql(expression, "reference")
    2571        reference = f" {reference}" if reference else ""
    2572        delete = self.sql(expression, "delete")
    2573        delete = f" ON DELETE {delete}" if delete else ""
    2574        update = self.sql(expression, "update")
    2575        update = f" ON UPDATE {update}" if update else ""
    2576        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"

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

    2578    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2579        expressions = self.expressions(expression, flat=True)
    2580        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2581        options = f" {options}" if options else ""
    2582        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

    2595    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
    2596        path = self.expressions(expression, sep="", flat=True).lstrip(".")
    2597        return f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"

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

    2599    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
    2600        if isinstance(expression, exp.JSONPathPart):
    2601            transform = self.TRANSFORMS.get(expression.__class__)
    2602            if not callable(transform):
    2603                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
    2604                return ""
    2605
    2606            return transform(self, expression)
    2607
    2608        if isinstance(expression, int):
    2609            return str(expression)
    2610
    2611        if self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
    2612            escaped = expression.replace("'", "\\'")
    2613            escaped = f"\\'{expression}\\'"
    2614        else:
    2615            escaped = expression.replace('"', '\\"')
    2616            escaped = f'"{escaped}"'
    2617
    2618        return escaped

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

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

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

    2623    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    2624        null_handling = expression.args.get("null_handling")
    2625        null_handling = f" {null_handling}" if null_handling else ""
    2626
    2627        unique_keys = expression.args.get("unique_keys")
    2628        if unique_keys is not None:
    2629            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2630        else:
    2631            unique_keys = ""
    2632
    2633        return_type = self.sql(expression, "return_type")
    2634        return_type = f" RETURNING {return_type}" if return_type else ""
    2635        encoding = self.sql(expression, "encoding")
    2636        encoding = f" ENCODING {encoding}" if encoding else ""
    2637
    2638        return self.func(
    2639            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    2640            *expression.expressions,
    2641            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2642        )

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

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

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

    2647    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2648        null_handling = expression.args.get("null_handling")
    2649        null_handling = f" {null_handling}" if null_handling else ""
    2650        return_type = self.sql(expression, "return_type")
    2651        return_type = f" RETURNING {return_type}" if return_type else ""
    2652        strict = " STRICT" if expression.args.get("strict") else ""
    2653        return self.func(
    2654            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2655        )

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

    2657    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2658        this = self.sql(expression, "this")
    2659        order = self.sql(expression, "order")
    2660        null_handling = expression.args.get("null_handling")
    2661        null_handling = f" {null_handling}" if null_handling else ""
    2662        return_type = self.sql(expression, "return_type")
    2663        return_type = f" RETURNING {return_type}" if return_type else ""
    2664        strict = " STRICT" if expression.args.get("strict") else ""
    2665        return self.func(
    2666            "JSON_ARRAYAGG",
    2667            this,
    2668            suffix=f"{order}{null_handling}{return_type}{strict})",
    2669        )

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

    2671    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2672        path = self.sql(expression, "path")
    2673        path = f" PATH {path}" if path else ""
    2674        nested_schema = self.sql(expression, "nested_schema")
    2675
    2676        if nested_schema:
    2677            return f"NESTED{path} {nested_schema}"
    2678
    2679        this = self.sql(expression, "this")
    2680        kind = self.sql(expression, "kind")
    2681        kind = f" {kind}" if kind else ""
    2682        return f"{this}{kind}{path}"

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

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

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

    2687    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    2688        this = self.sql(expression, "this")
    2689        path = self.sql(expression, "path")
    2690        path = f", {path}" if path else ""
    2691        error_handling = expression.args.get("error_handling")
    2692        error_handling = f" {error_handling}" if error_handling else ""
    2693        empty_handling = expression.args.get("empty_handling")
    2694        empty_handling = f" {empty_handling}" if empty_handling else ""
    2695        schema = self.sql(expression, "schema")
    2696        return self.func(
    2697            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    2698        )

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

    2700    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    2701        this = self.sql(expression, "this")
    2702        kind = self.sql(expression, "kind")
    2703        path = self.sql(expression, "path")
    2704        path = f" {path}" if path else ""
    2705        as_json = " AS JSON" if expression.args.get("as_json") else ""
    2706        return f"{this} {kind}{path}{as_json}"

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

    2708    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    2709        this = self.sql(expression, "this")
    2710        path = self.sql(expression, "path")
    2711        path = f", {path}" if path else ""
    2712        expressions = self.expressions(expression)
    2713        with_ = (
    2714            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2715            if expressions
    2716            else ""
    2717        )
    2718        return f"OPENJSON({this}{path}){with_}"

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

    2720    def in_sql(self, expression: exp.In) -> str:
    2721        query = expression.args.get("query")
    2722        unnest = expression.args.get("unnest")
    2723        field = expression.args.get("field")
    2724        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    2725
    2726        if query:
    2727            in_sql = self.sql(query)
    2728        elif unnest:
    2729            in_sql = self.in_unnest_op(unnest)
    2730        elif field:
    2731            in_sql = self.sql(field)
    2732        else:
    2733            in_sql = f"({self.expressions(expression, flat=True)})"
    2734
    2735        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    2740    def interval_sql(self, expression: exp.Interval) -> str:
    2741        unit = self.sql(expression, "unit")
    2742        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    2743            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    2744        unit = f" {unit}" if unit else ""
    2745
    2746        if self.SINGLE_STRING_INTERVAL:
    2747            this = expression.this.name if expression.this else ""
    2748            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    2749
    2750        this = self.sql(expression, "this")
    2751        if this:
    2752            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    2753            this = f" {this}" if unwrapped else f" ({this})"
    2754
    2755        return f"INTERVAL{this}{unit}"

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

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

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

    2760    def reference_sql(self, expression: exp.Reference) -> str:
    2761        this = self.sql(expression, "this")
    2762        expressions = self.expressions(expression, flat=True)
    2763        expressions = f"({expressions})" if expressions else ""
    2764        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2765        options = f" {options}" if options else ""
    2766        return f"REFERENCES {this}{expressions}{options}"

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

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

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

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

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

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

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

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

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

    2784    def alias_sql(self, expression: exp.Alias) -> str:
    2785        alias = self.sql(expression, "alias")
    2786        alias = f" AS {alias}" if alias else ""
    2787        return f"{self.sql(expression, 'this')}{alias}"

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

    2789    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    2790        alias = expression.args["alias"]
    2791        identifier_alias = isinstance(alias, exp.Identifier)
    2792
    2793        if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2794            alias.replace(exp.Literal.string(alias.output_name))
    2795        elif not identifier_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2796            alias.replace(exp.to_identifier(alias.output_name))
    2797
    2798        return self.alias_sql(expression)

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

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

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

    2803    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    2804        this = self.sql(expression, "this")
    2805        index = self.sql(expression, "expression")
    2806        return f"{this} AT {index}"

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

    2808    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    2809        this = self.sql(expression, "this")
    2810        zone = self.sql(expression, "zone")
    2811        return f"{this} AT TIME ZONE {zone}"

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

    2813    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    2814        this = self.sql(expression, "this")
    2815        zone = self.sql(expression, "zone")
    2816        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"

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

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

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

    2821    def and_sql(
    2822        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
    2823    ) -> str:
    2824        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

    2826    def or_sql(
    2827        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
    2828    ) -> str:
    2829        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

    2831    def xor_sql(
    2832        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
    2833    ) -> str:
    2834        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

    2836    def connector_sql(
    2837        self,
    2838        expression: exp.Connector,
    2839        op: str,
    2840        stack: t.Optional[t.List[str | exp.Expression]] = None,
    2841    ) -> str:
    2842        if stack is not None:
    2843            if expression.expressions:
    2844                stack.append(self.expressions(expression, sep=f" {op} "))
    2845            else:
    2846                stack.append(expression.right)
    2847                if expression.comments:
    2848                    for comment in expression.comments:
    2849                        op += f" /*{self.pad_comment(comment)}*/"
    2850                stack.extend((op, expression.left))
    2851            return op
    2852
    2853        stack = [expression]
    2854        sqls: t.List[str] = []
    2855        ops = set()
    2856
    2857        while stack:
    2858            node = stack.pop()
    2859            if isinstance(node, exp.Connector):
    2860                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
    2861            else:
    2862                sql = self.sql(node)
    2863                if sqls and sqls[-1] in ops:
    2864                    sqls[-1] += f" {sql}"
    2865                else:
    2866                    sqls.append(sql)
    2867
    2868        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
    2869        return sep.join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

    2889    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    2890        format_sql = self.sql(expression, "format")
    2891        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    2892        to_sql = self.sql(expression, "to")
    2893        to_sql = f" {to_sql}" if to_sql else ""
    2894        action = self.sql(expression, "action")
    2895        action = f" {action}" if action else ""
    2896        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

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

def currenttimestamp_sql(self, expression: sqlglot.expressions.CurrentTimestamp) -> str: View Source

    2902    def currenttimestamp_sql(self, expression: exp.CurrentTimestamp) -> str:
    2903        return self.func("CURRENT_TIMESTAMP", expression.this)

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

    2905    def collate_sql(self, expression: exp.Collate) -> str:
    2906        if self.COLLATE_IS_FUNC:
    2907            return self.function_fallback_sql(expression)
    2908        return self.binary(expression, "COLLATE")

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

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

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

    2913    def comment_sql(self, expression: exp.Comment) -> str:
    2914        this = self.sql(expression, "this")
    2915        kind = expression.args["kind"]
    2916        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    2917        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    2918        expression_sql = self.sql(expression, "expression")
    2919        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"

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

    2921    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    2922        this = self.sql(expression, "this")
    2923        delete = " DELETE" if expression.args.get("delete") else ""
    2924        recompress = self.sql(expression, "recompress")
    2925        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    2926        to_disk = self.sql(expression, "to_disk")
    2927        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    2928        to_volume = self.sql(expression, "to_volume")
    2929        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    2930        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    2932    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    2933        where = self.sql(expression, "where")
    2934        group = self.sql(expression, "group")
    2935        aggregates = self.expressions(expression, key="aggregates")
    2936        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    2937
    2938        if not (where or group or aggregates) and len(expression.expressions) == 1:
    2939            return f"TTL {self.expressions(expression, flat=True)}"
    2940
    2941        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    2946    def commit_sql(self, expression: exp.Commit) -> str:
    2947        chain = expression.args.get("chain")
    2948        if chain is not None:
    2949            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    2950
    2951        return f"COMMIT{chain or ''}"

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

    2953    def rollback_sql(self, expression: exp.Rollback) -> str:
    2954        savepoint = expression.args.get("savepoint")
    2955        savepoint = f" TO {savepoint}" if savepoint else ""
    2956        return f"ROLLBACK{savepoint}"

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

    2958    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    2959        this = self.sql(expression, "this")
    2960
    2961        dtype = self.sql(expression, "dtype")
    2962        if dtype:
    2963            collate = self.sql(expression, "collate")
    2964            collate = f" COLLATE {collate}" if collate else ""
    2965            using = self.sql(expression, "using")
    2966            using = f" USING {using}" if using else ""
    2967            return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}"
    2968
    2969        default = self.sql(expression, "default")
    2970        if default:
    2971            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    2972
    2973        comment = self.sql(expression, "comment")
    2974        if comment:
    2975            return f"ALTER COLUMN {this} COMMENT {comment}"
    2976
    2977        if not expression.args.get("drop"):
    2978            self.unsupported("Unsupported ALTER COLUMN syntax")
    2979
    2980        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    2982    def renametable_sql(self, expression: exp.RenameTable) -> str:
    2983        if not self.RENAME_TABLE_WITH_DB:
    2984            # Remove db from tables
    2985            expression = expression.transform(
    2986                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    2987            ).assert_is(exp.RenameTable)
    2988        this = self.sql(expression, "this")
    2989        return f"RENAME TO {this}"

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

    2991    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    2992        exists = " IF EXISTS" if expression.args.get("exists") else ""
    2993        old_column = self.sql(expression, "this")
    2994        new_column = self.sql(expression, "to")
    2995        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"

def altertable_sql(self, expression: sqlglot.expressions.AlterTable) -> str: View Source

    2997    def altertable_sql(self, expression: exp.AlterTable) -> str:
    2998        actions = expression.args["actions"]
    2999
    3000        if isinstance(actions[0], exp.ColumnDef):
    3001            actions = self.add_column_sql(expression)
    3002        elif isinstance(actions[0], exp.Schema):
    3003            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    3004        elif isinstance(actions[0], exp.Delete):
    3005            actions = self.expressions(expression, key="actions", flat=True)
    3006        else:
    3007            actions = self.expressions(expression, key="actions", flat=True)
    3008
    3009        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3010        only = " ONLY" if expression.args.get("only") else ""
    3011        options = self.expressions(expression, key="options")
    3012        options = f", {options}" if options else ""
    3013        return f"ALTER TABLE{exists}{only} {self.sql(expression, 'this')} {actions}{options}"

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

    3015    def add_column_sql(self, expression: exp.AlterTable) -> str:
    3016        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    3017            return self.expressions(
    3018                expression,
    3019                key="actions",
    3020                prefix="ADD COLUMN ",
    3021            )
    3022        return f"ADD {self.expressions(expression, key='actions', flat=True)}"

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

    3024    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    3025        expressions = self.expressions(expression)
    3026        exists = " IF EXISTS " if expression.args.get("exists") else " "
    3027        return f"DROP{exists}{expressions}"

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

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

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

    3032    def distinct_sql(self, expression: exp.Distinct) -> str:
    3033        this = self.expressions(expression, flat=True)
    3034
    3035        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    3036            case = exp.case()
    3037            for arg in expression.expressions:
    3038                case = case.when(arg.is_(exp.null()), exp.null())
    3039            this = self.sql(case.else_(f"({this})"))
    3040
    3041        this = f" {this}" if this else ""
    3042
    3043        on = self.sql(expression, "on")
    3044        on = f" ON {on}" if on else ""
    3045        return f"DISTINCT{this}{on}"

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

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

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

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

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

    3053    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    3054        this_sql = self.sql(expression, "this")
    3055        expression_sql = self.sql(expression, "expression")
    3056        kind = "MAX" if expression.args.get("max") else "MIN"
    3057        return f"{this_sql} HAVING {kind} {expression_sql}"

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

    3059    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    3060        return self.sql(
    3061            exp.Cast(
    3062                this=exp.Div(this=expression.this, expression=expression.expression),
    3063                to=exp.DataType(this=exp.DataType.Type.INT),
    3064            )
    3065        )

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

    3067    def dpipe_sql(self, expression: exp.DPipe) -> str:
    3068        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    3069            return self.func(
    3070                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
    3071            )
    3072        return self.binary(expression, "||")

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

    3074    def div_sql(self, expression: exp.Div) -> str:
    3075        l, r = expression.left, expression.right
    3076
    3077        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    3078            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    3079
    3080        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    3081            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
    3082                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    3083
    3084        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    3085            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    3086                return self.sql(
    3087                    exp.cast(
    3088                        l / r,
    3089                        to=exp.DataType.Type.BIGINT,
    3090                    )
    3091                )
    3092
    3093        return self.binary(expression, "/")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3128    def is_sql(self, expression: exp.Is) -> str:
    3129        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3130            return self.sql(
    3131                expression.this if expression.expression.this else exp.not_(expression.this)
    3132            )
    3133        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3174    def try_sql(self, expression: exp.Try) -> str:
    3175        if not self.TRY_SUPPORTED:
    3176            self.unsupported("Unsupported TRY function")
    3177            return self.sql(expression, "this")
    3178
    3179        return self.func("TRY", expression.this)

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

    3181    def log_sql(self, expression: exp.Log) -> str:
    3182        this = expression.this
    3183        expr = expression.expression
    3184
    3185        if self.dialect.LOG_BASE_FIRST is False:
    3186            this, expr = expr, this
    3187        elif self.dialect.LOG_BASE_FIRST is None and expr:
    3188            if this.name in ("2", "10"):
    3189                return self.func(f"LOG{this.name}", expr)
    3190
    3191            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
    3192
    3193        return self.func("LOG", this, expr)

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

    3195    def use_sql(self, expression: exp.Use) -> str:
    3196        kind = self.sql(expression, "kind")
    3197        kind = f" {kind}" if kind else ""
    3198        this = self.sql(expression, "this")
    3199        this = f" {this}" if this else ""
    3200        return f"USE{kind}{this}"

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

    3202    def binary(self, expression: exp.Binary, op: str) -> str:
    3203        op = self.maybe_comment(op, comments=expression.comments)
    3204        return f"{self.sql(expression, 'this')} {op} {self.sql(expression, 'expression')}"

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

    3206    def function_fallback_sql(self, expression: exp.Func) -> str:
    3207        args = []
    3208
    3209        for key in expression.arg_types:
    3210            arg_value = expression.args.get(key)
    3211
    3212            if isinstance(arg_value, list):
    3213                for value in arg_value:
    3214                    args.append(value)
    3215            elif arg_value is not None:
    3216                args.append(arg_value)
    3217
    3218        if self.normalize_functions:
    3219            name = expression.sql_name()
    3220        else:
    3221            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3222
    3223        return self.func(name, *args)

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

    3225    def func(
    3226        self,
    3227        name: str,
    3228        *args: t.Optional[exp.Expression | str],
    3229        prefix: str = "(",
    3230        suffix: str = ")",
    3231    ) -> str:
    3232        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

    3234    def format_args(self, *args: t.Optional[str | exp.Expression]) -> str:
    3235        arg_sqls = tuple(self.sql(arg) for arg in args if arg is not None)
    3236        if self.pretty and self.too_wide(arg_sqls):
    3237            return self.indent("\n" + ",\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True)
    3238        return ", ".join(arg_sqls)

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

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

    3243    def format_time(
    3244        self,
    3245        expression: exp.Expression,
    3246        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
    3247        inverse_time_trie: t.Optional[t.Dict] = None,
    3248    ) -> t.Optional[str]:
    3249        return format_time(
    3250            self.sql(expression, "format"),
    3251            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
    3252            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
    3253        )

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

    3255    def expressions(
    3256        self,
    3257        expression: t.Optional[exp.Expression] = None,
    3258        key: t.Optional[str] = None,
    3259        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    3260        flat: bool = False,
    3261        indent: bool = True,
    3262        skip_first: bool = False,
    3263        skip_last: bool = False,
    3264        sep: str = ", ",
    3265        prefix: str = "",
    3266        dynamic: bool = False,
    3267        new_line: bool = False,
    3268    ) -> str:
    3269        expressions = expression.args.get(key or "expressions") if expression else sqls
    3270
    3271        if not expressions:
    3272            return ""
    3273
    3274        if flat:
    3275            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    3276
    3277        num_sqls = len(expressions)
    3278
    3279        # These are calculated once in case we have the leading_comma / pretty option set, correspondingly
    3280        if self.pretty and not self.leading_comma:
    3281            stripped_sep = sep.strip()
    3282
    3283        result_sqls = []
    3284        for i, e in enumerate(expressions):
    3285            sql = self.sql(e, comment=False)
    3286            if not sql:
    3287                continue
    3288
    3289            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    3290
    3291            if self.pretty:
    3292                if self.leading_comma:
    3293                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
    3294                else:
    3295                    result_sqls.append(
    3296                        f"{prefix}{sql}{stripped_sep if i + 1 < num_sqls else ''}{comments}"
    3297                    )
    3298            else:
    3299                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    3300
    3301        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
    3302            if new_line:
    3303                result_sqls.insert(0, "")
    3304                result_sqls.append("")
    3305            result_sql = "\n".join(result_sqls)
    3306        else:
    3307            result_sql = "".join(result_sqls)
    3308        return (
    3309            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
    3310            if indent
    3311            else result_sql
    3312        )

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

    3314    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3315        flat = flat or isinstance(expression.parent, exp.Properties)
    3316        expressions_sql = self.expressions(expression, flat=flat)
    3317        if flat:
    3318            return f"{op} {expressions_sql}"
    3319        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    3321    def naked_property(self, expression: exp.Property) -> str:
    3322        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3323        if not property_name:
    3324            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3325        return f"{property_name} {self.sql(expression, 'this')}"

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

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

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

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

    3333    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3334        this = self.sql(expression, "this")
    3335        expressions = self.no_identify(self.expressions, expression)
    3336        expressions = (
    3337            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3338        )
    3339        return f"{this}{expressions}"

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

    3341    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3342        this = self.sql(expression, "this")
    3343        expressions = self.expressions(expression, flat=True)
    3344        return f"{this}({expressions})"

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

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

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

    3349    def when_sql(self, expression: exp.When) -> str:
    3350        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3351        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3352        condition = self.sql(expression, "condition")
    3353        condition = f" AND {condition}" if condition else ""
    3354
    3355        then_expression = expression.args.get("then")
    3356        if isinstance(then_expression, exp.Insert):
    3357            this = self.sql(then_expression, "this")
    3358            this = f"INSERT {this}" if this else "INSERT"
    3359            then = self.sql(then_expression, "expression")
    3360            then = f"{this} VALUES {then}" if then else this
    3361        elif isinstance(then_expression, exp.Update):
    3362            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3363                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3364            else:
    3365                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    3366        else:
    3367            then = self.sql(then_expression)
    3368        return f"WHEN {matched}{source}{condition} THEN {then}"

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

    3370    def merge_sql(self, expression: exp.Merge) -> str:
    3371        table = expression.this
    3372        table_alias = ""
    3373
    3374        hints = table.args.get("hints")
    3375        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3376            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3377            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3378
    3379        this = self.sql(table)
    3380        using = f"USING {self.sql(expression, 'using')}"
    3381        on = f"ON {self.sql(expression, 'on')}"
    3382        expressions = self.expressions(expression, sep=" ", indent=False)
    3383        sep = self.sep()
    3384
    3385        return self.prepend_ctes(
    3386            expression, f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{expressions}"
    3387        )

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

    3389    def tochar_sql(self, expression: exp.ToChar) -> str:
    3390        if expression.args.get("format"):
    3391            self.unsupported("Format argument unsupported for TO_CHAR/TO_VARCHAR function")
    3392
    3393        return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT))

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

    3395    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3396        if not self.SUPPORTS_TO_NUMBER:
    3397            self.unsupported("Unsupported TO_NUMBER function")
    3398            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3399
    3400        fmt = expression.args.get("format")
    3401        if not fmt:
    3402            self.unsupported("Conversion format is required for TO_NUMBER")
    3403            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3404
    3405        return self.func("TO_NUMBER", expression.this, fmt)

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

    3407    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3408        this = self.sql(expression, "this")
    3409        kind = self.sql(expression, "kind")
    3410        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3411        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3412        return f"{this}({kind}{args})"

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

    3414    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3415        this = self.sql(expression, "this")
    3416        max = self.sql(expression, "max")
    3417        min = self.sql(expression, "min")
    3418        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

    3426    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3427        expressions = self.expressions(expression, key="expressions", flat=True)
    3428        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3429        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3430        buckets = self.sql(expression, "buckets")
    3431        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    3433    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3434        this = self.sql(expression, "this")
    3435        having = self.sql(expression, "having")
    3436
    3437        if having:
    3438            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3439
    3440        return self.func("ANY_VALUE", this)

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

    3442    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3443        transform = self.func("TRANSFORM", *expression.expressions)
    3444        row_format_before = self.sql(expression, "row_format_before")
    3445        row_format_before = f" {row_format_before}" if row_format_before else ""
    3446        record_writer = self.sql(expression, "record_writer")
    3447        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3448        using = f" USING {self.sql(expression, 'command_script')}"
    3449        schema = self.sql(expression, "schema")
    3450        schema = f" AS {schema}" if schema else ""
    3451        row_format_after = self.sql(expression, "row_format_after")
    3452        row_format_after = f" {row_format_after}" if row_format_after else ""
    3453        record_reader = self.sql(expression, "record_reader")
    3454        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3455        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

    3457    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3458        key_block_size = self.sql(expression, "key_block_size")
    3459        if key_block_size:
    3460            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3461
    3462        using = self.sql(expression, "using")
    3463        if using:
    3464            return f"USING {using}"
    3465
    3466        parser = self.sql(expression, "parser")
    3467        if parser:
    3468            return f"WITH PARSER {parser}"
    3469
    3470        comment = self.sql(expression, "comment")
    3471        if comment:
    3472            return f"COMMENT {comment}"
    3473
    3474        visible = expression.args.get("visible")
    3475        if visible is not None:
    3476            return "VISIBLE" if visible else "INVISIBLE"
    3477
    3478        engine_attr = self.sql(expression, "engine_attr")
    3479        if engine_attr:
    3480            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3481
    3482        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3483        if secondary_engine_attr:
    3484            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3485
    3486        self.unsupported("Unsupported index constraint option.")
    3487        return ""

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

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

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

    3493    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3494        kind = self.sql(expression, "kind")
    3495        kind = f"{kind} INDEX" if kind else "INDEX"
    3496        this = self.sql(expression, "this")
    3497        this = f" {this}" if this else ""
    3498        index_type = self.sql(expression, "index_type")
    3499        index_type = f" USING {index_type}" if index_type else ""
    3500        expressions = self.expressions(expression, flat=True)
    3501        expressions = f" ({expressions})" if expressions else ""
    3502        options = self.expressions(expression, key="options", sep=" ")
    3503        options = f" {options}" if options else ""
    3504        return f"{kind}{this}{index_type}{expressions}{options}"

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

    3506    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3507        if self.NVL2_SUPPORTED:
    3508            return self.function_fallback_sql(expression)
    3509
    3510        case = exp.Case().when(
    3511            expression.this.is_(exp.null()).not_(copy=False),
    3512            expression.args["true"],
    3513            copy=False,
    3514        )
    3515        else_cond = expression.args.get("false")
    3516        if else_cond:
    3517            case.else_(else_cond, copy=False)
    3518
    3519        return self.sql(case)

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

    3521    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3522        this = self.sql(expression, "this")
    3523        expr = self.sql(expression, "expression")
    3524        iterator = self.sql(expression, "iterator")
    3525        condition = self.sql(expression, "condition")
    3526        condition = f" IF {condition}" if condition else ""
    3527        return f"{this} FOR {expr} IN {iterator}{condition}"

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

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

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

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

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

    3535    def predict_sql(self, expression: exp.Predict) -> str:
    3536        model = self.sql(expression, "this")
    3537        model = f"MODEL {model}"
    3538        table = self.sql(expression, "expression")
    3539        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    3540        parameters = self.sql(expression, "params_struct")
    3541        return self.func("PREDICT", model, table, parameters or None)

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

    3543    def forin_sql(self, expression: exp.ForIn) -> str:
    3544        this = self.sql(expression, "this")
    3545        expression_sql = self.sql(expression, "expression")
    3546        return f"FOR {this} DO {expression_sql}"

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

    3548    def refresh_sql(self, expression: exp.Refresh) -> str:
    3549        this = self.sql(expression, "this")
    3550        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    3551        return f"REFRESH {table}{this}"

def operator_sql(self, expression: sqlglot.expressions.Operator) -> str: View Source

    3553    def operator_sql(self, expression: exp.Operator) -> str:
    3554        return self.binary(expression, f"OPERATOR({self.sql(expression, 'operator')})")

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

    3556    def toarray_sql(self, expression: exp.ToArray) -> str:
    3557        arg = expression.this
    3558        if not arg.type:
    3559            from sqlglot.optimizer.annotate_types import annotate_types
    3560
    3561            arg = annotate_types(arg)
    3562
    3563        if arg.is_type(exp.DataType.Type.ARRAY):
    3564            return self.sql(arg)
    3565
    3566        cond_for_null = arg.is_(exp.null())
    3567        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

    3569    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    3570        this = expression.this
    3571        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    3572            return self.sql(this)
    3573
    3574        return self.sql(exp.cast(this, exp.DataType.Type.TIME))

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

    3576    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
    3577        this = expression.this
    3578        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
    3579            return self.sql(this)
    3580
    3581        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP))

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

    3583    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    3584        this = expression.this
    3585        time_format = self.format_time(expression)
    3586
    3587        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    3588            return self.sql(
    3589                exp.cast(
    3590                    exp.StrToTime(this=this, format=expression.args["format"]),
    3591                    exp.DataType.Type.DATE,
    3592                )
    3593            )
    3594
    3595        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    3596            return self.sql(this)
    3597
    3598        return self.sql(exp.cast(this, exp.DataType.Type.DATE))

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

    3600    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    3601        return self.sql(
    3602            exp.func(
    3603                "DATEDIFF",
    3604                expression.this,
    3605                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
    3606                "day",
    3607            )
    3608        )

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

    3610    def lastday_sql(self, expression: exp.LastDay) -> str:
    3611        if self.LAST_DAY_SUPPORTS_DATE_PART:
    3612            return self.function_fallback_sql(expression)
    3613
    3614        unit = expression.text("unit")
    3615        if unit and unit != "MONTH":
    3616            self.unsupported("Date parts are not supported in LAST_DAY.")
    3617
    3618        return self.func("LAST_DAY", expression.this)

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

    3620    def dateadd_sql(self, expression: exp.DateAdd) -> str:
    3621        from sqlglot.dialects.dialect import unit_to_str
    3622
    3623        return self.func(
    3624            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
    3625        )

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

    3627    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    3628        if self.CAN_IMPLEMENT_ARRAY_ANY:
    3629            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    3630            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    3631            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    3632            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    3633
    3634        from sqlglot.dialects import Dialect
    3635
    3636        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    3637        if self.dialect.__class__ != Dialect:
    3638            self.unsupported("ARRAY_ANY is unsupported")
    3639
    3640        return self.function_fallback_sql(expression)

def generateseries_sql(self, expression: sqlglot.expressions.GenerateSeries) -> str: View Source

    3642    def generateseries_sql(self, expression: exp.GenerateSeries) -> str:
    3643        expression.set("is_end_exclusive", None)
    3644        return self.function_fallback_sql(expression)

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

    3646    def struct_sql(self, expression: exp.Struct) -> str:
    3647        expression.set(
    3648            "expressions",
    3649            [
    3650                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    3651                if isinstance(e, exp.PropertyEQ)
    3652                else e
    3653                for e in expression.expressions
    3654            ],
    3655        )
    3656
    3657        return self.function_fallback_sql(expression)

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

    3659    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    3660        low = self.sql(expression, "this")
    3661        high = self.sql(expression, "expression")
    3662
    3663        return f"{low} TO {high}"

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

    3665    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    3666        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    3667        tables = f" {self.expressions(expression)}"
    3668
    3669        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3670
    3671        on_cluster = self.sql(expression, "cluster")
    3672        on_cluster = f" {on_cluster}" if on_cluster else ""
    3673
    3674        identity = self.sql(expression, "identity")
    3675        identity = f" {identity} IDENTITY" if identity else ""
    3676
    3677        option = self.sql(expression, "option")
    3678        option = f" {option}" if option else ""
    3679
    3680        partition = self.sql(expression, "partition")
    3681        partition = f" {partition}" if partition else ""
    3682
    3683        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"

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

    3687    def convert_sql(self, expression: exp.Convert) -> str:
    3688        to = expression.this
    3689        value = expression.expression
    3690        style = expression.args.get("style")
    3691        safe = expression.args.get("safe")
    3692        strict = expression.args.get("strict")
    3693
    3694        if not to or not value:
    3695            return ""
    3696
    3697        # Retrieve length of datatype and override to default if not specified
    3698        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3699            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    3700
    3701        transformed: t.Optional[exp.Expression] = None
    3702        cast = exp.Cast if strict else exp.TryCast
    3703
    3704        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
    3705        if isinstance(style, exp.Literal) and style.is_int:
    3706            from sqlglot.dialects.tsql import TSQL
    3707
    3708            style_value = style.name
    3709            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
    3710            if not converted_style:
    3711                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
    3712
    3713            fmt = exp.Literal.string(converted_style)
    3714
    3715            if to.this == exp.DataType.Type.DATE:
    3716                transformed = exp.StrToDate(this=value, format=fmt)
    3717            elif to.this == exp.DataType.Type.DATETIME:
    3718                transformed = exp.StrToTime(this=value, format=fmt)
    3719            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3720                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
    3721            elif to.this == exp.DataType.Type.TEXT:
    3722                transformed = exp.TimeToStr(this=value, format=fmt)
    3723
    3724        if not transformed:
    3725            transformed = cast(this=value, to=to, safe=safe)
    3726
    3727        return self.sql(transformed)

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

    3783    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
    3784        option = self.sql(expression, "this")
    3785        value = self.sql(expression, "expression")
    3786
    3787        if not value:
    3788            return option
    3789
    3790        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
    3791
    3792        return f"{option}{op}{value}"

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

    3794    def credentials_sql(self, expression: exp.Credentials) -> str:
    3795        cred_expr = expression.args.get("credentials")
    3796        if isinstance(cred_expr, exp.Literal):
    3797            # Redshift case: CREDENTIALS <string>
    3798            credentials = self.sql(expression, "credentials")
    3799            credentials = f"CREDENTIALS {credentials}"
    3800        else:
    3801            # Snowflake case: CREDENTIALS = (...)
    3802            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
    3803            credentials = f"CREDENTIALS = ({credentials})" if credentials else ""
    3804
    3805        storage = self.sql(expression, "storage")
    3806        storage = f" {storage}" if storage else ""
    3807
    3808        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
    3809        encryption = f"ENCRYPTION = ({encryption})" if encryption else ""
    3810
    3811        iam_role = self.sql(expression, "iam_role")
    3812        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
    3813
    3814        region = self.sql(expression, "region")
    3815        region = f" REGION {region}" if region else ""
    3816
    3817        return f"{credentials}{storage}{encryption}{iam_role}{region}"

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

    3819    def copy_sql(self, expression: exp.Copy) -> str:
    3820        this = self.sql(expression, "this")
    3821        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
    3822
    3823        credentials = self.sql(expression, "credentials")
    3824        credentials = f" {credentials}" if credentials else ""
    3825
    3826        kind = " FROM " if expression.args.get("kind") else " TO "
    3827        files = self.expressions(expression, key="files", flat=True)
    3828
    3829        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
    3830        params = self.expressions(expression, key="params", flat=True, sep=sep)
    3831        if params:
    3832            params = f" WITH ({params})" if self.COPY_PARAMS_ARE_WRAPPED else f" {params}"
    3833
    3834        return f"COPY{this}{kind}{files}{credentials}{params}"