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

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

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

    527    def __init__(
    528        self,
    529        pretty: t.Optional[bool] = None,
    530        identify: str | bool = False,
    531        normalize: bool = False,
    532        pad: int = 2,
    533        indent: int = 2,
    534        normalize_functions: t.Optional[str | bool] = None,
    535        unsupported_level: ErrorLevel = ErrorLevel.WARN,
    536        max_unsupported: int = 3,
    537        leading_comma: bool = False,
    538        max_text_width: int = 80,
    539        comments: bool = True,
    540        dialect: DialectType = None,
    541    ):
    542        import sqlglot
    543        from sqlglot.dialects import Dialect
    544
    545        self.pretty = pretty if pretty is not None else sqlglot.pretty
    546        self.identify = identify
    547        self.normalize = normalize
    548        self.pad = pad
    549        self._indent = indent
    550        self.unsupported_level = unsupported_level
    551        self.max_unsupported = max_unsupported
    552        self.leading_comma = leading_comma
    553        self.max_text_width = max_text_width
    554        self.comments = comments
    555        self.dialect = Dialect.get_or_raise(dialect)
    556
    557        # This is both a Dialect property and a Generator argument, so we prioritize the latter
    558        self.normalize_functions = (
    559            self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
    560        )
    561
    562        self.unsupported_messages: t.List[str] = []
    563        self._escaped_quote_end: str = (
    564            self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END
    565        )
    566        self._escaped_identifier_end: str = (
    567            self.dialect.tokenizer_class.IDENTIFIER_ESCAPES[0] + self.dialect.IDENTIFIER_END
    568        )

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.DateAdd'>: <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.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.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.JSONPathSelector'>, <class 'sqlglot.expressions.JSONPathSlice'>, <class 'sqlglot.expressions.JSONPathScript'>, <class 'sqlglot.expressions.JSONPathRoot'>, <class 'sqlglot.expressions.JSONPathRecursive'>, <class 'sqlglot.expressions.JSONPathKey'>, <class 'sqlglot.expressions.JSONPathWildcard'>, <class 'sqlglot.expressions.JSONPathFilter'>, <class 'sqlglot.expressions.JSONPathUnion'>, <class 'sqlglot.expressions.JSONPathSubscript'>}
CAN_IMPLEMENT_ARRAY_ANY = False
SUPPORTS_TO_NUMBER = 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'}
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.CHAR: 'CHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.VARCHAR: 'VARCHAR'>}
EXPRESSIONS_WITHOUT_NESTED_CTES: Set[Type[sqlglot.expressions.Expression]] = set()
SENTINEL_LINE_BREAK = '__SQLGLOT__LB__'
pretty
identify
normalize
pad
unsupported_level
max_unsupported
leading_comma
max_text_width
comments
dialect
normalize_functions
unsupported_messages: List[str]
def generate( self, expression: sqlglot.expressions.Expression, copy: bool = True) -> str: View Source

    570    def generate(self, expression: exp.Expression, copy: bool = True) -> str:
    571        """
    572        Generates the SQL string corresponding to the given syntax tree.
    573
    574        Args:
    575            expression: The syntax tree.
    576            copy: Whether to copy the expression. The generator performs mutations so
    577                it is safer to copy.
    578
    579        Returns:
    580            The SQL string corresponding to `expression`.
    581        """
    582        if copy:
    583            expression = expression.copy()
    584
    585        expression = self.preprocess(expression)
    586
    587        self.unsupported_messages = []
    588        sql = self.sql(expression).strip()
    589
    590        if self.pretty:
    591            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
    592
    593        if self.unsupported_level == ErrorLevel.IGNORE:
    594            return sql
    595
    596        if self.unsupported_level == ErrorLevel.WARN:
    597            for msg in self.unsupported_messages:
    598                logger.warning(msg)
    599        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
    600            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
    601
    602        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

    604    def preprocess(self, expression: exp.Expression) -> exp.Expression:
    605        """Apply generic preprocessing transformations to a given expression."""
    606        if (
    607            not expression.parent
    608            and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES
    609            and any(node.parent is not expression for node in expression.find_all(exp.With))
    610        ):
    611            from sqlglot.transforms import move_ctes_to_top_level
    612
    613            expression = move_ctes_to_top_level(expression)
    614
    615        if self.ENSURE_BOOLS:
    616            from sqlglot.transforms import ensure_bools
    617
    618            expression = ensure_bools(expression)
    619
    620        return expression

Apply generic preprocessing transformations to a given expression.

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

    622    def unsupported(self, message: str) -> None:
    623        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    624            raise UnsupportedError(message)
    625        self.unsupported_messages.append(message)

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

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

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

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

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

    633    def pad_comment(self, comment: str) -> str:
    634        comment = " " + comment if comment[0].strip() else comment
    635        comment = comment + " " if comment[-1].strip() else comment
    636        return comment

def maybe_comment( self, sql: str, expression: Optional[sqlglot.expressions.Expression] = None, comments: Optional[List[str]] = None) -> str: View Source

    638    def maybe_comment(
    639        self,
    640        sql: str,
    641        expression: t.Optional[exp.Expression] = None,
    642        comments: t.Optional[t.List[str]] = None,
    643    ) -> str:
    644        comments = (
    645            ((expression and expression.comments) if comments is None else comments)  # type: ignore
    646            if self.comments
    647            else None
    648        )
    649
    650        if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
    651            return sql
    652
    653        comments_sql = " ".join(
    654            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
    655        )
    656
    657        if not comments_sql:
    658            return sql
    659
    660        if isinstance(expression, self.WITH_SEPARATED_COMMENTS):
    661            return (
    662                f"{self.sep()}{comments_sql}{sql}"
    663                if sql[0].isspace()
    664                else f"{comments_sql}{self.sep()}{sql}"
    665            )
    666
    667        return f"{sql} {comments_sql}"

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

    669    def wrap(self, expression: exp.Expression | str) -> str:
    670        this_sql = self.indent(
    671            (
    672                self.sql(expression)
    673                if isinstance(expression, exp.UNWRAPPED_QUERIES)
    674                else self.sql(expression, "this")
    675            ),
    676            level=1,
    677            pad=0,
    678        )
    679        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"

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

    681    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    682        original = self.identify
    683        self.identify = False
    684        result = func(*args, **kwargs)
    685        self.identify = original
    686        return result

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

    688    def normalize_func(self, name: str) -> str:
    689        if self.normalize_functions == "upper" or self.normalize_functions is True:
    690            return name.upper()
    691        if self.normalize_functions == "lower":
    692            return name.lower()
    693        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

    695    def indent(
    696        self,
    697        sql: str,
    698        level: int = 0,
    699        pad: t.Optional[int] = None,
    700        skip_first: bool = False,
    701        skip_last: bool = False,
    702    ) -> str:
    703        if not self.pretty:
    704            return sql
    705
    706        pad = self.pad if pad is None else pad
    707        lines = sql.split("\n")
    708
    709        return "\n".join(
    710            (
    711                line
    712                if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
    713                else f"{' ' * (level * self._indent + pad)}{line}"
    714            )
    715            for i, line in enumerate(lines)
    716        )

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

    718    def sql(
    719        self,
    720        expression: t.Optional[str | exp.Expression],
    721        key: t.Optional[str] = None,
    722        comment: bool = True,
    723    ) -> str:
    724        if not expression:
    725            return ""
    726
    727        if isinstance(expression, str):
    728            return expression
    729
    730        if key:
    731            value = expression.args.get(key)
    732            if value:
    733                return self.sql(value)
    734            return ""
    735
    736        transform = self.TRANSFORMS.get(expression.__class__)
    737
    738        if callable(transform):
    739            sql = transform(self, expression)
    740        elif isinstance(expression, exp.Expression):
    741            exp_handler_name = f"{expression.key}_sql"
    742
    743            if hasattr(self, exp_handler_name):
    744                sql = getattr(self, exp_handler_name)(expression)
    745            elif isinstance(expression, exp.Func):
    746                sql = self.function_fallback_sql(expression)
    747            elif isinstance(expression, exp.Property):
    748                sql = self.property_sql(expression)
    749            else:
    750                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
    751        else:
    752            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
    753
    754        return self.maybe_comment(sql, expression) if self.comments and comment else sql

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

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

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

    761    def cache_sql(self, expression: exp.Cache) -> str:
    762        lazy = " LAZY" if expression.args.get("lazy") else ""
    763        table = self.sql(expression, "this")
    764        options = expression.args.get("options")
    765        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
    766        sql = self.sql(expression, "expression")
    767        sql = f" AS{self.sep()}{sql}" if sql else ""
    768        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
    769        return self.prepend_ctes(expression, sql)

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

    771    def characterset_sql(self, expression: exp.CharacterSet) -> str:
    772        if isinstance(expression.parent, exp.Cast):
    773            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
    774        default = "DEFAULT " if expression.args.get("default") else ""
    775        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"

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

    777    def column_sql(self, expression: exp.Column) -> str:
    778        join_mark = " (+)" if expression.args.get("join_mark") else ""
    779
    780        if join_mark and not self.COLUMN_JOIN_MARKS_SUPPORTED:
    781            join_mark = ""
    782            self.unsupported("Outer join syntax using the (+) operator is not supported.")
    783
    784        column = ".".join(
    785            self.sql(part)
    786            for part in (
    787                expression.args.get("catalog"),
    788                expression.args.get("db"),
    789                expression.args.get("table"),
    790                expression.args.get("this"),
    791            )
    792            if part
    793        )
    794
    795        return f"{column}{join_mark}"

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

    797    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    798        this = self.sql(expression, "this")
    799        this = f" {this}" if this else ""
    800        position = self.sql(expression, "position")
    801        return f"{position}{this}"

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

    803    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
    804        column = self.sql(expression, "this")
    805        kind = self.sql(expression, "kind")
    806        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
    807        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
    808        kind = f"{sep}{kind}" if kind else ""
    809        constraints = f" {constraints}" if constraints else ""
    810        position = self.sql(expression, "position")
    811        position = f" {position}" if position else ""
    812
    813        if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:
    814            kind = ""
    815
    816        return f"{exists}{column}{kind}{constraints}{position}"

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

    818    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    819        this = self.sql(expression, "this")
    820        kind_sql = self.sql(expression, "kind").strip()
    821        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

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

    823    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
    824        this = self.sql(expression, "this")
    825        if expression.args.get("not_null"):
    826            persisted = " PERSISTED NOT NULL"
    827        elif expression.args.get("persisted"):
    828            persisted = " PERSISTED"
    829        else:
    830            persisted = ""
    831        return f"AS {this}{persisted}"

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

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

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

    836    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
    837        if isinstance(expression.this, list):
    838            this = self.wrap(self.expressions(expression, key="this", flat=True))
    839        else:
    840            this = self.sql(expression, "this")
    841
    842        return f"COMPRESS {this}"

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

    844    def generatedasidentitycolumnconstraint_sql(
    845        self, expression: exp.GeneratedAsIdentityColumnConstraint
    846    ) -> str:
    847        this = ""
    848        if expression.this is not None:
    849            on_null = " ON NULL" if expression.args.get("on_null") else ""
    850            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
    851
    852        start = expression.args.get("start")
    853        start = f"START WITH {start}" if start else ""
    854        increment = expression.args.get("increment")
    855        increment = f" INCREMENT BY {increment}" if increment else ""
    856        minvalue = expression.args.get("minvalue")
    857        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    858        maxvalue = expression.args.get("maxvalue")
    859        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    860        cycle = expression.args.get("cycle")
    861        cycle_sql = ""
    862
    863        if cycle is not None:
    864            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
    865            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
    866
    867        sequence_opts = ""
    868        if start or increment or cycle_sql:
    869            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
    870            sequence_opts = f" ({sequence_opts.strip()})"
    871
    872        expr = self.sql(expression, "expression")
    873        expr = f"({expr})" if expr else "IDENTITY"
    874
    875        return f"GENERATED{this} AS {expr}{sequence_opts}"

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

    877    def generatedasrowcolumnconstraint_sql(
    878        self, expression: exp.GeneratedAsRowColumnConstraint
    879    ) -> str:
    880        start = "START" if expression.args.get("start") else "END"
    881        hidden = " HIDDEN" if expression.args.get("hidden") else ""
    882        return f"GENERATED ALWAYS AS ROW {start}{hidden}"

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

    884    def periodforsystemtimeconstraint_sql(
    885        self, expression: exp.PeriodForSystemTimeConstraint
    886    ) -> str:
    887        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

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

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

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

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

    895    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    896        desc = expression.args.get("desc")
    897        if desc is not None:
    898            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    899        return "PRIMARY KEY"

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

    901    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    902        this = self.sql(expression, "this")
    903        this = f" {this}" if this else ""
    904        index_type = expression.args.get("index_type")
    905        index_type = f" USING {index_type}" if index_type else ""
    906        on_conflict = self.sql(expression, "on_conflict")
    907        on_conflict = f" {on_conflict}" if on_conflict else ""
    908        return f"UNIQUE{this}{index_type}{on_conflict}"

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

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

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

    913    def create_sql(self, expression: exp.Create) -> str:
    914        kind = self.sql(expression, "kind")
    915        properties = expression.args.get("properties")
    916        properties_locs = self.locate_properties(properties) if properties else defaultdict()
    917
    918        this = self.createable_sql(expression, properties_locs)
    919
    920        properties_sql = ""
    921        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
    922            exp.Properties.Location.POST_WITH
    923        ):
    924            properties_sql = self.sql(
    925                exp.Properties(
    926                    expressions=[
    927                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
    928                        *properties_locs[exp.Properties.Location.POST_WITH],
    929                    ]
    930                )
    931            )
    932
    933        begin = " BEGIN" if expression.args.get("begin") else ""
    934        end = " END" if expression.args.get("end") else ""
    935
    936        expression_sql = self.sql(expression, "expression")
    937        if expression_sql:
    938            expression_sql = f"{begin}{self.sep()}{expression_sql}{end}"
    939
    940            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
    941                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
    942                    postalias_props_sql = self.properties(
    943                        exp.Properties(
    944                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
    945                        ),
    946                        wrapped=False,
    947                    )
    948                    expression_sql = f" AS {postalias_props_sql}{expression_sql}"
    949                else:
    950                    expression_sql = f" AS{expression_sql}"
    951
    952        postindex_props_sql = ""
    953        if properties_locs.get(exp.Properties.Location.POST_INDEX):
    954            postindex_props_sql = self.properties(
    955                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
    956                wrapped=False,
    957                prefix=" ",
    958            )
    959
    960        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
    961        indexes = f" {indexes}" if indexes else ""
    962        index_sql = indexes + postindex_props_sql
    963
    964        replace = " OR REPLACE" if expression.args.get("replace") else ""
    965        unique = " UNIQUE" if expression.args.get("unique") else ""
    966
    967        postcreate_props_sql = ""
    968        if properties_locs.get(exp.Properties.Location.POST_CREATE):
    969            postcreate_props_sql = self.properties(
    970                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
    971                sep=" ",
    972                prefix=" ",
    973                wrapped=False,
    974            )
    975
    976        modifiers = "".join((replace, unique, postcreate_props_sql))
    977
    978        postexpression_props_sql = ""
    979        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
    980            postexpression_props_sql = self.properties(
    981                exp.Properties(
    982                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
    983                ),
    984                sep=" ",
    985                prefix=" ",
    986                wrapped=False,
    987            )
    988
    989        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    990        no_schema_binding = (
    991            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
    992        )
    993
    994        clone = self.sql(expression, "clone")
    995        clone = f" {clone}" if clone else ""
    996
    997        expression_sql = f"CREATE{modifiers} {kind}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
    998        return self.prepend_ctes(expression, expression_sql)

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

    1000    def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str:
    1001        start = self.sql(expression, "start")
    1002        start = f"START WITH {start}" if start else ""
    1003        increment = self.sql(expression, "increment")
    1004        increment = f" INCREMENT BY {increment}" if increment else ""
    1005        minvalue = self.sql(expression, "minvalue")
    1006        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    1007        maxvalue = self.sql(expression, "maxvalue")
    1008        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    1009        owned = self.sql(expression, "owned")
    1010        owned = f" OWNED BY {owned}" if owned else ""
    1011
    1012        cache = expression.args.get("cache")
    1013        if cache is None:
    1014            cache_str = ""
    1015        elif cache is True:
    1016            cache_str = " CACHE"
    1017        else:
    1018            cache_str = f" CACHE {cache}"
    1019
    1020        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1021        options = f" {options}" if options else ""
    1022
    1023        return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()

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

    1025    def clone_sql(self, expression: exp.Clone) -> str:
    1026        this = self.sql(expression, "this")
    1027        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    1028        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
    1029        return f"{shallow}{keyword} {this}"

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

    1031    def describe_sql(self, expression: exp.Describe) -> str:
    1032        extended = " EXTENDED" if expression.args.get("extended") else ""
    1033        return f"DESCRIBE{extended} {self.sql(expression, 'this')}"

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

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

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

    1039    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    1040        with_ = self.sql(expression, "with")
    1041        if with_:
    1042            sql = f"{with_}{self.sep()}{sql}"
    1043        return sql

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

    1045    def with_sql(self, expression: exp.With) -> str:
    1046        sql = self.expressions(expression, flat=True)
    1047        recursive = (
    1048            "RECURSIVE "
    1049            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
    1050            else ""
    1051        )
    1052
    1053        return f"WITH {recursive}{sql}"

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

    1055    def cte_sql(self, expression: exp.CTE) -> str:
    1056        alias = self.sql(expression, "alias")
    1057
    1058        materialized = expression.args.get("materialized")
    1059        if materialized is False:
    1060            materialized = "NOT MATERIALIZED "
    1061        elif materialized:
    1062            materialized = "MATERIALIZED "
    1063
    1064        return f"{alias} AS {materialized or ''}{self.wrap(expression)}"

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

    1066    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    1067        alias = self.sql(expression, "this")
    1068        columns = self.expressions(expression, key="columns", flat=True)
    1069        columns = f"({columns})" if columns else ""
    1070
    1071        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
    1072            columns = ""
    1073            self.unsupported("Named columns are not supported in table alias.")
    1074
    1075        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
    1076            alias = "_t"
    1077
    1078        return f"{alias}{columns}"

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

    1080    def bitstring_sql(self, expression: exp.BitString) -> str:
    1081        this = self.sql(expression, "this")
    1082        if self.dialect.BIT_START:
    1083            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    1084        return f"{int(this, 2)}"

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

    1086    def hexstring_sql(self, expression: exp.HexString) -> str:
    1087        this = self.sql(expression, "this")
    1088        if self.dialect.HEX_START:
    1089            return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
    1090        return f"{int(this, 16)}"

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

    1092    def bytestring_sql(self, expression: exp.ByteString) -> str:
    1093        this = self.sql(expression, "this")
    1094        if self.dialect.BYTE_START:
    1095            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    1096        return this

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

    1098    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
    1099        this = self.sql(expression, "this")
    1100        escape = expression.args.get("escape")
    1101
    1102        if self.dialect.UNICODE_START:
    1103            escape = f" UESCAPE {self.sql(escape)}" if escape else ""
    1104            return f"{self.dialect.UNICODE_START}{this}{self.dialect.UNICODE_END}{escape}"
    1105
    1106        if escape:
    1107            pattern = re.compile(rf"{escape.name}(\d+)")
    1108        else:
    1109            pattern = ESCAPED_UNICODE_RE
    1110
    1111        this = pattern.sub(r"\\u\1", this)
    1112        return f"{self.dialect.QUOTE_START}{this}{self.dialect.QUOTE_END}"

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

    1114    def rawstring_sql(self, expression: exp.RawString) -> str:
    1115        string = self.escape_str(expression.this.replace("\\", "\\\\"))
    1116        return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}"

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

    1118    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    1119        this = self.sql(expression, "this")
    1120        specifier = self.sql(expression, "expression")
    1121        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    1122        return f"{this}{specifier}"

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

    1124    def datatype_sql(self, expression: exp.DataType) -> str:
    1125        type_value = expression.this
    1126
    1127        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
    1128            type_sql = self.sql(expression, "kind")
    1129        else:
    1130            type_sql = (
    1131                self.TYPE_MAPPING.get(type_value, type_value.value)
    1132                if isinstance(type_value, exp.DataType.Type)
    1133                else type_value
    1134            )
    1135
    1136        nested = ""
    1137        interior = self.expressions(expression, flat=True)
    1138        values = ""
    1139
    1140        if interior:
    1141            if expression.args.get("nested"):
    1142                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    1143                if expression.args.get("values") is not None:
    1144                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    1145                    values = self.expressions(expression, key="values", flat=True)
    1146                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    1147            elif type_value == exp.DataType.Type.INTERVAL:
    1148                nested = f" {interior}"
    1149            else:
    1150                nested = f"({interior})"
    1151
    1152        type_sql = f"{type_sql}{nested}{values}"
    1153        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
    1154            exp.DataType.Type.TIMETZ,
    1155            exp.DataType.Type.TIMESTAMPTZ,
    1156        ):
    1157            type_sql = f"{type_sql} WITH TIME ZONE"
    1158
    1159        return type_sql

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

    1161    def directory_sql(self, expression: exp.Directory) -> str:
    1162        local = "LOCAL " if expression.args.get("local") else ""
    1163        row_format = self.sql(expression, "row_format")
    1164        row_format = f" {row_format}" if row_format else ""
    1165        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

    1167    def delete_sql(self, expression: exp.Delete) -> str:
    1168        this = self.sql(expression, "this")
    1169        this = f" FROM {this}" if this else ""
    1170        using = self.sql(expression, "using")
    1171        using = f" USING {using}" if using else ""
    1172        where = self.sql(expression, "where")
    1173        returning = self.sql(expression, "returning")
    1174        limit = self.sql(expression, "limit")
    1175        tables = self.expressions(expression, key="tables")
    1176        tables = f" {tables}" if tables else ""
    1177        if self.RETURNING_END:
    1178            expression_sql = f"{this}{using}{where}{returning}{limit}"
    1179        else:
    1180            expression_sql = f"{returning}{this}{using}{where}{limit}"
    1181        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

    1183    def drop_sql(self, expression: exp.Drop) -> str:
    1184        this = self.sql(expression, "this")
    1185        expressions = self.expressions(expression, flat=True)
    1186        expressions = f" ({expressions})" if expressions else ""
    1187        kind = expression.args["kind"]
    1188        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    1189        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1190        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    1191        cascade = " CASCADE" if expression.args.get("cascade") else ""
    1192        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    1193        purge = " PURGE" if expression.args.get("purge") else ""
    1194        return f"DROP{temporary}{materialized} {kind}{exists_sql}{this}{expressions}{cascade}{constraints}{purge}"

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

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

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

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

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

    1202    def fetch_sql(self, expression: exp.Fetch) -> str:
    1203        direction = expression.args.get("direction")
    1204        direction = f" {direction}" if direction else ""
    1205        count = expression.args.get("count")
    1206        count = f" {count}" if count else ""
    1207        if expression.args.get("percent"):
    1208            count = f"{count} PERCENT"
    1209        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    1210        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"

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

    1212    def filter_sql(self, expression: exp.Filter) -> str:
    1213        if self.AGGREGATE_FILTER_SUPPORTED:
    1214            this = self.sql(expression, "this")
    1215            where = self.sql(expression, "expression").strip()
    1216            return f"{this} FILTER({where})"
    1217
    1218        agg = expression.this
    1219        agg_arg = agg.this
    1220        cond = expression.expression.this
    1221        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1222        return self.sql(agg)

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

    1224    def hint_sql(self, expression: exp.Hint) -> str:
    1225        if not self.QUERY_HINTS:
    1226            self.unsupported("Hints are not supported")
    1227            return ""
    1228
    1229        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

    1231    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
    1232        using = self.sql(expression, "using")
    1233        using = f" USING {using}" if using else ""
    1234        columns = self.expressions(expression, key="columns", flat=True)
    1235        columns = f"({columns})" if columns else ""
    1236        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1237        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1238        where = self.sql(expression, "where")
    1239        include = self.expressions(expression, key="include", flat=True)
    1240        if include:
    1241            include = f" INCLUDE ({include})"
    1242        with_storage = self.expressions(expression, key="with_storage", flat=True)
    1243        with_storage = f" WITH ({with_storage})" if with_storage else ""
    1244        tablespace = self.sql(expression, "tablespace")
    1245        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
    1246
    1247        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}"

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

    1249    def index_sql(self, expression: exp.Index) -> str:
    1250        unique = "UNIQUE " if expression.args.get("unique") else ""
    1251        primary = "PRIMARY " if expression.args.get("primary") else ""
    1252        amp = "AMP " if expression.args.get("amp") else ""
    1253        name = self.sql(expression, "this")
    1254        name = f"{name} " if name else ""
    1255        table = self.sql(expression, "table")
    1256        table = f"{self.INDEX_ON} {table}" if table else ""
    1257
    1258        index = "INDEX " if not table else ""
    1259
    1260        params = self.sql(expression, "params")
    1261        return f"{unique}{primary}{amp}{index}{name}{table}{params}"

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

    1263    def identifier_sql(self, expression: exp.Identifier) -> str:
    1264        text = expression.name
    1265        lower = text.lower()
    1266        text = lower if self.normalize and not expression.quoted else text
    1267        text = text.replace(self.dialect.IDENTIFIER_END, self._escaped_identifier_end)
    1268        if (
    1269            expression.quoted
    1270            or self.dialect.can_identify(text, self.identify)
    1271            or lower in self.RESERVED_KEYWORDS
    1272            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1273        ):
    1274            text = f"{self.dialect.IDENTIFIER_START}{text}{self.dialect.IDENTIFIER_END}"
    1275        return text

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

    1277    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1278        input_format = self.sql(expression, "input_format")
    1279        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1280        output_format = self.sql(expression, "output_format")
    1281        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1282        return self.sep().join((input_format, output_format))

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

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

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

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

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

    1291    def properties_sql(self, expression: exp.Properties) -> str:
    1292        root_properties = []
    1293        with_properties = []
    1294
    1295        for p in expression.expressions:
    1296            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1297            if p_loc == exp.Properties.Location.POST_WITH:
    1298                with_properties.append(p)
    1299            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1300                root_properties.append(p)
    1301
    1302        return self.root_properties(
    1303            exp.Properties(expressions=root_properties)
    1304        ) + self.with_properties(exp.Properties(expressions=with_properties))

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

    1306    def root_properties(self, properties: exp.Properties) -> str:
    1307        if properties.expressions:
    1308            return self.sep() + self.expressions(properties, indent=False, sep=" ")
    1309        return ""

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

    1311    def properties(
    1312        self,
    1313        properties: exp.Properties,
    1314        prefix: str = "",
    1315        sep: str = ", ",
    1316        suffix: str = "",
    1317        wrapped: bool = True,
    1318    ) -> str:
    1319        if properties.expressions:
    1320            expressions = self.expressions(properties, sep=sep, indent=False)
    1321            if expressions:
    1322                expressions = self.wrap(expressions) if wrapped else expressions
    1323                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1324        return ""

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

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

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

    1329    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1330        properties_locs = defaultdict(list)
    1331        for p in properties.expressions:
    1332            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1333            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1334                properties_locs[p_loc].append(p)
    1335            else:
    1336                self.unsupported(f"Unsupported property {p.key}")
    1337
    1338        return properties_locs

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

    1340    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1341        if isinstance(expression.this, exp.Dot):
    1342            return self.sql(expression, "this")
    1343        return f"'{expression.name}'" if string_key else expression.name

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

    1345    def property_sql(self, expression: exp.Property) -> str:
    1346        property_cls = expression.__class__
    1347        if property_cls == exp.Property:
    1348            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1349
    1350        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1351        if not property_name:
    1352            self.unsupported(f"Unsupported property {expression.key}")
    1353
    1354        return f"{property_name}={self.sql(expression, 'this')}"

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

    1356    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1357        if self.SUPPORTS_CREATE_TABLE_LIKE:
    1358            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1359            options = f" {options}" if options else ""
    1360
    1361            like = f"LIKE {self.sql(expression, 'this')}{options}"
    1362            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
    1363                like = f"({like})"
    1364
    1365            return like
    1366
    1367        if expression.expressions:
    1368            self.unsupported("Transpilation of LIKE property options is unsupported")
    1369
    1370        select = exp.select("*").from_(expression.this).limit(0)
    1371        return f"AS {self.sql(select)}"

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

    1373    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1374        no = "NO " if expression.args.get("no") else ""
    1375        protection = " PROTECTION" if expression.args.get("protection") else ""
    1376        return f"{no}FALLBACK{protection}"

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

    1378    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1379        no = "NO " if expression.args.get("no") else ""
    1380        local = expression.args.get("local")
    1381        local = f"{local} " if local else ""
    1382        dual = "DUAL " if expression.args.get("dual") else ""
    1383        before = "BEFORE " if expression.args.get("before") else ""
    1384        after = "AFTER " if expression.args.get("after") else ""
    1385        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1387    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1388        freespace = self.sql(expression, "this")
    1389        percent = " PERCENT" if expression.args.get("percent") else ""
    1390        return f"FREESPACE={freespace}{percent}"

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

    1392    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1393        if expression.args.get("default"):
    1394            property = "DEFAULT"
    1395        elif expression.args.get("on"):
    1396            property = "ON"
    1397        else:
    1398            property = "OFF"
    1399        return f"CHECKSUM={property}"

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

    1401    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1402        if expression.args.get("no"):
    1403            return "NO MERGEBLOCKRATIO"
    1404        if expression.args.get("default"):
    1405            return "DEFAULT MERGEBLOCKRATIO"
    1406
    1407        percent = " PERCENT" if expression.args.get("percent") else ""
    1408        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1410    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1411        default = expression.args.get("default")
    1412        minimum = expression.args.get("minimum")
    1413        maximum = expression.args.get("maximum")
    1414        if default or minimum or maximum:
    1415            if default:
    1416                prop = "DEFAULT"
    1417            elif minimum:
    1418                prop = "MINIMUM"
    1419            else:
    1420                prop = "MAXIMUM"
    1421            return f"{prop} DATABLOCKSIZE"
    1422        units = expression.args.get("units")
    1423        units = f" {units}" if units else ""
    1424        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1426    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1427        autotemp = expression.args.get("autotemp")
    1428        always = expression.args.get("always")
    1429        default = expression.args.get("default")
    1430        manual = expression.args.get("manual")
    1431        never = expression.args.get("never")
    1432
    1433        if autotemp is not None:
    1434            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1435        elif always:
    1436            prop = "ALWAYS"
    1437        elif default:
    1438            prop = "DEFAULT"
    1439        elif manual:
    1440            prop = "MANUAL"
    1441        elif never:
    1442            prop = "NEVER"
    1443        return f"BLOCKCOMPRESSION={prop}"

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

    1445    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1446        no = expression.args.get("no")
    1447        no = " NO" if no else ""
    1448        concurrent = expression.args.get("concurrent")
    1449        concurrent = " CONCURRENT" if concurrent else ""
    1450        target = self.sql(expression, "target")
    1451        target = f" {target}" if target else ""
    1452        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"

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

    1454    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1455        if isinstance(expression.this, list):
    1456            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1457        if expression.this:
    1458            modulus = self.sql(expression, "this")
    1459            remainder = self.sql(expression, "expression")
    1460            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1461
    1462        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1463        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1464        return f"FROM ({from_expressions}) TO ({to_expressions})"

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

    1466    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1467        this = self.sql(expression, "this")
    1468
    1469        for_values_or_default = expression.expression
    1470        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1471            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1472        else:
    1473            for_values_or_default = " DEFAULT"
    1474
    1475        return f"PARTITION OF {this}{for_values_or_default}"

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

    1477    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1478        kind = expression.args.get("kind")
    1479        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1480        for_or_in = expression.args.get("for_or_in")
    1481        for_or_in = f" {for_or_in}" if for_or_in else ""
    1482        lock_type = expression.args.get("lock_type")
    1483        override = " OVERRIDE" if expression.args.get("override") else ""
    1484        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"

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

    1486    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1487        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1488        statistics = expression.args.get("statistics")
    1489        statistics_sql = ""
    1490        if statistics is not None:
    1491            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1492        return f"{data_sql}{statistics_sql}"

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

    1494    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1495        sql = "WITH(SYSTEM_VERSIONING=ON"
    1496
    1497        if expression.this:
    1498            history_table = self.sql(expression, "this")
    1499            sql = f"{sql}(HISTORY_TABLE={history_table}"
    1500
    1501            if expression.expression:
    1502                data_consistency_check = self.sql(expression, "expression")
    1503                sql = f"{sql}, DATA_CONSISTENCY_CHECK={data_consistency_check}"
    1504
    1505            sql = f"{sql})"
    1506
    1507        return f"{sql})"

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

    1509    def insert_sql(self, expression: exp.Insert) -> str:
    1510        hint = self.sql(expression, "hint")
    1511        overwrite = expression.args.get("overwrite")
    1512
    1513        if isinstance(expression.this, exp.Directory):
    1514            this = " OVERWRITE" if overwrite else " INTO"
    1515        else:
    1516            this = self.INSERT_OVERWRITE if overwrite else " INTO"
    1517
    1518        alternative = expression.args.get("alternative")
    1519        alternative = f" OR {alternative}" if alternative else ""
    1520        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1521        is_function = expression.args.get("is_function")
    1522        if is_function:
    1523            this = f"{this} FUNCTION"
    1524        this = f"{this} {self.sql(expression, 'this')}"
    1525
    1526        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1527        partition_sql = (
    1528            f" {self.sql(expression, 'partition')}" if expression.args.get("partition") else ""
    1529        )
    1530        where = self.sql(expression, "where")
    1531        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1532        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1533        on_conflict = self.sql(expression, "conflict")
    1534        on_conflict = f" {on_conflict}" if on_conflict else ""
    1535        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1536        returning = self.sql(expression, "returning")
    1537
    1538        if self.RETURNING_END:
    1539            expression_sql = f"{expression_sql}{on_conflict}{returning}"
    1540        else:
    1541            expression_sql = f"{returning}{expression_sql}{on_conflict}"
    1542
    1543        sql = f"INSERT{hint}{alternative}{ignore}{this}{by_name}{exists}{partition_sql}{where}{expression_sql}"
    1544        return self.prepend_ctes(expression, sql)

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

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

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

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

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

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

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

    1555    def kill_sql(self, expression: exp.Kill) -> str:
    1556        kind = self.sql(expression, "kind")
    1557        kind = f" {kind}" if kind else ""
    1558        this = self.sql(expression, "this")
    1559        this = f" {this}" if this else ""
    1560        return f"KILL{kind}{this}"

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

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

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

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

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

    1568    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1569        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1570
    1571        constraint = self.sql(expression, "constraint")
    1572        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
    1573
    1574        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
    1575        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
    1576        action = self.sql(expression, "action")
    1577
    1578        expressions = self.expressions(expression, flat=True)
    1579        if expressions:
    1580            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1581            expressions = f" {set_keyword}{expressions}"
    1582
    1583        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}"

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

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

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

    1588    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1589        fields = expression.args.get("fields")
    1590        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1591        escaped = expression.args.get("escaped")
    1592        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1593        items = expression.args.get("collection_items")
    1594        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1595        keys = expression.args.get("map_keys")
    1596        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1597        lines = expression.args.get("lines")
    1598        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1599        null = expression.args.get("null")
    1600        null = f" NULL DEFINED AS {null}" if null else ""
    1601        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1606    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1607        this = f"{self.sql(expression, 'this')} INDEX"
    1608        target = self.sql(expression, "target")
    1609        target = f" FOR {target}" if target else ""
    1610        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1612    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1613        this = self.sql(expression, "this")
    1614        kind = self.sql(expression, "kind")
    1615        expr = self.sql(expression, "expression")
    1616        return f"{this} ({kind} => {expr})"

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

    1618    def table_parts(self, expression: exp.Table) -> str:
    1619        return ".".join(
    1620            self.sql(part)
    1621            for part in (
    1622                expression.args.get("catalog"),
    1623                expression.args.get("db"),
    1624                expression.args.get("this"),
    1625            )
    1626            if part is not None
    1627        )

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

    1629    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1630        table = self.table_parts(expression)
    1631        only = "ONLY " if expression.args.get("only") else ""
    1632        version = self.sql(expression, "version")
    1633        version = f" {version}" if version else ""
    1634        alias = self.sql(expression, "alias")
    1635        alias = f"{sep}{alias}" if alias else ""
    1636        hints = self.expressions(expression, key="hints", sep=" ")
    1637        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1638        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1639        pivots = f" {pivots}" if pivots else ""
    1640        joins = self.expressions(expression, key="joins", sep="", skip_first=True)
    1641        laterals = self.expressions(expression, key="laterals", sep="")
    1642
    1643        file_format = self.sql(expression, "format")
    1644        if file_format:
    1645            pattern = self.sql(expression, "pattern")
    1646            pattern = f", PATTERN => {pattern}" if pattern else ""
    1647            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    1648
    1649        ordinality = expression.args.get("ordinality") or ""
    1650        if ordinality:
    1651            ordinality = f" WITH ORDINALITY{alias}"
    1652            alias = ""
    1653
    1654        when = self.sql(expression, "when")
    1655        if when:
    1656            table = f"{table} {when}"
    1657
    1658        return f"{only}{table}{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

    1660    def tablesample_sql(
    1661        self,
    1662        expression: exp.TableSample,
    1663        sep: str = " AS ",
    1664        tablesample_keyword: t.Optional[str] = None,
    1665    ) -> str:
    1666        if self.dialect.ALIAS_POST_TABLESAMPLE and expression.this and expression.this.alias:
    1667            table = expression.this.copy()
    1668            table.set("alias", None)
    1669            this = self.sql(table)
    1670            alias = f"{sep}{self.sql(expression.this, 'alias')}"
    1671        else:
    1672            this = self.sql(expression, "this")
    1673            alias = ""
    1674
    1675        method = self.sql(expression, "method")
    1676        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1677        numerator = self.sql(expression, "bucket_numerator")
    1678        denominator = self.sql(expression, "bucket_denominator")
    1679        field = self.sql(expression, "bucket_field")
    1680        field = f" ON {field}" if field else ""
    1681        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1682        seed = self.sql(expression, "seed")
    1683        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
    1684
    1685        size = self.sql(expression, "size")
    1686        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
    1687            size = f"{size} ROWS"
    1688
    1689        percent = self.sql(expression, "percent")
    1690        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
    1691            percent = f"{percent} PERCENT"
    1692
    1693        expr = f"{bucket}{percent}{size}"
    1694        if self.TABLESAMPLE_REQUIRES_PARENS:
    1695            expr = f"({expr})"
    1696
    1697        return (
    1698            f"{this} {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}{alias}"
    1699        )

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

    1701    def pivot_sql(self, expression: exp.Pivot) -> str:
    1702        expressions = self.expressions(expression, flat=True)
    1703
    1704        if expression.this:
    1705            this = self.sql(expression, "this")
    1706            if not expressions:
    1707                return f"UNPIVOT {this}"
    1708
    1709            on = f"{self.seg('ON')} {expressions}"
    1710            using = self.expressions(expression, key="using", flat=True)
    1711            using = f"{self.seg('USING')} {using}" if using else ""
    1712            group = self.sql(expression, "group")
    1713            return f"PIVOT {this}{on}{using}{group}"
    1714
    1715        alias = self.sql(expression, "alias")
    1716        alias = f" AS {alias}" if alias else ""
    1717        direction = "UNPIVOT" if expression.unpivot else "PIVOT"
    1718        field = self.sql(expression, "field")
    1719        include_nulls = expression.args.get("include_nulls")
    1720        if include_nulls is not None:
    1721            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    1722        else:
    1723            nulls = ""
    1724        return f"{direction}{nulls}({expressions} FOR {field}){alias}"

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

    1726    def version_sql(self, expression: exp.Version) -> str:
    1727        this = f"FOR {expression.name}"
    1728        kind = expression.text("kind")
    1729        expr = self.sql(expression, "expression")
    1730        return f"{this} {kind} {expr}"

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

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

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

    1735    def update_sql(self, expression: exp.Update) -> str:
    1736        this = self.sql(expression, "this")
    1737        set_sql = self.expressions(expression, flat=True)
    1738        from_sql = self.sql(expression, "from")
    1739        where_sql = self.sql(expression, "where")
    1740        returning = self.sql(expression, "returning")
    1741        order = self.sql(expression, "order")
    1742        limit = self.sql(expression, "limit")
    1743        if self.RETURNING_END:
    1744            expression_sql = f"{from_sql}{where_sql}{returning}"
    1745        else:
    1746            expression_sql = f"{returning}{from_sql}{where_sql}"
    1747        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    1748        return self.prepend_ctes(expression, sql)

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

    1750    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
    1751        values_as_table = values_as_table and self.VALUES_AS_TABLE
    1752
    1753        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    1754        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
    1755            args = self.expressions(expression)
    1756            alias = self.sql(expression, "alias")
    1757            values = f"VALUES{self.seg('')}{args}"
    1758            values = (
    1759                f"({values})"
    1760                if self.WRAP_DERIVED_VALUES and (alias or isinstance(expression.parent, exp.From))
    1761                else values
    1762            )
    1763            return f"{values} AS {alias}" if alias else values
    1764
    1765        # Converts `VALUES...` expression into a series of select unions.
    1766        alias_node = expression.args.get("alias")
    1767        column_names = alias_node and alias_node.columns
    1768
    1769        selects: t.List[exp.Query] = []
    1770
    1771        for i, tup in enumerate(expression.expressions):
    1772            row = tup.expressions
    1773
    1774            if i == 0 and column_names:
    1775                row = [
    1776                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    1777                ]
    1778
    1779            selects.append(exp.Select(expressions=row))
    1780
    1781        if self.pretty:
    1782            # This may result in poor performance for large-cardinality `VALUES` tables, due to
    1783            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
    1784            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
    1785            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
    1786            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
    1787
    1788        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
    1789        unions = " UNION ALL ".join(self.sql(select) for select in selects)
    1790        return f"({unions}){alias}"

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

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

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

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

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

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

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

    1803    def group_sql(self, expression: exp.Group) -> str:
    1804        group_by = self.op_expressions("GROUP BY", expression)
    1805
    1806        if expression.args.get("all"):
    1807            return f"{group_by} ALL"
    1808
    1809        grouping_sets = self.expressions(expression, key="grouping_sets", indent=False)
    1810        grouping_sets = (
    1811            f"{self.seg('GROUPING SETS')} {self.wrap(grouping_sets)}" if grouping_sets else ""
    1812        )
    1813
    1814        cube = expression.args.get("cube", [])
    1815        if seq_get(cube, 0) is True:
    1816            return f"{group_by}{self.seg('WITH CUBE')}"
    1817        else:
    1818            cube_sql = self.expressions(expression, key="cube", indent=False)
    1819            cube_sql = f"{self.seg('CUBE')} {self.wrap(cube_sql)}" if cube_sql else ""
    1820
    1821        rollup = expression.args.get("rollup", [])
    1822        if seq_get(rollup, 0) is True:
    1823            return f"{group_by}{self.seg('WITH ROLLUP')}"
    1824        else:
    1825            rollup_sql = self.expressions(expression, key="rollup", indent=False)
    1826            rollup_sql = f"{self.seg('ROLLUP')} {self.wrap(rollup_sql)}" if rollup_sql else ""
    1827
    1828        groupings = csv(
    1829            grouping_sets,
    1830            cube_sql,
    1831            rollup_sql,
    1832            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    1833            sep=self.GROUPINGS_SEP,
    1834        )
    1835
    1836        if expression.args.get("expressions") and groupings:
    1837            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    1838
    1839        return f"{group_by}{groupings}"

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

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

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

    1845    def connect_sql(self, expression: exp.Connect) -> str:
    1846        start = self.sql(expression, "start")
    1847        start = self.seg(f"START WITH {start}") if start else ""
    1848        connect = self.sql(expression, "connect")
    1849        connect = self.seg(f"CONNECT BY {connect}")
    1850        return start + connect

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

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

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

    1855    def join_sql(self, expression: exp.Join) -> str:
    1856        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    1857            side = None
    1858        else:
    1859            side = expression.side
    1860
    1861        op_sql = " ".join(
    1862            op
    1863            for op in (
    1864                expression.method,
    1865                "GLOBAL" if expression.args.get("global") else None,
    1866                side,
    1867                expression.kind,
    1868                expression.hint if self.JOIN_HINTS else None,
    1869            )
    1870            if op
    1871        )
    1872        on_sql = self.sql(expression, "on")
    1873        using = expression.args.get("using")
    1874
    1875        if not on_sql and using:
    1876            on_sql = csv(*(self.sql(column) for column in using))
    1877
    1878        this = expression.this
    1879        this_sql = self.sql(this)
    1880
    1881        if on_sql:
    1882            on_sql = self.indent(on_sql, skip_first=True)
    1883            space = self.seg(" " * self.pad) if self.pretty else " "
    1884            if using:
    1885                on_sql = f"{space}USING ({on_sql})"
    1886            else:
    1887                on_sql = f"{space}ON {on_sql}"
    1888        elif not op_sql:
    1889            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
    1890                return f" {this_sql}"
    1891
    1892            return f", {this_sql}"
    1893
    1894        op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    1895        return f"{self.seg(op_sql)} {this_sql}{on_sql}"

def lambda_sql( self, expression: sqlglot.expressions.Lambda, arrow_sep: str = '->') -> str: View Source

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

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

    1902    def lateral_op(self, expression: exp.Lateral) -> str:
    1903        cross_apply = expression.args.get("cross_apply")
    1904
    1905        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    1906        if cross_apply is True:
    1907            op = "INNER JOIN "
    1908        elif cross_apply is False:
    1909            op = "LEFT JOIN "
    1910        else:
    1911            op = ""
    1912
    1913        return f"{op}LATERAL"

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

    1915    def lateral_sql(self, expression: exp.Lateral) -> str:
    1916        this = self.sql(expression, "this")
    1917
    1918        if expression.args.get("view"):
    1919            alias = expression.args["alias"]
    1920            columns = self.expressions(alias, key="columns", flat=True)
    1921            table = f" {alias.name}" if alias.name else ""
    1922            columns = f" AS {columns}" if columns else ""
    1923            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    1924            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    1925
    1926        alias = self.sql(expression, "alias")
    1927        alias = f" AS {alias}" if alias else ""
    1928        return f"{self.lateral_op(expression)} {this}{alias}"

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

    1930    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    1931        this = self.sql(expression, "this")
    1932
    1933        args = [
    1934            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    1935            for e in (expression.args.get(k) for k in ("offset", "expression"))
    1936            if e
    1937        ]
    1938
    1939        args_sql = ", ".join(self.sql(e) for e in args)
    1940        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
    1941        expressions = self.expressions(expression, flat=True)
    1942        expressions = f" BY {expressions}" if expressions else ""
    1943
    1944        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}"

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

    1946    def offset_sql(self, expression: exp.Offset) -> str:
    1947        this = self.sql(expression, "this")
    1948        value = expression.expression
    1949        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    1950        expressions = self.expressions(expression, flat=True)
    1951        expressions = f" BY {expressions}" if expressions else ""
    1952        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"

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

    1954    def setitem_sql(self, expression: exp.SetItem) -> str:
    1955        kind = self.sql(expression, "kind")
    1956        kind = f"{kind} " if kind else ""
    1957        this = self.sql(expression, "this")
    1958        expressions = self.expressions(expression)
    1959        collate = self.sql(expression, "collate")
    1960        collate = f" COLLATE {collate}" if collate else ""
    1961        global_ = "GLOBAL " if expression.args.get("global") else ""
    1962        return f"{global_}{kind}{this}{expressions}{collate}"

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

    1964    def set_sql(self, expression: exp.Set) -> str:
    1965        expressions = (
    1966            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    1967        )
    1968        tag = " TAG" if expression.args.get("tag") else ""
    1969        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"

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

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

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

    1974    def lock_sql(self, expression: exp.Lock) -> str:
    1975        if not self.LOCKING_READS_SUPPORTED:
    1976            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    1977            return ""
    1978
    1979        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    1980        expressions = self.expressions(expression, flat=True)
    1981        expressions = f" OF {expressions}" if expressions else ""
    1982        wait = expression.args.get("wait")
    1983
    1984        if wait is not None:
    1985            if isinstance(wait, exp.Literal):
    1986                wait = f" WAIT {self.sql(wait)}"
    1987            else:
    1988                wait = " NOWAIT" if wait else " SKIP LOCKED"
    1989
    1990        return f"{lock_type}{expressions}{wait or ''}"

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

    1992    def literal_sql(self, expression: exp.Literal) -> str:
    1993        text = expression.this or ""
    1994        if expression.is_string:
    1995            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    1996        return text

def escape_str(self, text: str) -> str: View Source

    1998    def escape_str(self, text: str) -> str:
    1999        text = text.replace(self.dialect.QUOTE_END, self._escaped_quote_end)
    2000        if self.dialect.INVERSE_ESCAPE_SEQUENCES:
    2001            text = "".join(self.dialect.INVERSE_ESCAPE_SEQUENCES.get(ch, ch) for ch in text)
    2002        elif self.pretty:
    2003            text = text.replace("\n", self.SENTINEL_LINE_BREAK)
    2004        return text

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

    2006    def loaddata_sql(self, expression: exp.LoadData) -> str:
    2007        local = " LOCAL" if expression.args.get("local") else ""
    2008        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    2009        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    2010        this = f" INTO TABLE {self.sql(expression, 'this')}"
    2011        partition = self.sql(expression, "partition")
    2012        partition = f" {partition}" if partition else ""
    2013        input_format = self.sql(expression, "input_format")
    2014        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    2015        serde = self.sql(expression, "serde")
    2016        serde = f" SERDE {serde}" if serde else ""
    2017        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    2019    def null_sql(self, *_) -> str:
    2020        return "NULL"

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

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

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

    2025    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2026        this = self.sql(expression, "this")
    2027        this = f"{this} " if this else this
    2028        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2029        order = self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat)  # type: ignore
    2030        interpolated_values = [
    2031            f"{self.sql(named_expression, 'alias')} AS {self.sql(named_expression, 'this')}"
    2032            for named_expression in expression.args.get("interpolate") or []
    2033        ]
    2034        interpolate = (
    2035            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    2036        )
    2037        return f"{order}{interpolate}"

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

    2039    def withfill_sql(self, expression: exp.WithFill) -> str:
    2040        from_sql = self.sql(expression, "from")
    2041        from_sql = f" FROM {from_sql}" if from_sql else ""
    2042        to_sql = self.sql(expression, "to")
    2043        to_sql = f" TO {to_sql}" if to_sql else ""
    2044        step_sql = self.sql(expression, "step")
    2045        step_sql = f" STEP {step_sql}" if step_sql else ""
    2046        return f"WITH FILL{from_sql}{to_sql}{step_sql}"

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

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

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

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

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

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

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

    2057    def ordered_sql(self, expression: exp.Ordered) -> str:
    2058        desc = expression.args.get("desc")
    2059        asc = not desc
    2060
    2061        nulls_first = expression.args.get("nulls_first")
    2062        nulls_last = not nulls_first
    2063        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
    2064        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
    2065        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
    2066
    2067        this = self.sql(expression, "this")
    2068
    2069        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
    2070        nulls_sort_change = ""
    2071        if nulls_first and (
    2072            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    2073        ):
    2074            nulls_sort_change = " NULLS FIRST"
    2075        elif (
    2076            nulls_last
    2077            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    2078            and not nulls_are_last
    2079        ):
    2080            nulls_sort_change = " NULLS LAST"
    2081
    2082        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
    2083        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    2084            window = expression.find_ancestor(exp.Window, exp.Select)
    2085            if isinstance(window, exp.Window) and window.args.get("spec"):
    2086                self.unsupported(
    2087                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
    2088                )
    2089                nulls_sort_change = ""
    2090            elif self.NULL_ORDERING_SUPPORTED is None:
    2091                if expression.this.is_int:
    2092                    self.unsupported(
    2093                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
    2094                    )
    2095                else:
    2096                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
    2097                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
    2098                nulls_sort_change = ""
    2099
    2100        with_fill = self.sql(expression, "with_fill")
    2101        with_fill = f" {with_fill}" if with_fill else ""
    2102
    2103        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"

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

    2105    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    2106        partition = self.partition_by_sql(expression)
    2107        order = self.sql(expression, "order")
    2108        measures = self.expressions(expression, key="measures")
    2109        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    2110        rows = self.sql(expression, "rows")
    2111        rows = self.seg(rows) if rows else ""
    2112        after = self.sql(expression, "after")
    2113        after = self.seg(after) if after else ""
    2114        pattern = self.sql(expression, "pattern")
    2115        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    2116        definition_sqls = [
    2117            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    2118            for definition in expression.args.get("define", [])
    2119        ]
    2120        definitions = self.expressions(sqls=definition_sqls)
    2121        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    2122        body = "".join(
    2123            (
    2124                partition,
    2125                order,
    2126                measures,
    2127                rows,
    2128                after,
    2129                pattern,
    2130                define,
    2131            )
    2132        )
    2133        alias = self.sql(expression, "alias")
    2134        alias = f" {alias}" if alias else ""
    2135        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    2137    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    2138        limit = expression.args.get("limit")
    2139
    2140        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    2141            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    2142        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    2143            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    2144
    2145        options = self.expressions(expression, key="options")
    2146        if options:
    2147            options = f" OPTION{self.wrap(options)}"
    2148
    2149        return csv(
    2150            *sqls,
    2151            *[self.sql(join) for join in expression.args.get("joins") or []],
    2152            self.sql(expression, "connect"),
    2153            self.sql(expression, "match"),
    2154            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2155            self.sql(expression, "prewhere"),
    2156            self.sql(expression, "where"),
    2157            self.sql(expression, "group"),
    2158            self.sql(expression, "having"),
    2159            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
    2160            self.sql(expression, "order"),
    2161            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
    2162            *self.after_limit_modifiers(expression),
    2163            options,
    2164            sep="",
    2165        )

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

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

    2170    def offset_limit_modifiers(
    2171        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2172    ) -> t.List[str]:
    2173        return [
    2174            self.sql(expression, "offset") if fetch else self.sql(limit),
    2175            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2176        ]

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

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

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

    2183    def select_sql(self, expression: exp.Select) -> str:
    2184        into = expression.args.get("into")
    2185        if not self.SUPPORTS_SELECT_INTO and into:
    2186            into.pop()
    2187
    2188        hint = self.sql(expression, "hint")
    2189        distinct = self.sql(expression, "distinct")
    2190        distinct = f" {distinct}" if distinct else ""
    2191        kind = self.sql(expression, "kind")
    2192
    2193        limit = expression.args.get("limit")
    2194        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
    2195            top = self.limit_sql(limit, top=True)
    2196            limit.pop()
    2197        else:
    2198            top = ""
    2199
    2200        expressions = self.expressions(expression)
    2201
    2202        if kind:
    2203            if kind in self.SELECT_KINDS:
    2204                kind = f" AS {kind}"
    2205            else:
    2206                if kind == "STRUCT":
    2207                    expressions = self.expressions(
    2208                        sqls=[
    2209                            self.sql(
    2210                                exp.Struct(
    2211                                    expressions=[
    2212                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
    2213                                        if isinstance(e, exp.Alias)
    2214                                        else e
    2215                                        for e in expression.expressions
    2216                                    ]
    2217                                )
    2218                            )
    2219                        ]
    2220                    )
    2221                kind = ""
    2222
    2223        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
    2224        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
    2225        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
    2226        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    2227        sql = self.query_modifiers(
    2228            expression,
    2229            f"SELECT{top_distinct}{kind}{expressions}",
    2230            self.sql(expression, "into", comment=False),
    2231            self.sql(expression, "from", comment=False),
    2232        )
    2233
    2234        sql = self.prepend_ctes(expression, sql)
    2235
    2236        if not self.SUPPORTS_SELECT_INTO and into:
    2237            if into.args.get("temporary"):
    2238                table_kind = " TEMPORARY"
    2239            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
    2240                table_kind = " UNLOGGED"
    2241            else:
    2242                table_kind = ""
    2243            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
    2244
    2245        return sql

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

    2247    def schema_sql(self, expression: exp.Schema) -> str:
    2248        this = self.sql(expression, "this")
    2249        sql = self.schema_columns_sql(expression)
    2250        return f"{this} {sql}" if this and sql else this or sql

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

    2252    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2253        if expression.expressions:
    2254            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2255        return ""

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

    2257    def star_sql(self, expression: exp.Star) -> str:
    2258        except_ = self.expressions(expression, key="except", flat=True)
    2259        except_ = f"{self.seg(self.STAR_MAPPING['except'])} ({except_})" if except_ else ""
    2260        replace = self.expressions(expression, key="replace", flat=True)
    2261        replace = f"{self.seg(self.STAR_MAPPING['replace'])} ({replace})" if replace else ""
    2262        return f"*{except_}{replace}"

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

    2264    def parameter_sql(self, expression: exp.Parameter) -> str:
    2265        this = self.sql(expression, "this")
    2266        return f"{self.PARAMETER_TOKEN}{this}"

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

    2268    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2269        this = self.sql(expression, "this")
    2270        kind = expression.text("kind")
    2271        if kind:
    2272            kind = f"{kind}."
    2273        return f"@@{kind}{this}"

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

    2275    def placeholder_sql(self, expression: exp.Placeholder) -> str:
    2276        return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.name else "?"

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

    2278    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2279        alias = self.sql(expression, "alias")
    2280        alias = f"{sep}{alias}" if alias else ""
    2281
    2282        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    2283        pivots = f" {pivots}" if pivots else ""
    2284
    2285        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2286        return self.prepend_ctes(expression, sql)

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

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

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

    2292    def set_operations(self, expression: exp.Union) -> str:
    2293        sqls: t.List[str] = []
    2294        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    2295
    2296        while stack:
    2297            node = stack.pop()
    2298
    2299            if isinstance(node, exp.Union):
    2300                stack.append(node.expression)
    2301                stack.append(
    2302                    self.maybe_comment(
    2303                        getattr(self, f"{node.key}_op")(node),
    2304                        expression=node.this,
    2305                        comments=node.comments,
    2306                    )
    2307                )
    2308                stack.append(node.this)
    2309            else:
    2310                sqls.append(self.sql(node))
    2311
    2312        this = self.sep().join(sqls)
    2313        this = self.query_modifiers(expression, this)
    2314        return self.prepend_ctes(expression, this)

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

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

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

    2319    def union_op(self, expression: exp.Union) -> str:
    2320        kind = " DISTINCT" if self.EXPLICIT_UNION else ""
    2321        kind = kind if expression.args.get("distinct") else " ALL"
    2322        by_name = " BY NAME" if expression.args.get("by_name") else ""
    2323        return f"UNION{kind}{by_name}"

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

    2325    def unnest_sql(self, expression: exp.Unnest) -> str:
    2326        args = self.expressions(expression, flat=True)
    2327
    2328        alias = expression.args.get("alias")
    2329        offset = expression.args.get("offset")
    2330
    2331        if self.UNNEST_WITH_ORDINALITY:
    2332            if alias and isinstance(offset, exp.Expression):
    2333                alias.append("columns", offset)
    2334
    2335        if alias and self.dialect.UNNEST_COLUMN_ONLY:
    2336            columns = alias.columns
    2337            alias = self.sql(columns[0]) if columns else ""
    2338        else:
    2339            alias = self.sql(alias)
    2340
    2341        alias = f" AS {alias}" if alias else alias
    2342        if self.UNNEST_WITH_ORDINALITY:
    2343            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2344        else:
    2345            if isinstance(offset, exp.Expression):
    2346                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2347            elif offset:
    2348                suffix = f"{alias} WITH OFFSET"
    2349            else:
    2350                suffix = alias
    2351
    2352        return f"UNNEST({args}){suffix}"

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

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

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

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

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

    2361    def window_sql(self, expression: exp.Window) -> str:
    2362        this = self.sql(expression, "this")
    2363        partition = self.partition_by_sql(expression)
    2364        order = expression.args.get("order")
    2365        order = self.order_sql(order, flat=True) if order else ""
    2366        spec = self.sql(expression, "spec")
    2367        alias = self.sql(expression, "alias")
    2368        over = self.sql(expression, "over") or "OVER"
    2369
    2370        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2371
    2372        first = expression.args.get("first")
    2373        if first is None:
    2374            first = ""
    2375        else:
    2376            first = "FIRST" if first else "LAST"
    2377
    2378        if not partition and not order and not spec and alias:
    2379            return f"{this} {alias}"
    2380
    2381        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    2382        return f"{this} ({args})"

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

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

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

    2388    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2389        kind = self.sql(expression, "kind")
    2390        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2391        end = (
    2392            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2393            or "CURRENT ROW"
    2394        )
    2395        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    2402    def between_sql(self, expression: exp.Between) -> str:
    2403        this = self.sql(expression, "this")
    2404        low = self.sql(expression, "low")
    2405        high = self.sql(expression, "high")
    2406        return f"{this} BETWEEN {low} AND {high}"

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

    2408    def bracket_sql(self, expression: exp.Bracket) -> str:
    2409        expressions = apply_index_offset(
    2410            expression.this,
    2411            expression.expressions,
    2412            self.dialect.INDEX_OFFSET - expression.args.get("offset", 0),
    2413        )
    2414        expressions_sql = ", ".join(self.sql(e) for e in expressions)
    2415        return f"{self.sql(expression, 'this')}[{expressions_sql}]"

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

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

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

    2420    def any_sql(self, expression: exp.Any) -> str:
    2421        this = self.sql(expression, "this")
    2422        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
    2423            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2424                this = self.wrap(this)
    2425            return f"ANY{this}"
    2426        return f"ANY {this}"

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

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

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

    2431    def case_sql(self, expression: exp.Case) -> str:
    2432        this = self.sql(expression, "this")
    2433        statements = [f"CASE {this}" if this else "CASE"]
    2434
    2435        for e in expression.args["ifs"]:
    2436            statements.append(f"WHEN {self.sql(e, 'this')}")
    2437            statements.append(f"THEN {self.sql(e, 'true')}")
    2438
    2439        default = self.sql(expression, "default")
    2440
    2441        if default:
    2442            statements.append(f"ELSE {default}")
    2443
    2444        statements.append("END")
    2445
    2446        if self.pretty and self.text_width(statements) > self.max_text_width:
    2447            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2448
    2449        return " ".join(statements)

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

    2451    def constraint_sql(self, expression: exp.Constraint) -> str:
    2452        this = self.sql(expression, "this")
    2453        expressions = self.expressions(expression, flat=True)
    2454        return f"CONSTRAINT {this} {expressions}"

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

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

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

    2461    def extract_sql(self, expression: exp.Extract) -> str:
    2462        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2463        expression_sql = self.sql(expression, "expression")
    2464        return f"EXTRACT({this} FROM {expression_sql})"

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

    2466    def trim_sql(self, expression: exp.Trim) -> str:
    2467        trim_type = self.sql(expression, "position")
    2468
    2469        if trim_type == "LEADING":
    2470            return self.func("LTRIM", expression.this)
    2471        elif trim_type == "TRAILING":
    2472            return self.func("RTRIM", expression.this)
    2473        else:
    2474            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

    2476    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2477        args = expression.expressions
    2478        if isinstance(expression, exp.ConcatWs):
    2479            args = args[1:]  # Skip the delimiter
    2480
    2481        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2482            args = [exp.cast(e, "text") for e in args]
    2483
    2484        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2485            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2486
    2487        return args

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

    2489    def concat_sql(self, expression: exp.Concat) -> str:
    2490        expressions = self.convert_concat_args(expression)
    2491
    2492        # Some dialects don't allow a single-argument CONCAT call
    2493        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2494            return self.sql(expressions[0])
    2495
    2496        return self.func("CONCAT", *expressions)

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

    2498    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2499        return self.func(
    2500            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2501        )

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

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

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

    2507    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2508        expressions = self.expressions(expression, flat=True)
    2509        reference = self.sql(expression, "reference")
    2510        reference = f" {reference}" if reference else ""
    2511        delete = self.sql(expression, "delete")
    2512        delete = f" ON DELETE {delete}" if delete else ""
    2513        update = self.sql(expression, "update")
    2514        update = f" ON UPDATE {update}" if update else ""
    2515        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"

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

    2517    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2518        expressions = self.expressions(expression, flat=True)
    2519        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2520        options = f" {options}" if options else ""
    2521        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

    2534    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
    2535        path = self.expressions(expression, sep="", flat=True).lstrip(".")
    2536        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

    2538    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
    2539        if isinstance(expression, exp.JSONPathPart):
    2540            transform = self.TRANSFORMS.get(expression.__class__)
    2541            if not callable(transform):
    2542                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
    2543                return ""
    2544
    2545            return transform(self, expression)
    2546
    2547        if isinstance(expression, int):
    2548            return str(expression)
    2549
    2550        if self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
    2551            escaped = expression.replace("'", "\\'")
    2552            escaped = f"\\'{expression}\\'"
    2553        else:
    2554            escaped = expression.replace('"', '\\"')
    2555            escaped = f'"{escaped}"'
    2556
    2557        return escaped

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

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

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

    2562    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    2563        null_handling = expression.args.get("null_handling")
    2564        null_handling = f" {null_handling}" if null_handling else ""
    2565
    2566        unique_keys = expression.args.get("unique_keys")
    2567        if unique_keys is not None:
    2568            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2569        else:
    2570            unique_keys = ""
    2571
    2572        return_type = self.sql(expression, "return_type")
    2573        return_type = f" RETURNING {return_type}" if return_type else ""
    2574        encoding = self.sql(expression, "encoding")
    2575        encoding = f" ENCODING {encoding}" if encoding else ""
    2576
    2577        return self.func(
    2578            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    2579            *expression.expressions,
    2580            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2581        )

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

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

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

    2586    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2587        null_handling = expression.args.get("null_handling")
    2588        null_handling = f" {null_handling}" if null_handling else ""
    2589        return_type = self.sql(expression, "return_type")
    2590        return_type = f" RETURNING {return_type}" if return_type else ""
    2591        strict = " STRICT" if expression.args.get("strict") else ""
    2592        return self.func(
    2593            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2594        )

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

    2596    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2597        this = self.sql(expression, "this")
    2598        order = self.sql(expression, "order")
    2599        null_handling = expression.args.get("null_handling")
    2600        null_handling = f" {null_handling}" if null_handling else ""
    2601        return_type = self.sql(expression, "return_type")
    2602        return_type = f" RETURNING {return_type}" if return_type else ""
    2603        strict = " STRICT" if expression.args.get("strict") else ""
    2604        return self.func(
    2605            "JSON_ARRAYAGG",
    2606            this,
    2607            suffix=f"{order}{null_handling}{return_type}{strict})",
    2608        )

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

    2610    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2611        path = self.sql(expression, "path")
    2612        path = f" PATH {path}" if path else ""
    2613        nested_schema = self.sql(expression, "nested_schema")
    2614
    2615        if nested_schema:
    2616            return f"NESTED{path} {nested_schema}"
    2617
    2618        this = self.sql(expression, "this")
    2619        kind = self.sql(expression, "kind")
    2620        kind = f" {kind}" if kind else ""
    2621        return f"{this}{kind}{path}"

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

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

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

    2626    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    2627        this = self.sql(expression, "this")
    2628        path = self.sql(expression, "path")
    2629        path = f", {path}" if path else ""
    2630        error_handling = expression.args.get("error_handling")
    2631        error_handling = f" {error_handling}" if error_handling else ""
    2632        empty_handling = expression.args.get("empty_handling")
    2633        empty_handling = f" {empty_handling}" if empty_handling else ""
    2634        schema = self.sql(expression, "schema")
    2635        return self.func(
    2636            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    2637        )

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

    2639    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    2640        this = self.sql(expression, "this")
    2641        kind = self.sql(expression, "kind")
    2642        path = self.sql(expression, "path")
    2643        path = f" {path}" if path else ""
    2644        as_json = " AS JSON" if expression.args.get("as_json") else ""
    2645        return f"{this} {kind}{path}{as_json}"

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

    2647    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    2648        this = self.sql(expression, "this")
    2649        path = self.sql(expression, "path")
    2650        path = f", {path}" if path else ""
    2651        expressions = self.expressions(expression)
    2652        with_ = (
    2653            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2654            if expressions
    2655            else ""
    2656        )
    2657        return f"OPENJSON({this}{path}){with_}"

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

    2659    def in_sql(self, expression: exp.In) -> str:
    2660        query = expression.args.get("query")
    2661        unnest = expression.args.get("unnest")
    2662        field = expression.args.get("field")
    2663        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    2664
    2665        if query:
    2666            in_sql = self.wrap(self.sql(query))
    2667        elif unnest:
    2668            in_sql = self.in_unnest_op(unnest)
    2669        elif field:
    2670            in_sql = self.sql(field)
    2671        else:
    2672            in_sql = f"({self.expressions(expression, flat=True)})"
    2673
    2674        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    2679    def interval_sql(self, expression: exp.Interval) -> str:
    2680        unit = self.sql(expression, "unit")
    2681        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    2682            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    2683        unit = f" {unit}" if unit else ""
    2684
    2685        if self.SINGLE_STRING_INTERVAL:
    2686            this = expression.this.name if expression.this else ""
    2687            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    2688
    2689        this = self.sql(expression, "this")
    2690        if this:
    2691            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    2692            this = f" {this}" if unwrapped else f" ({this})"
    2693
    2694        return f"INTERVAL{this}{unit}"

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

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

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

    2699    def reference_sql(self, expression: exp.Reference) -> str:
    2700        this = self.sql(expression, "this")
    2701        expressions = self.expressions(expression, flat=True)
    2702        expressions = f"({expressions})" if expressions else ""
    2703        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2704        options = f" {options}" if options else ""
    2705        return f"REFERENCES {this}{expressions}{options}"

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

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

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

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

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

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

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

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

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

    2723    def alias_sql(self, expression: exp.Alias) -> str:
    2724        alias = self.sql(expression, "alias")
    2725        alias = f" AS {alias}" if alias else ""
    2726        return f"{self.sql(expression, 'this')}{alias}"

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

    2728    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    2729        alias = expression.args["alias"]
    2730        identifier_alias = isinstance(alias, exp.Identifier)
    2731
    2732        if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2733            alias.replace(exp.Literal.string(alias.output_name))
    2734        elif not identifier_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2735            alias.replace(exp.to_identifier(alias.output_name))
    2736
    2737        return self.alias_sql(expression)

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

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

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

    2742    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    2743        this = self.sql(expression, "this")
    2744        index = self.sql(expression, "expression")
    2745        return f"{this} AT {index}"

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

    2747    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    2748        this = self.sql(expression, "this")
    2749        zone = self.sql(expression, "zone")
    2750        return f"{this} AT TIME ZONE {zone}"

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

    2752    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    2753        this = self.sql(expression, "this")
    2754        zone = self.sql(expression, "zone")
    2755        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"

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

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

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

    2760    def and_sql(
    2761        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
    2762    ) -> str:
    2763        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

    2765    def or_sql(
    2766        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
    2767    ) -> str:
    2768        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

    2770    def xor_sql(
    2771        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
    2772    ) -> str:
    2773        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

    2775    def connector_sql(
    2776        self,
    2777        expression: exp.Connector,
    2778        op: str,
    2779        stack: t.Optional[t.List[str | exp.Expression]] = None,
    2780    ) -> str:
    2781        if stack is not None:
    2782            if expression.expressions:
    2783                stack.append(self.expressions(expression, sep=f" {op} "))
    2784            else:
    2785                stack.append(expression.right)
    2786                if expression.comments:
    2787                    for comment in expression.comments:
    2788                        op += f" /*{self.pad_comment(comment)}*/"
    2789                stack.extend((op, expression.left))
    2790            return op
    2791
    2792        stack = [expression]
    2793        sqls: t.List[str] = []
    2794        ops = set()
    2795
    2796        while stack:
    2797            node = stack.pop()
    2798            if isinstance(node, exp.Connector):
    2799                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
    2800            else:
    2801                sql = self.sql(node)
    2802                if sqls and sqls[-1] in ops:
    2803                    sqls[-1] += f" {sql}"
    2804                else:
    2805                    sqls.append(sql)
    2806
    2807        sep = "\n" if self.pretty and self.text_width(sqls) > self.max_text_width else " "
    2808        return sep.join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

    2828    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    2829        format_sql = self.sql(expression, "format")
    2830        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    2831        to_sql = self.sql(expression, "to")
    2832        to_sql = f" {to_sql}" if to_sql else ""
    2833        action = self.sql(expression, "action")
    2834        action = f" {action}" if action else ""
    2835        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

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

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

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

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

    2844    def collate_sql(self, expression: exp.Collate) -> str:
    2845        if self.COLLATE_IS_FUNC:
    2846            return self.function_fallback_sql(expression)
    2847        return self.binary(expression, "COLLATE")

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

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

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

    2852    def comment_sql(self, expression: exp.Comment) -> str:
    2853        this = self.sql(expression, "this")
    2854        kind = expression.args["kind"]
    2855        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    2856        expression_sql = self.sql(expression, "expression")
    2857        return f"COMMENT{exists_sql}ON {kind} {this} IS {expression_sql}"

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

    2859    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    2860        this = self.sql(expression, "this")
    2861        delete = " DELETE" if expression.args.get("delete") else ""
    2862        recompress = self.sql(expression, "recompress")
    2863        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    2864        to_disk = self.sql(expression, "to_disk")
    2865        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    2866        to_volume = self.sql(expression, "to_volume")
    2867        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    2868        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    2870    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    2871        where = self.sql(expression, "where")
    2872        group = self.sql(expression, "group")
    2873        aggregates = self.expressions(expression, key="aggregates")
    2874        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    2875
    2876        if not (where or group or aggregates) and len(expression.expressions) == 1:
    2877            return f"TTL {self.expressions(expression, flat=True)}"
    2878
    2879        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    2884    def commit_sql(self, expression: exp.Commit) -> str:
    2885        chain = expression.args.get("chain")
    2886        if chain is not None:
    2887            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    2888
    2889        return f"COMMIT{chain or ''}"

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

    2891    def rollback_sql(self, expression: exp.Rollback) -> str:
    2892        savepoint = expression.args.get("savepoint")
    2893        savepoint = f" TO {savepoint}" if savepoint else ""
    2894        return f"ROLLBACK{savepoint}"

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

    2896    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    2897        this = self.sql(expression, "this")
    2898
    2899        dtype = self.sql(expression, "dtype")
    2900        if dtype:
    2901            collate = self.sql(expression, "collate")
    2902            collate = f" COLLATE {collate}" if collate else ""
    2903            using = self.sql(expression, "using")
    2904            using = f" USING {using}" if using else ""
    2905            return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}"
    2906
    2907        default = self.sql(expression, "default")
    2908        if default:
    2909            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    2910
    2911        comment = self.sql(expression, "comment")
    2912        if comment:
    2913            return f"ALTER COLUMN {this} COMMENT {comment}"
    2914
    2915        if not expression.args.get("drop"):
    2916            self.unsupported("Unsupported ALTER COLUMN syntax")
    2917
    2918        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    2920    def renametable_sql(self, expression: exp.RenameTable) -> str:
    2921        if not self.RENAME_TABLE_WITH_DB:
    2922            # Remove db from tables
    2923            expression = expression.transform(
    2924                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    2925            ).assert_is(exp.RenameTable)
    2926        this = self.sql(expression, "this")
    2927        return f"RENAME TO {this}"

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

    2929    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    2930        exists = " IF EXISTS" if expression.args.get("exists") else ""
    2931        old_column = self.sql(expression, "this")
    2932        new_column = self.sql(expression, "to")
    2933        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"

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

    2935    def altertable_sql(self, expression: exp.AlterTable) -> str:
    2936        actions = expression.args["actions"]
    2937
    2938        if isinstance(actions[0], exp.ColumnDef):
    2939            actions = self.add_column_sql(expression)
    2940        elif isinstance(actions[0], exp.Schema):
    2941            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    2942        elif isinstance(actions[0], exp.Delete):
    2943            actions = self.expressions(expression, key="actions", flat=True)
    2944        else:
    2945            actions = self.expressions(expression, key="actions", flat=True)
    2946
    2947        exists = " IF EXISTS" if expression.args.get("exists") else ""
    2948        only = " ONLY" if expression.args.get("only") else ""
    2949        options = self.expressions(expression, key="options")
    2950        options = f", {options}" if options else ""
    2951        return f"ALTER TABLE{exists}{only} {self.sql(expression, 'this')} {actions}{options}"

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

    2953    def add_column_sql(self, expression: exp.AlterTable) -> str:
    2954        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    2955            return self.expressions(
    2956                expression,
    2957                key="actions",
    2958                prefix="ADD COLUMN ",
    2959            )
    2960        return f"ADD {self.expressions(expression, key='actions', flat=True)}"

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

    2962    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    2963        expressions = self.expressions(expression)
    2964        exists = " IF EXISTS " if expression.args.get("exists") else " "
    2965        return f"DROP{exists}{expressions}"

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

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

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

    2970    def distinct_sql(self, expression: exp.Distinct) -> str:
    2971        this = self.expressions(expression, flat=True)
    2972
    2973        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    2974            case = exp.case()
    2975            for arg in expression.expressions:
    2976                case = case.when(arg.is_(exp.null()), exp.null())
    2977            this = self.sql(case.else_(f"({this})"))
    2978
    2979        this = f" {this}" if this else ""
    2980
    2981        on = self.sql(expression, "on")
    2982        on = f" ON {on}" if on else ""
    2983        return f"DISTINCT{this}{on}"

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

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

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

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

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

    2991    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    2992        this_sql = self.sql(expression, "this")
    2993        expression_sql = self.sql(expression, "expression")
    2994        kind = "MAX" if expression.args.get("max") else "MIN"
    2995        return f"{this_sql} HAVING {kind} {expression_sql}"

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

    3021    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    3022        return self.sql(
    3023            exp.Cast(
    3024                this=exp.Div(this=expression.this, expression=expression.expression),
    3025                to=exp.DataType(this=exp.DataType.Type.INT),
    3026            )
    3027        )

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

    3029    def dpipe_sql(self, expression: exp.DPipe) -> str:
    3030        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    3031            return self.func("CONCAT", *(exp.cast(e, "text") for e in expression.flatten()))
    3032        return self.binary(expression, "||")

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

    3034    def div_sql(self, expression: exp.Div) -> str:
    3035        l, r = expression.left, expression.right
    3036
    3037        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    3038            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    3039
    3040        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    3041            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
    3042                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    3043
    3044        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    3045            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    3046                return self.sql(
    3047                    exp.cast(
    3048                        l / r,
    3049                        to=exp.DataType.Type.BIGINT,
    3050                    )
    3051                )
    3052
    3053        return self.binary(expression, "/")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3088    def is_sql(self, expression: exp.Is) -> str:
    3089        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3090            return self.sql(
    3091                expression.this if expression.expression.this else exp.not_(expression.this)
    3092            )
    3093        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3134    def log_sql(self, expression: exp.Log) -> str:
    3135        this = expression.this
    3136        expr = expression.expression
    3137
    3138        if self.dialect.LOG_BASE_FIRST is False:
    3139            this, expr = expr, this
    3140        elif self.dialect.LOG_BASE_FIRST is None and expr:
    3141            if this.name in ("2", "10"):
    3142                return self.func(f"LOG{this.name}", expr)
    3143
    3144            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
    3145
    3146        return self.func("LOG", this, expr)

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

    3148    def use_sql(self, expression: exp.Use) -> str:
    3149        kind = self.sql(expression, "kind")
    3150        kind = f" {kind}" if kind else ""
    3151        this = self.sql(expression, "this")
    3152        this = f" {this}" if this else ""
    3153        return f"USE{kind}{this}"

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

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

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

    3159    def function_fallback_sql(self, expression: exp.Func) -> str:
    3160        args = []
    3161
    3162        for key in expression.arg_types:
    3163            arg_value = expression.args.get(key)
    3164
    3165            if isinstance(arg_value, list):
    3166                for value in arg_value:
    3167                    args.append(value)
    3168            elif arg_value is not None:
    3169                args.append(arg_value)
    3170
    3171        if self.normalize_functions:
    3172            name = expression.sql_name()
    3173        else:
    3174            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3175
    3176        return self.func(name, *args)

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

    3178    def func(
    3179        self,
    3180        name: str,
    3181        *args: t.Optional[exp.Expression | str],
    3182        prefix: str = "(",
    3183        suffix: str = ")",
    3184    ) -> str:
    3185        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

    3187    def format_args(self, *args: t.Optional[str | exp.Expression]) -> str:
    3188        arg_sqls = tuple(self.sql(arg) for arg in args if arg is not None)
    3189        if self.pretty and self.text_width(arg_sqls) > self.max_text_width:
    3190            return self.indent("\n" + ",\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True)
    3191        return ", ".join(arg_sqls)

def text_width(self, args: Iterable) -> int: View Source

    3193    def text_width(self, args: t.Iterable) -> int:
    3194        return sum(len(arg) for arg in args)

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

    3196    def format_time(self, expression: exp.Expression) -> t.Optional[str]:
    3197        return format_time(
    3198            self.sql(expression, "format"),
    3199            self.dialect.INVERSE_TIME_MAPPING,
    3200            self.dialect.INVERSE_TIME_TRIE,
    3201        )

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, sep: str = ', ', prefix: str = '') -> str: View Source

    3203    def expressions(
    3204        self,
    3205        expression: t.Optional[exp.Expression] = None,
    3206        key: t.Optional[str] = None,
    3207        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    3208        flat: bool = False,
    3209        indent: bool = True,
    3210        skip_first: bool = False,
    3211        sep: str = ", ",
    3212        prefix: str = "",
    3213    ) -> str:
    3214        expressions = expression.args.get(key or "expressions") if expression else sqls
    3215
    3216        if not expressions:
    3217            return ""
    3218
    3219        if flat:
    3220            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    3221
    3222        num_sqls = len(expressions)
    3223
    3224        # These are calculated once in case we have the leading_comma / pretty option set, correspondingly
    3225        pad = " " * len(sep)
    3226        stripped_sep = sep.strip()
    3227
    3228        result_sqls = []
    3229        for i, e in enumerate(expressions):
    3230            sql = self.sql(e, comment=False)
    3231            if not sql:
    3232                continue
    3233
    3234            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    3235
    3236            if self.pretty:
    3237                if self.leading_comma:
    3238                    result_sqls.append(f"{sep if i > 0 else pad}{prefix}{sql}{comments}")
    3239                else:
    3240                    result_sqls.append(
    3241                        f"{prefix}{sql}{stripped_sep if i + 1 < num_sqls else ''}{comments}"
    3242                    )
    3243            else:
    3244                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    3245
    3246        result_sql = "\n".join(result_sqls) if self.pretty else "".join(result_sqls)
    3247        return self.indent(result_sql, skip_first=skip_first) if indent else result_sql

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

    3249    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3250        flat = flat or isinstance(expression.parent, exp.Properties)
    3251        expressions_sql = self.expressions(expression, flat=flat)
    3252        if flat:
    3253            return f"{op} {expressions_sql}"
    3254        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    3256    def naked_property(self, expression: exp.Property) -> str:
    3257        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3258        if not property_name:
    3259            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3260        return f"{property_name} {self.sql(expression, 'this')}"

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

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

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

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

    3268    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3269        this = self.sql(expression, "this")
    3270        expressions = self.no_identify(self.expressions, expression)
    3271        expressions = (
    3272            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3273        )
    3274        return f"{this}{expressions}"

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

    3276    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3277        this = self.sql(expression, "this")
    3278        expressions = self.expressions(expression, flat=True)
    3279        return f"{this}({expressions})"

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

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

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

    3284    def when_sql(self, expression: exp.When) -> str:
    3285        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3286        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3287        condition = self.sql(expression, "condition")
    3288        condition = f" AND {condition}" if condition else ""
    3289
    3290        then_expression = expression.args.get("then")
    3291        if isinstance(then_expression, exp.Insert):
    3292            then = f"INSERT {self.sql(then_expression, 'this')}"
    3293            if "expression" in then_expression.args:
    3294                then += f" VALUES {self.sql(then_expression, 'expression')}"
    3295        elif isinstance(then_expression, exp.Update):
    3296            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3297                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3298            else:
    3299                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    3300        else:
    3301            then = self.sql(then_expression)
    3302        return f"WHEN {matched}{source}{condition} THEN {then}"

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

    3304    def merge_sql(self, expression: exp.Merge) -> str:
    3305        table = expression.this
    3306        table_alias = ""
    3307
    3308        hints = table.args.get("hints")
    3309        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3310            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3311            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3312
    3313        this = self.sql(table)
    3314        using = f"USING {self.sql(expression, 'using')}"
    3315        on = f"ON {self.sql(expression, 'on')}"
    3316        expressions = self.expressions(expression, sep=" ")
    3317
    3318        return self.prepend_ctes(
    3319            expression, f"MERGE INTO {this}{table_alias} {using} {on} {expressions}"
    3320        )

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

    3322    def tochar_sql(self, expression: exp.ToChar) -> str:
    3323        if expression.args.get("format"):
    3324            self.unsupported("Format argument unsupported for TO_CHAR/TO_VARCHAR function")
    3325
    3326        return self.sql(exp.cast(expression.this, "text"))

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

    3328    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3329        if not self.SUPPORTS_TO_NUMBER:
    3330            self.unsupported("Unsupported TO_NUMBER function")
    3331            return self.sql(exp.cast(expression.this, "double"))
    3332
    3333        fmt = expression.args.get("format")
    3334        if not fmt:
    3335            self.unsupported("Conversion format is required for TO_NUMBER")
    3336            return self.sql(exp.cast(expression.this, "double"))
    3337
    3338        return self.func("TO_NUMBER", expression.this, fmt)

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

    3340    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3341        this = self.sql(expression, "this")
    3342        kind = self.sql(expression, "kind")
    3343        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3344        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3345        return f"{this}({kind}{args})"

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

    3347    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3348        this = self.sql(expression, "this")
    3349        max = self.sql(expression, "max")
    3350        min = self.sql(expression, "min")
    3351        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

    3359    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3360        expressions = self.expressions(expression, key="expressions", flat=True)
    3361        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3362        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3363        buckets = self.sql(expression, "buckets")
    3364        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    3366    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3367        this = self.sql(expression, "this")
    3368        having = self.sql(expression, "having")
    3369
    3370        if having:
    3371            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3372
    3373        return self.func("ANY_VALUE", this)

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

    3375    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3376        transform = self.func("TRANSFORM", *expression.expressions)
    3377        row_format_before = self.sql(expression, "row_format_before")
    3378        row_format_before = f" {row_format_before}" if row_format_before else ""
    3379        record_writer = self.sql(expression, "record_writer")
    3380        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3381        using = f" USING {self.sql(expression, 'command_script')}"
    3382        schema = self.sql(expression, "schema")
    3383        schema = f" AS {schema}" if schema else ""
    3384        row_format_after = self.sql(expression, "row_format_after")
    3385        row_format_after = f" {row_format_after}" if row_format_after else ""
    3386        record_reader = self.sql(expression, "record_reader")
    3387        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3388        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

    3390    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3391        key_block_size = self.sql(expression, "key_block_size")
    3392        if key_block_size:
    3393            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3394
    3395        using = self.sql(expression, "using")
    3396        if using:
    3397            return f"USING {using}"
    3398
    3399        parser = self.sql(expression, "parser")
    3400        if parser:
    3401            return f"WITH PARSER {parser}"
    3402
    3403        comment = self.sql(expression, "comment")
    3404        if comment:
    3405            return f"COMMENT {comment}"
    3406
    3407        visible = expression.args.get("visible")
    3408        if visible is not None:
    3409            return "VISIBLE" if visible else "INVISIBLE"
    3410
    3411        engine_attr = self.sql(expression, "engine_attr")
    3412        if engine_attr:
    3413            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3414
    3415        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3416        if secondary_engine_attr:
    3417            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3418
    3419        self.unsupported("Unsupported index constraint option.")
    3420        return ""

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

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

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

    3426    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3427        kind = self.sql(expression, "kind")
    3428        kind = f"{kind} INDEX" if kind else "INDEX"
    3429        this = self.sql(expression, "this")
    3430        this = f" {this}" if this else ""
    3431        index_type = self.sql(expression, "index_type")
    3432        index_type = f" USING {index_type}" if index_type else ""
    3433        schema = self.sql(expression, "schema")
    3434        schema = f" {schema}" if schema else ""
    3435        options = self.expressions(expression, key="options", sep=" ")
    3436        options = f" {options}" if options else ""
    3437        return f"{kind}{this}{index_type}{schema}{options}"

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

    3439    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3440        if self.NVL2_SUPPORTED:
    3441            return self.function_fallback_sql(expression)
    3442
    3443        case = exp.Case().when(
    3444            expression.this.is_(exp.null()).not_(copy=False),
    3445            expression.args["true"],
    3446            copy=False,
    3447        )
    3448        else_cond = expression.args.get("false")
    3449        if else_cond:
    3450            case.else_(else_cond, copy=False)
    3451
    3452        return self.sql(case)

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

    3454    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3455        this = self.sql(expression, "this")
    3456        expr = self.sql(expression, "expression")
    3457        iterator = self.sql(expression, "iterator")
    3458        condition = self.sql(expression, "condition")
    3459        condition = f" IF {condition}" if condition else ""
    3460        return f"{this} FOR {expr} IN {iterator}{condition}"

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

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

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

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

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

    3468    def predict_sql(self, expression: exp.Predict) -> str:
    3469        model = self.sql(expression, "this")
    3470        model = f"MODEL {model}"
    3471        table = self.sql(expression, "expression")
    3472        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    3473        parameters = self.sql(expression, "params_struct")
    3474        return self.func("PREDICT", model, table, parameters or None)

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

    3476    def forin_sql(self, expression: exp.ForIn) -> str:
    3477        this = self.sql(expression, "this")
    3478        expression_sql = self.sql(expression, "expression")
    3479        return f"FOR {this} DO {expression_sql}"

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

    3481    def refresh_sql(self, expression: exp.Refresh) -> str:
    3482        this = self.sql(expression, "this")
    3483        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    3484        return f"REFRESH {table}{this}"

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

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

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

    3489    def toarray_sql(self, expression: exp.ToArray) -> str:
    3490        arg = expression.this
    3491        if not arg.type:
    3492            from sqlglot.optimizer.annotate_types import annotate_types
    3493
    3494            arg = annotate_types(arg)
    3495
    3496        if arg.is_type(exp.DataType.Type.ARRAY):
    3497            return self.sql(arg)
    3498
    3499        cond_for_null = arg.is_(exp.null())
    3500        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

    3502    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    3503        this = expression.this
    3504        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    3505            return self.sql(this)
    3506
    3507        return self.sql(exp.cast(this, "time"))

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

    3509    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    3510        this = expression.this
    3511        time_format = self.format_time(expression)
    3512
    3513        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    3514            return self.sql(
    3515                exp.cast(exp.StrToTime(this=this, format=expression.args["format"]), "date")
    3516            )
    3517
    3518        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    3519            return self.sql(this)
    3520
    3521        return self.sql(exp.cast(this, "date"))

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

    3523    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    3524        return self.sql(
    3525            exp.func(
    3526                "DATEDIFF",
    3527                expression.this,
    3528                exp.cast(exp.Literal.string("1970-01-01"), "date"),
    3529                "day",
    3530            )
    3531        )

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

    3533    def lastday_sql(self, expression: exp.LastDay) -> str:
    3534        if self.LAST_DAY_SUPPORTS_DATE_PART:
    3535            return self.function_fallback_sql(expression)
    3536
    3537        unit = expression.text("unit")
    3538        if unit and unit != "MONTH":
    3539            self.unsupported("Date parts are not supported in LAST_DAY.")
    3540
    3541        return self.func("LAST_DAY", expression.this)

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

    3543    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    3544        if self.CAN_IMPLEMENT_ARRAY_ANY:
    3545            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    3546            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    3547            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    3548            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    3549
    3550        from sqlglot.dialects import Dialect
    3551
    3552        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    3553        if self.dialect.__class__ != Dialect:
    3554            self.unsupported("ARRAY_ANY is unsupported")
    3555
    3556        return self.function_fallback_sql(expression)

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

    3582    def generateseries_sql(self, expression: exp.GenerateSeries) -> str:
    3583        expression.set("is_end_exclusive", None)
    3584        return self.function_fallback_sql(expression)

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

    3586    def struct_sql(self, expression: exp.Struct) -> str:
    3587        expression.set(
    3588            "expressions",
    3589            [
    3590                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    3591                if isinstance(e, exp.PropertyEQ)
    3592                else e
    3593                for e in expression.expressions
    3594            ],
    3595        )
    3596
    3597        return self.function_fallback_sql(expression)

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

    3599    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    3600        low = self.sql(expression, "this")
    3601        high = self.sql(expression, "expression")
    3602
    3603        return f"{low} TO {high}"

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

    3605    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    3606        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    3607        tables = f" {self.expressions(expression)}"
    3608
    3609        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3610
    3611        on_cluster = self.sql(expression, "cluster")
    3612        on_cluster = f" {on_cluster}" if on_cluster else ""
    3613
    3614        identity = self.sql(expression, "identity")
    3615        identity = f" {identity} IDENTITY" if identity else ""
    3616
    3617        option = self.sql(expression, "option")
    3618        option = f" {option}" if option else ""
    3619
    3620        partition = self.sql(expression, "partition")
    3621        partition = f" {partition}" if partition else ""
    3622
    3623        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"

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

    3627    def convert_sql(self, expression: exp.Convert) -> str:
    3628        to = expression.this
    3629        value = expression.expression
    3630        style = expression.args.get("style")
    3631        safe = expression.args.get("safe")
    3632        strict = expression.args.get("strict")
    3633
    3634        if not to or not value:
    3635            return ""
    3636
    3637        # Retrieve length of datatype and override to default if not specified
    3638        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3639            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    3640
    3641        transformed: t.Optional[exp.Expression] = None
    3642        cast = exp.Cast if strict else exp.TryCast
    3643
    3644        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
    3645        if isinstance(style, exp.Literal) and style.is_int:
    3646            from sqlglot.dialects.tsql import TSQL
    3647
    3648            style_value = style.name
    3649            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
    3650            if not converted_style:
    3651                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
    3652
    3653            fmt = exp.Literal.string(converted_style)
    3654
    3655            if to.this == exp.DataType.Type.DATE:
    3656                transformed = exp.StrToDate(this=value, format=fmt)
    3657            elif to.this == exp.DataType.Type.DATETIME:
    3658                transformed = exp.StrToTime(this=value, format=fmt)
    3659            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3660                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
    3661            elif to.this == exp.DataType.Type.TEXT:
    3662                transformed = exp.TimeToStr(this=value, format=fmt)
    3663
    3664        if not transformed:
    3665            transformed = cast(this=value, to=to, safe=safe)
    3666
    3667        return self.sql(transformed)