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

    494    def __init__(
    495        self,
    496        pretty: t.Optional[bool] = None,
    497        identify: str | bool = False,
    498        normalize: bool = False,
    499        pad: int = 2,
    500        indent: int = 2,
    501        normalize_functions: t.Optional[str | bool] = None,
    502        unsupported_level: ErrorLevel = ErrorLevel.WARN,
    503        max_unsupported: int = 3,
    504        leading_comma: bool = False,
    505        max_text_width: int = 80,
    506        comments: bool = True,
    507        dialect: DialectType = None,
    508    ):
    509        import sqlglot
    510        from sqlglot.dialects import Dialect
    511
    512        self.pretty = pretty if pretty is not None else sqlglot.pretty
    513        self.identify = identify
    514        self.normalize = normalize
    515        self.pad = pad
    516        self._indent = indent
    517        self.unsupported_level = unsupported_level
    518        self.max_unsupported = max_unsupported
    519        self.leading_comma = leading_comma
    520        self.max_text_width = max_text_width
    521        self.comments = comments
    522        self.dialect = Dialect.get_or_raise(dialect)
    523
    524        # This is both a Dialect property and a Generator argument, so we prioritize the latter
    525        self.normalize_functions = (
    526            self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
    527        )
    528
    529        self.unsupported_messages: t.List[str] = []
    530        self._escaped_quote_end: str = (
    531            self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END
    532        )
    533        self._escaped_identifier_end: str = (
    534            self.dialect.tokenizer_class.IDENTIFIER_ESCAPES[0] + self.dialect.IDENTIFIER_END
    535        )

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.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.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.HeapProperty'>: <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.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.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <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.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'>, <class 'sqlglot.expressions.JSONPathSelector'>, <class 'sqlglot.expressions.JSONPathSlice'>}
CAN_IMPLEMENT_ARRAY_ANY = False
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'}
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.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.HeapProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.InheritsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <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.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.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.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.NCHAR: 'NCHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.CHAR: 'CHAR'>, <Type.NVARCHAR: 'NVARCHAR'>}
EXPRESSIONS_WITHOUT_NESTED_CTES: Set[Type[sqlglot.expressions.Expression]] = set()
SENTINEL_LINE_BREAK = '__SQLGLOT__LB__'
pretty
identify
normalize
pad
unsupported_level
max_unsupported
leading_comma
max_text_width
comments
dialect
normalize_functions
unsupported_messages: List[str]
def generate( self, expression: sqlglot.expressions.Expression, copy: bool = True) -> str: View Source

    537    def generate(self, expression: exp.Expression, copy: bool = True) -> str:
    538        """
    539        Generates the SQL string corresponding to the given syntax tree.
    540
    541        Args:
    542            expression: The syntax tree.
    543            copy: Whether to copy the expression. The generator performs mutations so
    544                it is safer to copy.
    545
    546        Returns:
    547            The SQL string corresponding to `expression`.
    548        """
    549        if copy:
    550            expression = expression.copy()
    551
    552        expression = self.preprocess(expression)
    553
    554        self.unsupported_messages = []
    555        sql = self.sql(expression).strip()
    556
    557        if self.pretty:
    558            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
    559
    560        if self.unsupported_level == ErrorLevel.IGNORE:
    561            return sql
    562
    563        if self.unsupported_level == ErrorLevel.WARN:
    564            for msg in self.unsupported_messages:
    565                logger.warning(msg)
    566        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
    567            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
    568
    569        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

    571    def preprocess(self, expression: exp.Expression) -> exp.Expression:
    572        """Apply generic preprocessing transformations to a given expression."""
    573        if (
    574            not expression.parent
    575            and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES
    576            and any(node.parent is not expression for node in expression.find_all(exp.With))
    577        ):
    578            from sqlglot.transforms import move_ctes_to_top_level
    579
    580            expression = move_ctes_to_top_level(expression)
    581
    582        if self.ENSURE_BOOLS:
    583            from sqlglot.transforms import ensure_bools
    584
    585            expression = ensure_bools(expression)
    586
    587        return expression

Apply generic preprocessing transformations to a given expression.

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

    589    def unsupported(self, message: str) -> None:
    590        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    591            raise UnsupportedError(message)
    592        self.unsupported_messages.append(message)

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

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

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

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

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

    600    def pad_comment(self, comment: str) -> str:
    601        comment = " " + comment if comment[0].strip() else comment
    602        comment = comment + " " if comment[-1].strip() else comment
    603        return comment

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

    605    def maybe_comment(
    606        self,
    607        sql: str,
    608        expression: t.Optional[exp.Expression] = None,
    609        comments: t.Optional[t.List[str]] = None,
    610    ) -> str:
    611        comments = (
    612            ((expression and expression.comments) if comments is None else comments)  # type: ignore
    613            if self.comments
    614            else None
    615        )
    616
    617        if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
    618            return sql
    619
    620        comments_sql = " ".join(
    621            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
    622        )
    623
    624        if not comments_sql:
    625            return sql
    626
    627        if isinstance(expression, self.WITH_SEPARATED_COMMENTS):
    628            return (
    629                f"{self.sep()}{comments_sql}{sql}"
    630                if sql[0].isspace()
    631                else f"{comments_sql}{self.sep()}{sql}"
    632            )
    633
    634        return f"{sql} {comments_sql}"

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

    636    def wrap(self, expression: exp.Expression | str) -> str:
    637        this_sql = self.indent(
    638            (
    639                self.sql(expression)
    640                if isinstance(expression, exp.UNWRAPPED_QUERIES)
    641                else self.sql(expression, "this")
    642            ),
    643            level=1,
    644            pad=0,
    645        )
    646        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"

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

    648    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    649        original = self.identify
    650        self.identify = False
    651        result = func(*args, **kwargs)
    652        self.identify = original
    653        return result

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

    655    def normalize_func(self, name: str) -> str:
    656        if self.normalize_functions == "upper" or self.normalize_functions is True:
    657            return name.upper()
    658        if self.normalize_functions == "lower":
    659            return name.lower()
    660        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

    662    def indent(
    663        self,
    664        sql: str,
    665        level: int = 0,
    666        pad: t.Optional[int] = None,
    667        skip_first: bool = False,
    668        skip_last: bool = False,
    669    ) -> str:
    670        if not self.pretty:
    671            return sql
    672
    673        pad = self.pad if pad is None else pad
    674        lines = sql.split("\n")
    675
    676        return "\n".join(
    677            (
    678                line
    679                if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
    680                else f"{' ' * (level * self._indent + pad)}{line}"
    681            )
    682            for i, line in enumerate(lines)
    683        )

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

    685    def sql(
    686        self,
    687        expression: t.Optional[str | exp.Expression],
    688        key: t.Optional[str] = None,
    689        comment: bool = True,
    690    ) -> str:
    691        if not expression:
    692            return ""
    693
    694        if isinstance(expression, str):
    695            return expression
    696
    697        if key:
    698            value = expression.args.get(key)
    699            if value:
    700                return self.sql(value)
    701            return ""
    702
    703        transform = self.TRANSFORMS.get(expression.__class__)
    704
    705        if callable(transform):
    706            sql = transform(self, expression)
    707        elif isinstance(expression, exp.Expression):
    708            exp_handler_name = f"{expression.key}_sql"
    709
    710            if hasattr(self, exp_handler_name):
    711                sql = getattr(self, exp_handler_name)(expression)
    712            elif isinstance(expression, exp.Func):
    713                sql = self.function_fallback_sql(expression)
    714            elif isinstance(expression, exp.Property):
    715                sql = self.property_sql(expression)
    716            else:
    717                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
    718        else:
    719            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
    720
    721        return self.maybe_comment(sql, expression) if self.comments and comment else sql

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

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

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

    728    def cache_sql(self, expression: exp.Cache) -> str:
    729        lazy = " LAZY" if expression.args.get("lazy") else ""
    730        table = self.sql(expression, "this")
    731        options = expression.args.get("options")
    732        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
    733        sql = self.sql(expression, "expression")
    734        sql = f" AS{self.sep()}{sql}" if sql else ""
    735        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
    736        return self.prepend_ctes(expression, sql)

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

    738    def characterset_sql(self, expression: exp.CharacterSet) -> str:
    739        if isinstance(expression.parent, exp.Cast):
    740            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
    741        default = "DEFAULT " if expression.args.get("default") else ""
    742        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"

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

    744    def column_sql(self, expression: exp.Column) -> str:
    745        join_mark = " (+)" if expression.args.get("join_mark") else ""
    746
    747        if join_mark and not self.COLUMN_JOIN_MARKS_SUPPORTED:
    748            join_mark = ""
    749            self.unsupported("Outer join syntax using the (+) operator is not supported.")
    750
    751        column = ".".join(
    752            self.sql(part)
    753            for part in (
    754                expression.args.get("catalog"),
    755                expression.args.get("db"),
    756                expression.args.get("table"),
    757                expression.args.get("this"),
    758            )
    759            if part
    760        )
    761
    762        return f"{column}{join_mark}"

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

    764    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    765        this = self.sql(expression, "this")
    766        this = f" {this}" if this else ""
    767        position = self.sql(expression, "position")
    768        return f"{position}{this}"

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

    770    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
    771        column = self.sql(expression, "this")
    772        kind = self.sql(expression, "kind")
    773        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
    774        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
    775        kind = f"{sep}{kind}" if kind else ""
    776        constraints = f" {constraints}" if constraints else ""
    777        position = self.sql(expression, "position")
    778        position = f" {position}" if position else ""
    779
    780        if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:
    781            kind = ""
    782
    783        return f"{exists}{column}{kind}{constraints}{position}"

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

    785    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    786        this = self.sql(expression, "this")
    787        kind_sql = self.sql(expression, "kind").strip()
    788        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

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

    790    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
    791        this = self.sql(expression, "this")
    792        if expression.args.get("not_null"):
    793            persisted = " PERSISTED NOT NULL"
    794        elif expression.args.get("persisted"):
    795            persisted = " PERSISTED"
    796        else:
    797            persisted = ""
    798        return f"AS {this}{persisted}"

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

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

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

    803    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
    804        if isinstance(expression.this, list):
    805            this = self.wrap(self.expressions(expression, key="this", flat=True))
    806        else:
    807            this = self.sql(expression, "this")
    808
    809        return f"COMPRESS {this}"

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

    811    def generatedasidentitycolumnconstraint_sql(
    812        self, expression: exp.GeneratedAsIdentityColumnConstraint
    813    ) -> str:
    814        this = ""
    815        if expression.this is not None:
    816            on_null = " ON NULL" if expression.args.get("on_null") else ""
    817            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
    818
    819        start = expression.args.get("start")
    820        start = f"START WITH {start}" if start else ""
    821        increment = expression.args.get("increment")
    822        increment = f" INCREMENT BY {increment}" if increment else ""
    823        minvalue = expression.args.get("minvalue")
    824        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    825        maxvalue = expression.args.get("maxvalue")
    826        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    827        cycle = expression.args.get("cycle")
    828        cycle_sql = ""
    829
    830        if cycle is not None:
    831            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
    832            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
    833
    834        sequence_opts = ""
    835        if start or increment or cycle_sql:
    836            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
    837            sequence_opts = f" ({sequence_opts.strip()})"
    838
    839        expr = self.sql(expression, "expression")
    840        expr = f"({expr})" if expr else "IDENTITY"
    841
    842        return f"GENERATED{this} AS {expr}{sequence_opts}"

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

    844    def generatedasrowcolumnconstraint_sql(
    845        self, expression: exp.GeneratedAsRowColumnConstraint
    846    ) -> str:
    847        start = "START" if expression.args.get("start") else "END"
    848        hidden = " HIDDEN" if expression.args.get("hidden") else ""
    849        return f"GENERATED ALWAYS AS ROW {start}{hidden}"

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

    851    def periodforsystemtimeconstraint_sql(
    852        self, expression: exp.PeriodForSystemTimeConstraint
    853    ) -> str:
    854        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

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

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

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

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

    862    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    863        desc = expression.args.get("desc")
    864        if desc is not None:
    865            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    866        return "PRIMARY KEY"

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

    868    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    869        this = self.sql(expression, "this")
    870        this = f" {this}" if this else ""
    871        index_type = expression.args.get("index_type")
    872        index_type = f" USING {index_type}" if index_type else ""
    873        return f"UNIQUE{this}{index_type}"

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

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

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

    878    def create_sql(self, expression: exp.Create) -> str:
    879        kind = self.sql(expression, "kind")
    880        properties = expression.args.get("properties")
    881        properties_locs = self.locate_properties(properties) if properties else defaultdict()
    882
    883        this = self.createable_sql(expression, properties_locs)
    884
    885        properties_sql = ""
    886        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
    887            exp.Properties.Location.POST_WITH
    888        ):
    889            properties_sql = self.sql(
    890                exp.Properties(
    891                    expressions=[
    892                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
    893                        *properties_locs[exp.Properties.Location.POST_WITH],
    894                    ]
    895                )
    896            )
    897
    898        begin = " BEGIN" if expression.args.get("begin") else ""
    899        end = " END" if expression.args.get("end") else ""
    900
    901        expression_sql = self.sql(expression, "expression")
    902        if expression_sql:
    903            expression_sql = f"{begin}{self.sep()}{expression_sql}{end}"
    904
    905            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
    906                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
    907                    postalias_props_sql = self.properties(
    908                        exp.Properties(
    909                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
    910                        ),
    911                        wrapped=False,
    912                    )
    913                    expression_sql = f" AS {postalias_props_sql}{expression_sql}"
    914                else:
    915                    expression_sql = f" AS{expression_sql}"
    916
    917        postindex_props_sql = ""
    918        if properties_locs.get(exp.Properties.Location.POST_INDEX):
    919            postindex_props_sql = self.properties(
    920                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
    921                wrapped=False,
    922                prefix=" ",
    923            )
    924
    925        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
    926        indexes = f" {indexes}" if indexes else ""
    927        index_sql = indexes + postindex_props_sql
    928
    929        replace = " OR REPLACE" if expression.args.get("replace") else ""
    930        unique = " UNIQUE" if expression.args.get("unique") else ""
    931
    932        postcreate_props_sql = ""
    933        if properties_locs.get(exp.Properties.Location.POST_CREATE):
    934            postcreate_props_sql = self.properties(
    935                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
    936                sep=" ",
    937                prefix=" ",
    938                wrapped=False,
    939            )
    940
    941        modifiers = "".join((replace, unique, postcreate_props_sql))
    942
    943        postexpression_props_sql = ""
    944        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
    945            postexpression_props_sql = self.properties(
    946                exp.Properties(
    947                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
    948                ),
    949                sep=" ",
    950                prefix=" ",
    951                wrapped=False,
    952            )
    953
    954        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    955        no_schema_binding = (
    956            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
    957        )
    958
    959        clone = self.sql(expression, "clone")
    960        clone = f" {clone}" if clone else ""
    961
    962        expression_sql = f"CREATE{modifiers} {kind}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
    963        return self.prepend_ctes(expression, expression_sql)

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

    965    def clone_sql(self, expression: exp.Clone) -> str:
    966        this = self.sql(expression, "this")
    967        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    968        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
    969        return f"{shallow}{keyword} {this}"

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

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

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

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

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

    979    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    980        with_ = self.sql(expression, "with")
    981        if with_:
    982            sql = f"{with_}{self.sep()}{sql}"
    983        return sql

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

    985    def with_sql(self, expression: exp.With) -> str:
    986        sql = self.expressions(expression, flat=True)
    987        recursive = (
    988            "RECURSIVE "
    989            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
    990            else ""
    991        )
    992
    993        return f"WITH {recursive}{sql}"

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

    995    def cte_sql(self, expression: exp.CTE) -> str:
    996        alias = self.sql(expression, "alias")
    997        return f"{alias} AS {self.wrap(expression)}"

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

     999    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    1000        alias = self.sql(expression, "this")
    1001        columns = self.expressions(expression, key="columns", flat=True)
    1002        columns = f"({columns})" if columns else ""
    1003
    1004        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
    1005            columns = ""
    1006            self.unsupported("Named columns are not supported in table alias.")
    1007
    1008        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
    1009            alias = "_t"
    1010
    1011        return f"{alias}{columns}"

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

    1013    def bitstring_sql(self, expression: exp.BitString) -> str:
    1014        this = self.sql(expression, "this")
    1015        if self.dialect.BIT_START:
    1016            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    1017        return f"{int(this, 2)}"

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

    1019    def hexstring_sql(self, expression: exp.HexString) -> str:
    1020        this = self.sql(expression, "this")
    1021        if self.dialect.HEX_START:
    1022            return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
    1023        return f"{int(this, 16)}"

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

    1025    def bytestring_sql(self, expression: exp.ByteString) -> str:
    1026        this = self.sql(expression, "this")
    1027        if self.dialect.BYTE_START:
    1028            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    1029        return this

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

    1031    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
    1032        this = self.sql(expression, "this")
    1033        escape = expression.args.get("escape")
    1034
    1035        if self.dialect.UNICODE_START:
    1036            escape = f" UESCAPE {self.sql(escape)}" if escape else ""
    1037            return f"{self.dialect.UNICODE_START}{this}{self.dialect.UNICODE_END}{escape}"
    1038
    1039        if escape:
    1040            pattern = re.compile(rf"{escape.name}(\d+)")
    1041        else:
    1042            pattern = ESCAPED_UNICODE_RE
    1043
    1044        this = pattern.sub(r"\\u\1", this)
    1045        return f"{self.dialect.QUOTE_START}{this}{self.dialect.QUOTE_END}"

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

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

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

    1051    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    1052        this = self.sql(expression, "this")
    1053        specifier = self.sql(expression, "expression")
    1054        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    1055        return f"{this}{specifier}"

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

    1057    def datatype_sql(self, expression: exp.DataType) -> str:
    1058        type_value = expression.this
    1059
    1060        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
    1061            type_sql = self.sql(expression, "kind")
    1062        else:
    1063            type_sql = (
    1064                self.TYPE_MAPPING.get(type_value, type_value.value)
    1065                if isinstance(type_value, exp.DataType.Type)
    1066                else type_value
    1067            )
    1068
    1069        nested = ""
    1070        interior = self.expressions(expression, flat=True)
    1071        values = ""
    1072
    1073        if interior:
    1074            if expression.args.get("nested"):
    1075                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    1076                if expression.args.get("values") is not None:
    1077                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    1078                    values = self.expressions(expression, key="values", flat=True)
    1079                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    1080            elif type_value == exp.DataType.Type.INTERVAL:
    1081                nested = f" {interior}"
    1082            else:
    1083                nested = f"({interior})"
    1084
    1085        type_sql = f"{type_sql}{nested}{values}"
    1086        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
    1087            exp.DataType.Type.TIMETZ,
    1088            exp.DataType.Type.TIMESTAMPTZ,
    1089        ):
    1090            type_sql = f"{type_sql} WITH TIME ZONE"
    1091
    1092        return type_sql

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

    1094    def directory_sql(self, expression: exp.Directory) -> str:
    1095        local = "LOCAL " if expression.args.get("local") else ""
    1096        row_format = self.sql(expression, "row_format")
    1097        row_format = f" {row_format}" if row_format else ""
    1098        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

    1100    def delete_sql(self, expression: exp.Delete) -> str:
    1101        this = self.sql(expression, "this")
    1102        this = f" FROM {this}" if this else ""
    1103        using = self.sql(expression, "using")
    1104        using = f" USING {using}" if using else ""
    1105        where = self.sql(expression, "where")
    1106        returning = self.sql(expression, "returning")
    1107        limit = self.sql(expression, "limit")
    1108        tables = self.expressions(expression, key="tables")
    1109        tables = f" {tables}" if tables else ""
    1110        if self.RETURNING_END:
    1111            expression_sql = f"{this}{using}{where}{returning}{limit}"
    1112        else:
    1113            expression_sql = f"{returning}{this}{using}{where}{limit}"
    1114        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

    1116    def drop_sql(self, expression: exp.Drop) -> str:
    1117        this = self.sql(expression, "this")
    1118        kind = expression.args["kind"]
    1119        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    1120        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1121        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    1122        cascade = " CASCADE" if expression.args.get("cascade") else ""
    1123        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    1124        purge = " PURGE" if expression.args.get("purge") else ""
    1125        return (
    1126            f"DROP{temporary}{materialized} {kind}{exists_sql}{this}{cascade}{constraints}{purge}"
    1127        )

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

    1129    def except_sql(self, expression: exp.Except) -> str:
    1130        return self.prepend_ctes(
    1131            expression,
    1132            self.set_operation(expression, self.except_op(expression)),
    1133        )

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

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

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

    1138    def fetch_sql(self, expression: exp.Fetch) -> str:
    1139        direction = expression.args.get("direction")
    1140        direction = f" {direction}" if direction else ""
    1141        count = expression.args.get("count")
    1142        count = f" {count}" if count else ""
    1143        if expression.args.get("percent"):
    1144            count = f"{count} PERCENT"
    1145        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    1146        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"

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

    1148    def filter_sql(self, expression: exp.Filter) -> str:
    1149        if self.AGGREGATE_FILTER_SUPPORTED:
    1150            this = self.sql(expression, "this")
    1151            where = self.sql(expression, "expression").strip()
    1152            return f"{this} FILTER({where})"
    1153
    1154        agg = expression.this
    1155        agg_arg = agg.this
    1156        cond = expression.expression.this
    1157        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1158        return self.sql(agg)

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

    1160    def hint_sql(self, expression: exp.Hint) -> str:
    1161        if not self.QUERY_HINTS:
    1162            self.unsupported("Hints are not supported")
    1163            return ""
    1164
    1165        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

    1167    def index_sql(self, expression: exp.Index) -> str:
    1168        unique = "UNIQUE " if expression.args.get("unique") else ""
    1169        primary = "PRIMARY " if expression.args.get("primary") else ""
    1170        amp = "AMP " if expression.args.get("amp") else ""
    1171        name = self.sql(expression, "this")
    1172        name = f"{name} " if name else ""
    1173        table = self.sql(expression, "table")
    1174        table = f"{self.INDEX_ON} {table}" if table else ""
    1175        using = self.sql(expression, "using")
    1176        using = f" USING {using}" if using else ""
    1177        index = "INDEX " if not table else ""
    1178        columns = self.expressions(expression, key="columns", flat=True)
    1179        columns = f"({columns})" if columns else ""
    1180        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1181        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1182        where = self.sql(expression, "where")
    1183        include = self.expressions(expression, key="include", flat=True)
    1184        if include:
    1185            include = f" INCLUDE ({include})"
    1186        return f"{unique}{primary}{amp}{index}{name}{table}{using}{columns}{include}{partition_by}{where}"

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

    1188    def identifier_sql(self, expression: exp.Identifier) -> str:
    1189        text = expression.name
    1190        lower = text.lower()
    1191        text = lower if self.normalize and not expression.quoted else text
    1192        text = text.replace(self.dialect.IDENTIFIER_END, self._escaped_identifier_end)
    1193        if (
    1194            expression.quoted
    1195            or self.dialect.can_identify(text, self.identify)
    1196            or lower in self.RESERVED_KEYWORDS
    1197            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1198        ):
    1199            text = f"{self.dialect.IDENTIFIER_START}{text}{self.dialect.IDENTIFIER_END}"
    1200        return text

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

    1202    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1203        input_format = self.sql(expression, "input_format")
    1204        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1205        output_format = self.sql(expression, "output_format")
    1206        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1207        return self.sep().join((input_format, output_format))

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

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

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

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

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

    1216    def properties_sql(self, expression: exp.Properties) -> str:
    1217        root_properties = []
    1218        with_properties = []
    1219
    1220        for p in expression.expressions:
    1221            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1222            if p_loc == exp.Properties.Location.POST_WITH:
    1223                with_properties.append(p)
    1224            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1225                root_properties.append(p)
    1226
    1227        return self.root_properties(
    1228            exp.Properties(expressions=root_properties)
    1229        ) + self.with_properties(exp.Properties(expressions=with_properties))

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

    1231    def root_properties(self, properties: exp.Properties) -> str:
    1232        if properties.expressions:
    1233            return self.sep() + self.expressions(properties, indent=False, sep=" ")
    1234        return ""

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

    1236    def properties(
    1237        self,
    1238        properties: exp.Properties,
    1239        prefix: str = "",
    1240        sep: str = ", ",
    1241        suffix: str = "",
    1242        wrapped: bool = True,
    1243    ) -> str:
    1244        if properties.expressions:
    1245            expressions = self.expressions(properties, sep=sep, indent=False)
    1246            if expressions:
    1247                expressions = self.wrap(expressions) if wrapped else expressions
    1248                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1249        return ""

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

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

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

    1254    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1255        properties_locs = defaultdict(list)
    1256        for p in properties.expressions:
    1257            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1258            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1259                properties_locs[p_loc].append(p)
    1260            else:
    1261                self.unsupported(f"Unsupported property {p.key}")
    1262
    1263        return properties_locs

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

    1265    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1266        if isinstance(expression.this, exp.Dot):
    1267            return self.sql(expression, "this")
    1268        return f"'{expression.name}'" if string_key else expression.name

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

    1270    def property_sql(self, expression: exp.Property) -> str:
    1271        property_cls = expression.__class__
    1272        if property_cls == exp.Property:
    1273            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1274
    1275        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1276        if not property_name:
    1277            self.unsupported(f"Unsupported property {expression.key}")
    1278
    1279        return f"{property_name}={self.sql(expression, 'this')}"

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

    1281    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1282        if self.SUPPORTS_CREATE_TABLE_LIKE:
    1283            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1284            options = f" {options}" if options else ""
    1285
    1286            like = f"LIKE {self.sql(expression, 'this')}{options}"
    1287            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
    1288                like = f"({like})"
    1289
    1290            return like
    1291
    1292        if expression.expressions:
    1293            self.unsupported("Transpilation of LIKE property options is unsupported")
    1294
    1295        select = exp.select("*").from_(expression.this).limit(0)
    1296        return f"AS {self.sql(select)}"

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

    1298    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1299        no = "NO " if expression.args.get("no") else ""
    1300        protection = " PROTECTION" if expression.args.get("protection") else ""
    1301        return f"{no}FALLBACK{protection}"

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

    1303    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1304        no = "NO " if expression.args.get("no") else ""
    1305        local = expression.args.get("local")
    1306        local = f"{local} " if local else ""
    1307        dual = "DUAL " if expression.args.get("dual") else ""
    1308        before = "BEFORE " if expression.args.get("before") else ""
    1309        after = "AFTER " if expression.args.get("after") else ""
    1310        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1312    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1313        freespace = self.sql(expression, "this")
    1314        percent = " PERCENT" if expression.args.get("percent") else ""
    1315        return f"FREESPACE={freespace}{percent}"

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

    1317    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1318        if expression.args.get("default"):
    1319            property = "DEFAULT"
    1320        elif expression.args.get("on"):
    1321            property = "ON"
    1322        else:
    1323            property = "OFF"
    1324        return f"CHECKSUM={property}"

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

    1326    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1327        if expression.args.get("no"):
    1328            return "NO MERGEBLOCKRATIO"
    1329        if expression.args.get("default"):
    1330            return "DEFAULT MERGEBLOCKRATIO"
    1331
    1332        percent = " PERCENT" if expression.args.get("percent") else ""
    1333        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1335    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1336        default = expression.args.get("default")
    1337        minimum = expression.args.get("minimum")
    1338        maximum = expression.args.get("maximum")
    1339        if default or minimum or maximum:
    1340            if default:
    1341                prop = "DEFAULT"
    1342            elif minimum:
    1343                prop = "MINIMUM"
    1344            else:
    1345                prop = "MAXIMUM"
    1346            return f"{prop} DATABLOCKSIZE"
    1347        units = expression.args.get("units")
    1348        units = f" {units}" if units else ""
    1349        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1351    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1352        autotemp = expression.args.get("autotemp")
    1353        always = expression.args.get("always")
    1354        default = expression.args.get("default")
    1355        manual = expression.args.get("manual")
    1356        never = expression.args.get("never")
    1357
    1358        if autotemp is not None:
    1359            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1360        elif always:
    1361            prop = "ALWAYS"
    1362        elif default:
    1363            prop = "DEFAULT"
    1364        elif manual:
    1365            prop = "MANUAL"
    1366        elif never:
    1367            prop = "NEVER"
    1368        return f"BLOCKCOMPRESSION={prop}"

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

    1370    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1371        no = expression.args.get("no")
    1372        no = " NO" if no else ""
    1373        concurrent = expression.args.get("concurrent")
    1374        concurrent = " CONCURRENT" if concurrent else ""
    1375
    1376        for_ = ""
    1377        if expression.args.get("for_all"):
    1378            for_ = " FOR ALL"
    1379        elif expression.args.get("for_insert"):
    1380            for_ = " FOR INSERT"
    1381        elif expression.args.get("for_none"):
    1382            for_ = " FOR NONE"
    1383        return f"WITH{no}{concurrent} ISOLATED LOADING{for_}"

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

    1385    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1386        if isinstance(expression.this, list):
    1387            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1388        if expression.this:
    1389            modulus = self.sql(expression, "this")
    1390            remainder = self.sql(expression, "expression")
    1391            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1392
    1393        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1394        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1395        return f"FROM ({from_expressions}) TO ({to_expressions})"

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

    1397    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1398        this = self.sql(expression, "this")
    1399
    1400        for_values_or_default = expression.expression
    1401        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1402            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1403        else:
    1404            for_values_or_default = " DEFAULT"
    1405
    1406        return f"PARTITION OF {this}{for_values_or_default}"

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

    1408    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1409        kind = expression.args.get("kind")
    1410        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1411        for_or_in = expression.args.get("for_or_in")
    1412        for_or_in = f" {for_or_in}" if for_or_in else ""
    1413        lock_type = expression.args.get("lock_type")
    1414        override = " OVERRIDE" if expression.args.get("override") else ""
    1415        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"

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

    1417    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1418        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1419        statistics = expression.args.get("statistics")
    1420        statistics_sql = ""
    1421        if statistics is not None:
    1422            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1423        return f"{data_sql}{statistics_sql}"

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

    1425    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1426        sql = "WITH(SYSTEM_VERSIONING=ON"
    1427
    1428        if expression.this:
    1429            history_table = self.sql(expression, "this")
    1430            sql = f"{sql}(HISTORY_TABLE={history_table}"
    1431
    1432            if expression.expression:
    1433                data_consistency_check = self.sql(expression, "expression")
    1434                sql = f"{sql}, DATA_CONSISTENCY_CHECK={data_consistency_check}"
    1435
    1436            sql = f"{sql})"
    1437
    1438        return f"{sql})"

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

    1440    def insert_sql(self, expression: exp.Insert) -> str:
    1441        overwrite = expression.args.get("overwrite")
    1442
    1443        if isinstance(expression.this, exp.Directory):
    1444            this = " OVERWRITE" if overwrite else " INTO"
    1445        else:
    1446            this = self.INSERT_OVERWRITE if overwrite else " INTO"
    1447
    1448        alternative = expression.args.get("alternative")
    1449        alternative = f" OR {alternative}" if alternative else ""
    1450        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1451
    1452        this = f"{this} {self.sql(expression, 'this')}"
    1453
    1454        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1455        partition_sql = (
    1456            f" {self.sql(expression, 'partition')}" if expression.args.get("partition") else ""
    1457        )
    1458        where = self.sql(expression, "where")
    1459        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1460        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1461        conflict = self.sql(expression, "conflict")
    1462        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1463        returning = self.sql(expression, "returning")
    1464
    1465        if self.RETURNING_END:
    1466            expression_sql = f"{expression_sql}{conflict}{returning}"
    1467        else:
    1468            expression_sql = f"{returning}{expression_sql}{conflict}"
    1469
    1470        sql = f"INSERT{alternative}{ignore}{this}{by_name}{exists}{partition_sql}{where}{expression_sql}"
    1471        return self.prepend_ctes(expression, sql)

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

    1473    def intersect_sql(self, expression: exp.Intersect) -> str:
    1474        return self.prepend_ctes(
    1475            expression,
    1476            self.set_operation(expression, self.intersect_op(expression)),
    1477        )

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

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

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

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

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

    1485    def kill_sql(self, expression: exp.Kill) -> str:
    1486        kind = self.sql(expression, "kind")
    1487        kind = f" {kind}" if kind else ""
    1488        this = self.sql(expression, "this")
    1489        this = f" {this}" if this else ""
    1490        return f"KILL{kind}{this}"

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

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

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

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

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

    1498    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1499        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1500        constraint = self.sql(expression, "constraint")
    1501        if constraint:
    1502            constraint = f"ON CONSTRAINT {constraint}"
    1503        key = self.expressions(expression, key="key", flat=True)
    1504        do = "" if expression.args.get("duplicate") else " DO "
    1505        nothing = "NOTHING" if expression.args.get("nothing") else ""
    1506        expressions = self.expressions(expression, flat=True)
    1507        set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1508        if expressions:
    1509            expressions = f"UPDATE {set_keyword}{expressions}"
    1510        return f"{self.seg(conflict)} {constraint}{key}{do}{nothing}{expressions}"

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

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

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

    1515    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1516        fields = expression.args.get("fields")
    1517        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1518        escaped = expression.args.get("escaped")
    1519        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1520        items = expression.args.get("collection_items")
    1521        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1522        keys = expression.args.get("map_keys")
    1523        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1524        lines = expression.args.get("lines")
    1525        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1526        null = expression.args.get("null")
    1527        null = f" NULL DEFINED AS {null}" if null else ""
    1528        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1533    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1534        this = f"{self.sql(expression, 'this')} INDEX"
    1535        target = self.sql(expression, "target")
    1536        target = f" FOR {target}" if target else ""
    1537        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1539    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1540        this = self.sql(expression, "this")
    1541        kind = self.sql(expression, "kind")
    1542        expr = self.sql(expression, "expression")
    1543        return f"{this} ({kind} => {expr})"

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

    1545    def table_parts(self, expression: exp.Table) -> str:
    1546        return ".".join(
    1547            self.sql(part)
    1548            for part in (
    1549                expression.args.get("catalog"),
    1550                expression.args.get("db"),
    1551                expression.args.get("this"),
    1552            )
    1553            if part is not None
    1554        )

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

    1556    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1557        table = self.table_parts(expression)
    1558        only = "ONLY " if expression.args.get("only") else ""
    1559        version = self.sql(expression, "version")
    1560        version = f" {version}" if version else ""
    1561        alias = self.sql(expression, "alias")
    1562        alias = f"{sep}{alias}" if alias else ""
    1563        hints = self.expressions(expression, key="hints", sep=" ")
    1564        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1565        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1566        pivots = f" {pivots}" if pivots else ""
    1567        joins = self.expressions(expression, key="joins", sep="", skip_first=True)
    1568        laterals = self.expressions(expression, key="laterals", sep="")
    1569
    1570        file_format = self.sql(expression, "format")
    1571        if file_format:
    1572            pattern = self.sql(expression, "pattern")
    1573            pattern = f", PATTERN => {pattern}" if pattern else ""
    1574            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    1575
    1576        ordinality = expression.args.get("ordinality") or ""
    1577        if ordinality:
    1578            ordinality = f" WITH ORDINALITY{alias}"
    1579            alias = ""
    1580
    1581        when = self.sql(expression, "when")
    1582        if when:
    1583            table = f"{table} {when}"
    1584
    1585        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

    1587    def tablesample_sql(
    1588        self,
    1589        expression: exp.TableSample,
    1590        sep: str = " AS ",
    1591        tablesample_keyword: t.Optional[str] = None,
    1592    ) -> str:
    1593        if self.dialect.ALIAS_POST_TABLESAMPLE and expression.this and expression.this.alias:
    1594            table = expression.this.copy()
    1595            table.set("alias", None)
    1596            this = self.sql(table)
    1597            alias = f"{sep}{self.sql(expression.this, 'alias')}"
    1598        else:
    1599            this = self.sql(expression, "this")
    1600            alias = ""
    1601
    1602        method = self.sql(expression, "method")
    1603        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1604        numerator = self.sql(expression, "bucket_numerator")
    1605        denominator = self.sql(expression, "bucket_denominator")
    1606        field = self.sql(expression, "bucket_field")
    1607        field = f" ON {field}" if field else ""
    1608        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1609        seed = self.sql(expression, "seed")
    1610        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
    1611
    1612        size = self.sql(expression, "size")
    1613        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
    1614            size = f"{size} ROWS"
    1615
    1616        percent = self.sql(expression, "percent")
    1617        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
    1618            percent = f"{percent} PERCENT"
    1619
    1620        expr = f"{bucket}{percent}{size}"
    1621        if self.TABLESAMPLE_REQUIRES_PARENS:
    1622            expr = f"({expr})"
    1623
    1624        return (
    1625            f"{this} {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}{alias}"
    1626        )

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

    1628    def pivot_sql(self, expression: exp.Pivot) -> str:
    1629        expressions = self.expressions(expression, flat=True)
    1630
    1631        if expression.this:
    1632            this = self.sql(expression, "this")
    1633            if not expressions:
    1634                return f"UNPIVOT {this}"
    1635
    1636            on = f"{self.seg('ON')} {expressions}"
    1637            using = self.expressions(expression, key="using", flat=True)
    1638            using = f"{self.seg('USING')} {using}" if using else ""
    1639            group = self.sql(expression, "group")
    1640            return f"PIVOT {this}{on}{using}{group}"
    1641
    1642        alias = self.sql(expression, "alias")
    1643        alias = f" AS {alias}" if alias else ""
    1644        direction = "UNPIVOT" if expression.unpivot else "PIVOT"
    1645        field = self.sql(expression, "field")
    1646        include_nulls = expression.args.get("include_nulls")
    1647        if include_nulls is not None:
    1648            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    1649        else:
    1650            nulls = ""
    1651        return f"{direction}{nulls}({expressions} FOR {field}){alias}"

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

    1653    def version_sql(self, expression: exp.Version) -> str:
    1654        this = f"FOR {expression.name}"
    1655        kind = expression.text("kind")
    1656        expr = self.sql(expression, "expression")
    1657        return f"{this} {kind} {expr}"

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

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

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

    1662    def update_sql(self, expression: exp.Update) -> str:
    1663        this = self.sql(expression, "this")
    1664        set_sql = self.expressions(expression, flat=True)
    1665        from_sql = self.sql(expression, "from")
    1666        where_sql = self.sql(expression, "where")
    1667        returning = self.sql(expression, "returning")
    1668        order = self.sql(expression, "order")
    1669        limit = self.sql(expression, "limit")
    1670        if self.RETURNING_END:
    1671            expression_sql = f"{from_sql}{where_sql}{returning}"
    1672        else:
    1673            expression_sql = f"{returning}{from_sql}{where_sql}"
    1674        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    1675        return self.prepend_ctes(expression, sql)

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

    1677    def values_sql(self, expression: exp.Values) -> str:
    1678        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    1679        if self.VALUES_AS_TABLE or not expression.find_ancestor(exp.From, exp.Join):
    1680            args = self.expressions(expression)
    1681            alias = self.sql(expression, "alias")
    1682            values = f"VALUES{self.seg('')}{args}"
    1683            values = (
    1684                f"({values})"
    1685                if self.WRAP_DERIVED_VALUES and (alias or isinstance(expression.parent, exp.From))
    1686                else values
    1687            )
    1688            return f"{values} AS {alias}" if alias else values
    1689
    1690        # Converts `VALUES...` expression into a series of select unions.
    1691        alias_node = expression.args.get("alias")
    1692        column_names = alias_node and alias_node.columns
    1693
    1694        selects: t.List[exp.Query] = []
    1695
    1696        for i, tup in enumerate(expression.expressions):
    1697            row = tup.expressions
    1698
    1699            if i == 0 and column_names:
    1700                row = [
    1701                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    1702                ]
    1703
    1704            selects.append(exp.Select(expressions=row))
    1705
    1706        if self.pretty:
    1707            # This may result in poor performance for large-cardinality `VALUES` tables, due to
    1708            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
    1709            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
    1710            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
    1711            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
    1712
    1713        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
    1714        unions = " UNION ALL ".join(self.sql(select) for select in selects)
    1715        return f"({unions}){alias}"

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

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

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

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

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

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

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

    1728    def group_sql(self, expression: exp.Group) -> str:
    1729        group_by = self.op_expressions("GROUP BY", expression)
    1730
    1731        if expression.args.get("all"):
    1732            return f"{group_by} ALL"
    1733
    1734        grouping_sets = self.expressions(expression, key="grouping_sets", indent=False)
    1735        grouping_sets = (
    1736            f"{self.seg('GROUPING SETS')} {self.wrap(grouping_sets)}" if grouping_sets else ""
    1737        )
    1738
    1739        cube = expression.args.get("cube", [])
    1740        if seq_get(cube, 0) is True:
    1741            return f"{group_by}{self.seg('WITH CUBE')}"
    1742        else:
    1743            cube_sql = self.expressions(expression, key="cube", indent=False)
    1744            cube_sql = f"{self.seg('CUBE')} {self.wrap(cube_sql)}" if cube_sql else ""
    1745
    1746        rollup = expression.args.get("rollup", [])
    1747        if seq_get(rollup, 0) is True:
    1748            return f"{group_by}{self.seg('WITH ROLLUP')}"
    1749        else:
    1750            rollup_sql = self.expressions(expression, key="rollup", indent=False)
    1751            rollup_sql = f"{self.seg('ROLLUP')} {self.wrap(rollup_sql)}" if rollup_sql else ""
    1752
    1753        groupings = csv(
    1754            grouping_sets,
    1755            cube_sql,
    1756            rollup_sql,
    1757            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    1758            sep=self.GROUPINGS_SEP,
    1759        )
    1760
    1761        if expression.args.get("expressions") and groupings:
    1762            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    1763
    1764        return f"{group_by}{groupings}"

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

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

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

    1770    def connect_sql(self, expression: exp.Connect) -> str:
    1771        start = self.sql(expression, "start")
    1772        start = self.seg(f"START WITH {start}") if start else ""
    1773        connect = self.sql(expression, "connect")
    1774        connect = self.seg(f"CONNECT BY {connect}")
    1775        return start + connect

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

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

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

    1780    def join_sql(self, expression: exp.Join) -> str:
    1781        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    1782            side = None
    1783        else:
    1784            side = expression.side
    1785
    1786        op_sql = " ".join(
    1787            op
    1788            for op in (
    1789                expression.method,
    1790                "GLOBAL" if expression.args.get("global") else None,
    1791                side,
    1792                expression.kind,
    1793                expression.hint if self.JOIN_HINTS else None,
    1794            )
    1795            if op
    1796        )
    1797        on_sql = self.sql(expression, "on")
    1798        using = expression.args.get("using")
    1799
    1800        if not on_sql and using:
    1801            on_sql = csv(*(self.sql(column) for column in using))
    1802
    1803        this = expression.this
    1804        this_sql = self.sql(this)
    1805
    1806        if on_sql:
    1807            on_sql = self.indent(on_sql, skip_first=True)
    1808            space = self.seg(" " * self.pad) if self.pretty else " "
    1809            if using:
    1810                on_sql = f"{space}USING ({on_sql})"
    1811            else:
    1812                on_sql = f"{space}ON {on_sql}"
    1813        elif not op_sql:
    1814            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
    1815                return f" {this_sql}"
    1816
    1817            return f", {this_sql}"
    1818
    1819        op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    1820        return f"{self.seg(op_sql)} {this_sql}{on_sql}"

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

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

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

    1827    def lateral_op(self, expression: exp.Lateral) -> str:
    1828        cross_apply = expression.args.get("cross_apply")
    1829
    1830        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    1831        if cross_apply is True:
    1832            op = "INNER JOIN "
    1833        elif cross_apply is False:
    1834            op = "LEFT JOIN "
    1835        else:
    1836            op = ""
    1837
    1838        return f"{op}LATERAL"

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

    1840    def lateral_sql(self, expression: exp.Lateral) -> str:
    1841        this = self.sql(expression, "this")
    1842
    1843        if expression.args.get("view"):
    1844            alias = expression.args["alias"]
    1845            columns = self.expressions(alias, key="columns", flat=True)
    1846            table = f" {alias.name}" if alias.name else ""
    1847            columns = f" AS {columns}" if columns else ""
    1848            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    1849            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    1850
    1851        alias = self.sql(expression, "alias")
    1852        alias = f" AS {alias}" if alias else ""
    1853        return f"{self.lateral_op(expression)} {this}{alias}"

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

    1855    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    1856        this = self.sql(expression, "this")
    1857
    1858        args = [
    1859            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    1860            for e in (expression.args.get(k) for k in ("offset", "expression"))
    1861            if e
    1862        ]
    1863
    1864        args_sql = ", ".join(self.sql(e) for e in args)
    1865        args_sql = f"({args_sql})" if any(top and not e.is_number for e in args) else args_sql
    1866        expressions = self.expressions(expression, flat=True)
    1867        expressions = f" BY {expressions}" if expressions else ""
    1868
    1869        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}"

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

    1871    def offset_sql(self, expression: exp.Offset) -> str:
    1872        this = self.sql(expression, "this")
    1873        value = expression.expression
    1874        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    1875        expressions = self.expressions(expression, flat=True)
    1876        expressions = f" BY {expressions}" if expressions else ""
    1877        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"

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

    1879    def setitem_sql(self, expression: exp.SetItem) -> str:
    1880        kind = self.sql(expression, "kind")
    1881        kind = f"{kind} " if kind else ""
    1882        this = self.sql(expression, "this")
    1883        expressions = self.expressions(expression)
    1884        collate = self.sql(expression, "collate")
    1885        collate = f" COLLATE {collate}" if collate else ""
    1886        global_ = "GLOBAL " if expression.args.get("global") else ""
    1887        return f"{global_}{kind}{this}{expressions}{collate}"

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

    1889    def set_sql(self, expression: exp.Set) -> str:
    1890        expressions = (
    1891            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    1892        )
    1893        tag = " TAG" if expression.args.get("tag") else ""
    1894        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"

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

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

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

    1899    def lock_sql(self, expression: exp.Lock) -> str:
    1900        if not self.LOCKING_READS_SUPPORTED:
    1901            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    1902            return ""
    1903
    1904        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    1905        expressions = self.expressions(expression, flat=True)
    1906        expressions = f" OF {expressions}" if expressions else ""
    1907        wait = expression.args.get("wait")
    1908
    1909        if wait is not None:
    1910            if isinstance(wait, exp.Literal):
    1911                wait = f" WAIT {self.sql(wait)}"
    1912            else:
    1913                wait = " NOWAIT" if wait else " SKIP LOCKED"
    1914
    1915        return f"{lock_type}{expressions}{wait or ''}"

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

    1917    def literal_sql(self, expression: exp.Literal) -> str:
    1918        text = expression.this or ""
    1919        if expression.is_string:
    1920            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    1921        return text

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

    1923    def escape_str(self, text: str) -> str:
    1924        text = text.replace(self.dialect.QUOTE_END, self._escaped_quote_end)
    1925        if self.dialect.INVERSE_ESCAPE_SEQUENCES:
    1926            text = "".join(self.dialect.INVERSE_ESCAPE_SEQUENCES.get(ch, ch) for ch in text)
    1927        elif self.pretty:
    1928            text = text.replace("\n", self.SENTINEL_LINE_BREAK)
    1929        return text

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

    1931    def loaddata_sql(self, expression: exp.LoadData) -> str:
    1932        local = " LOCAL" if expression.args.get("local") else ""
    1933        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    1934        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    1935        this = f" INTO TABLE {self.sql(expression, 'this')}"
    1936        partition = self.sql(expression, "partition")
    1937        partition = f" {partition}" if partition else ""
    1938        input_format = self.sql(expression, "input_format")
    1939        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    1940        serde = self.sql(expression, "serde")
    1941        serde = f" SERDE {serde}" if serde else ""
    1942        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    1944    def null_sql(self, *_) -> str:
    1945        return "NULL"

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

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

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

    1950    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    1951        this = self.sql(expression, "this")
    1952        this = f"{this} " if this else this
    1953        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    1954        order = self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat)  # type: ignore
    1955        interpolated_values = [
    1956            f"{self.sql(named_expression, 'alias')} AS {self.sql(named_expression, 'this')}"
    1957            for named_expression in expression.args.get("interpolate") or []
    1958        ]
    1959        interpolate = (
    1960            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    1961        )
    1962        return f"{order}{interpolate}"

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

    1964    def withfill_sql(self, expression: exp.WithFill) -> str:
    1965        from_sql = self.sql(expression, "from")
    1966        from_sql = f" FROM {from_sql}" if from_sql else ""
    1967        to_sql = self.sql(expression, "to")
    1968        to_sql = f" TO {to_sql}" if to_sql else ""
    1969        step_sql = self.sql(expression, "step")
    1970        step_sql = f" STEP {step_sql}" if step_sql else ""
    1971        return f"WITH FILL{from_sql}{to_sql}{step_sql}"

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

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

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

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

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

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

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

    1982    def ordered_sql(self, expression: exp.Ordered) -> str:
    1983        desc = expression.args.get("desc")
    1984        asc = not desc
    1985
    1986        nulls_first = expression.args.get("nulls_first")
    1987        nulls_last = not nulls_first
    1988        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
    1989        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
    1990        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
    1991
    1992        this = self.sql(expression, "this")
    1993
    1994        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
    1995        nulls_sort_change = ""
    1996        if nulls_first and (
    1997            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    1998        ):
    1999            nulls_sort_change = " NULLS FIRST"
    2000        elif (
    2001            nulls_last
    2002            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    2003            and not nulls_are_last
    2004        ):
    2005            nulls_sort_change = " NULLS LAST"
    2006
    2007        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
    2008        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    2009            window = expression.find_ancestor(exp.Window, exp.Select)
    2010            if isinstance(window, exp.Window) and window.args.get("spec"):
    2011                self.unsupported(
    2012                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
    2013                )
    2014                nulls_sort_change = ""
    2015            elif self.NULL_ORDERING_SUPPORTED is None:
    2016                if expression.this.is_int:
    2017                    self.unsupported(
    2018                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
    2019                    )
    2020                else:
    2021                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
    2022                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
    2023                nulls_sort_change = ""
    2024
    2025        with_fill = self.sql(expression, "with_fill")
    2026        with_fill = f" {with_fill}" if with_fill else ""
    2027
    2028        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"

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

    2030    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    2031        partition = self.partition_by_sql(expression)
    2032        order = self.sql(expression, "order")
    2033        measures = self.expressions(expression, key="measures")
    2034        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    2035        rows = self.sql(expression, "rows")
    2036        rows = self.seg(rows) if rows else ""
    2037        after = self.sql(expression, "after")
    2038        after = self.seg(after) if after else ""
    2039        pattern = self.sql(expression, "pattern")
    2040        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    2041        definition_sqls = [
    2042            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    2043            for definition in expression.args.get("define", [])
    2044        ]
    2045        definitions = self.expressions(sqls=definition_sqls)
    2046        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    2047        body = "".join(
    2048            (
    2049                partition,
    2050                order,
    2051                measures,
    2052                rows,
    2053                after,
    2054                pattern,
    2055                define,
    2056            )
    2057        )
    2058        alias = self.sql(expression, "alias")
    2059        alias = f" {alias}" if alias else ""
    2060        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    2062    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    2063        limit: t.Optional[exp.Fetch | exp.Limit] = expression.args.get("limit")
    2064
    2065        # If the limit is generated as TOP, we need to ensure it's not generated twice
    2066        with_offset_limit_modifiers = not isinstance(limit, exp.Limit) or not self.LIMIT_IS_TOP
    2067
    2068        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    2069            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    2070        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    2071            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    2072
    2073        fetch = isinstance(limit, exp.Fetch)
    2074
    2075        offset_limit_modifiers = (
    2076            self.offset_limit_modifiers(expression, fetch, limit)
    2077            if with_offset_limit_modifiers
    2078            else []
    2079        )
    2080
    2081        options = self.expressions(expression, key="options")
    2082        if options:
    2083            options = f" OPTION{self.wrap(options)}"
    2084
    2085        return csv(
    2086            *sqls,
    2087            *[self.sql(join) for join in expression.args.get("joins") or []],
    2088            self.sql(expression, "connect"),
    2089            self.sql(expression, "match"),
    2090            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2091            self.sql(expression, "prewhere"),
    2092            self.sql(expression, "where"),
    2093            self.sql(expression, "group"),
    2094            self.sql(expression, "having"),
    2095            *self.after_having_modifiers(expression),
    2096            self.sql(expression, "order"),
    2097            *offset_limit_modifiers,
    2098            *self.after_limit_modifiers(expression),
    2099            options,
    2100            sep="",
    2101        )

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

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

    2106    def offset_limit_modifiers(
    2107        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2108    ) -> t.List[str]:
    2109        return [
    2110            self.sql(expression, "offset") if fetch else self.sql(limit),
    2111            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2112        ]

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

    2114    def after_having_modifiers(self, expression: exp.Expression) -> t.List[str]:
    2115        return [
    2116            self.sql(expression, "qualify"),
    2117            (
    2118                self.seg("WINDOW ") + self.expressions(expression, key="windows", flat=True)
    2119                if expression.args.get("windows")
    2120                else ""
    2121            ),
    2122            self.sql(expression, "distribute"),
    2123            self.sql(expression, "sort"),
    2124            self.sql(expression, "cluster"),
    2125        ]

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

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

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

    2132    def select_sql(self, expression: exp.Select) -> str:
    2133        into = expression.args.get("into")
    2134        if not self.SUPPORTS_SELECT_INTO and into:
    2135            into.pop()
    2136
    2137        hint = self.sql(expression, "hint")
    2138        distinct = self.sql(expression, "distinct")
    2139        distinct = f" {distinct}" if distinct else ""
    2140        kind = self.sql(expression, "kind")
    2141        limit = expression.args.get("limit")
    2142        top = (
    2143            self.limit_sql(limit, top=True)
    2144            if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP
    2145            else ""
    2146        )
    2147
    2148        expressions = self.expressions(expression)
    2149
    2150        if kind:
    2151            if kind in self.SELECT_KINDS:
    2152                kind = f" AS {kind}"
    2153            else:
    2154                if kind == "STRUCT":
    2155                    expressions = self.expressions(
    2156                        sqls=[
    2157                            self.sql(
    2158                                exp.Struct(
    2159                                    expressions=[
    2160                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
    2161                                        if isinstance(e, exp.Alias)
    2162                                        else e
    2163                                        for e in expression.expressions
    2164                                    ]
    2165                                )
    2166                            )
    2167                        ]
    2168                    )
    2169                kind = ""
    2170
    2171        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
    2172        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
    2173        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
    2174        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    2175        sql = self.query_modifiers(
    2176            expression,
    2177            f"SELECT{top_distinct}{kind}{expressions}",
    2178            self.sql(expression, "into", comment=False),
    2179            self.sql(expression, "from", comment=False),
    2180        )
    2181
    2182        sql = self.prepend_ctes(expression, sql)
    2183
    2184        if not self.SUPPORTS_SELECT_INTO and into:
    2185            if into.args.get("temporary"):
    2186                table_kind = " TEMPORARY"
    2187            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
    2188                table_kind = " UNLOGGED"
    2189            else:
    2190                table_kind = ""
    2191            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
    2192
    2193        return sql

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

    2195    def schema_sql(self, expression: exp.Schema) -> str:
    2196        this = self.sql(expression, "this")
    2197        sql = self.schema_columns_sql(expression)
    2198        return f"{this} {sql}" if this and sql else this or sql

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

    2200    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2201        if expression.expressions:
    2202            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2203        return ""

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

    2205    def star_sql(self, expression: exp.Star) -> str:
    2206        except_ = self.expressions(expression, key="except", flat=True)
    2207        except_ = f"{self.seg(self.STAR_MAPPING['except'])} ({except_})" if except_ else ""
    2208        replace = self.expressions(expression, key="replace", flat=True)
    2209        replace = f"{self.seg(self.STAR_MAPPING['replace'])} ({replace})" if replace else ""
    2210        return f"*{except_}{replace}"

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

    2212    def parameter_sql(self, expression: exp.Parameter) -> str:
    2213        this = self.sql(expression, "this")
    2214        return f"{self.PARAMETER_TOKEN}{this}"

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

    2216    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2217        this = self.sql(expression, "this")
    2218        kind = expression.text("kind")
    2219        if kind:
    2220            kind = f"{kind}."
    2221        return f"@@{kind}{this}"

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

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

    2226    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2227        alias = self.sql(expression, "alias")
    2228        alias = f"{sep}{alias}" if alias else ""
    2229
    2230        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    2231        pivots = f" {pivots}" if pivots else ""
    2232
    2233        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2234        return self.prepend_ctes(expression, sql)

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

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

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

    2240    def union_sql(self, expression: exp.Union) -> str:
    2241        return self.prepend_ctes(
    2242            expression,
    2243            self.set_operation(expression, self.union_op(expression)),
    2244        )

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

    2246    def union_op(self, expression: exp.Union) -> str:
    2247        kind = " DISTINCT" if self.EXPLICIT_UNION else ""
    2248        kind = kind if expression.args.get("distinct") else " ALL"
    2249        by_name = " BY NAME" if expression.args.get("by_name") else ""
    2250        return f"UNION{kind}{by_name}"

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

    2252    def unnest_sql(self, expression: exp.Unnest) -> str:
    2253        args = self.expressions(expression, flat=True)
    2254
    2255        alias = expression.args.get("alias")
    2256        offset = expression.args.get("offset")
    2257
    2258        if self.UNNEST_WITH_ORDINALITY:
    2259            if alias and isinstance(offset, exp.Expression):
    2260                alias.append("columns", offset)
    2261
    2262        if alias and self.dialect.UNNEST_COLUMN_ONLY:
    2263            columns = alias.columns
    2264            alias = self.sql(columns[0]) if columns else ""
    2265        else:
    2266            alias = self.sql(alias)
    2267
    2268        alias = f" AS {alias}" if alias else alias
    2269        if self.UNNEST_WITH_ORDINALITY:
    2270            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2271        else:
    2272            if isinstance(offset, exp.Expression):
    2273                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2274            elif offset:
    2275                suffix = f"{alias} WITH OFFSET"
    2276            else:
    2277                suffix = alias
    2278
    2279        return f"UNNEST({args}){suffix}"

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

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

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

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

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

    2288    def window_sql(self, expression: exp.Window) -> str:
    2289        this = self.sql(expression, "this")
    2290        partition = self.partition_by_sql(expression)
    2291        order = expression.args.get("order")
    2292        order = self.order_sql(order, flat=True) if order else ""
    2293        spec = self.sql(expression, "spec")
    2294        alias = self.sql(expression, "alias")
    2295        over = self.sql(expression, "over") or "OVER"
    2296
    2297        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2298
    2299        first = expression.args.get("first")
    2300        if first is None:
    2301            first = ""
    2302        else:
    2303            first = "FIRST" if first else "LAST"
    2304
    2305        if not partition and not order and not spec and alias:
    2306            return f"{this} {alias}"
    2307
    2308        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    2309        return f"{this} ({args})"

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

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

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

    2315    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2316        kind = self.sql(expression, "kind")
    2317        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2318        end = (
    2319            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2320            or "CURRENT ROW"
    2321        )
    2322        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    2329    def between_sql(self, expression: exp.Between) -> str:
    2330        this = self.sql(expression, "this")
    2331        low = self.sql(expression, "low")
    2332        high = self.sql(expression, "high")
    2333        return f"{this} BETWEEN {low} AND {high}"

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

    2335    def bracket_sql(self, expression: exp.Bracket) -> str:
    2336        expressions = apply_index_offset(
    2337            expression.this,
    2338            expression.expressions,
    2339            self.dialect.INDEX_OFFSET - expression.args.get("offset", 0),
    2340        )
    2341        expressions_sql = ", ".join(self.sql(e) for e in expressions)
    2342        return f"{self.sql(expression, 'this')}[{expressions_sql}]"

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

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

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

    2347    def any_sql(self, expression: exp.Any) -> str:
    2348        this = self.sql(expression, "this")
    2349        if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2350            this = self.wrap(this)
    2351        return f"ANY {this}"

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

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

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

    2356    def case_sql(self, expression: exp.Case) -> str:
    2357        this = self.sql(expression, "this")
    2358        statements = [f"CASE {this}" if this else "CASE"]
    2359
    2360        for e in expression.args["ifs"]:
    2361            statements.append(f"WHEN {self.sql(e, 'this')}")
    2362            statements.append(f"THEN {self.sql(e, 'true')}")
    2363
    2364        default = self.sql(expression, "default")
    2365
    2366        if default:
    2367            statements.append(f"ELSE {default}")
    2368
    2369        statements.append("END")
    2370
    2371        if self.pretty and self.text_width(statements) > self.max_text_width:
    2372            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2373
    2374        return " ".join(statements)

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

    2376    def constraint_sql(self, expression: exp.Constraint) -> str:
    2377        this = self.sql(expression, "this")
    2378        expressions = self.expressions(expression, flat=True)
    2379        return f"CONSTRAINT {this} {expressions}"

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

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

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

    2386    def extract_sql(self, expression: exp.Extract) -> str:
    2387        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2388        expression_sql = self.sql(expression, "expression")
    2389        return f"EXTRACT({this} FROM {expression_sql})"

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

    2391    def trim_sql(self, expression: exp.Trim) -> str:
    2392        trim_type = self.sql(expression, "position")
    2393
    2394        if trim_type == "LEADING":
    2395            return self.func("LTRIM", expression.this)
    2396        elif trim_type == "TRAILING":
    2397            return self.func("RTRIM", expression.this)
    2398        else:
    2399            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

    2401    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2402        args = expression.expressions
    2403        if isinstance(expression, exp.ConcatWs):
    2404            args = args[1:]  # Skip the delimiter
    2405
    2406        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2407            args = [exp.cast(e, "text") for e in args]
    2408
    2409        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2410            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2411
    2412        return args

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

    2414    def concat_sql(self, expression: exp.Concat) -> str:
    2415        expressions = self.convert_concat_args(expression)
    2416
    2417        # Some dialects don't allow a single-argument CONCAT call
    2418        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2419            return self.sql(expressions[0])
    2420
    2421        return self.func("CONCAT", *expressions)

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

    2423    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2424        return self.func(
    2425            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2426        )

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

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

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

    2432    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2433        expressions = self.expressions(expression, flat=True)
    2434        reference = self.sql(expression, "reference")
    2435        reference = f" {reference}" if reference else ""
    2436        delete = self.sql(expression, "delete")
    2437        delete = f" ON DELETE {delete}" if delete else ""
    2438        update = self.sql(expression, "update")
    2439        update = f" ON UPDATE {update}" if update else ""
    2440        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"

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

    2442    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2443        expressions = self.expressions(expression, flat=True)
    2444        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2445        options = f" {options}" if options else ""
    2446        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

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

    2463    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
    2464        if isinstance(expression, exp.JSONPathPart):
    2465            transform = self.TRANSFORMS.get(expression.__class__)
    2466            if not callable(transform):
    2467                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
    2468                return ""
    2469
    2470            return transform(self, expression)
    2471
    2472        if isinstance(expression, int):
    2473            return str(expression)
    2474
    2475        if self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
    2476            escaped = expression.replace("'", "\\'")
    2477            escaped = f"\\'{expression}\\'"
    2478        else:
    2479            escaped = expression.replace('"', '\\"')
    2480            escaped = f'"{escaped}"'
    2481
    2482        return escaped

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

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

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

    2487    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    2488        null_handling = expression.args.get("null_handling")
    2489        null_handling = f" {null_handling}" if null_handling else ""
    2490
    2491        unique_keys = expression.args.get("unique_keys")
    2492        if unique_keys is not None:
    2493            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2494        else:
    2495            unique_keys = ""
    2496
    2497        return_type = self.sql(expression, "return_type")
    2498        return_type = f" RETURNING {return_type}" if return_type else ""
    2499        encoding = self.sql(expression, "encoding")
    2500        encoding = f" ENCODING {encoding}" if encoding else ""
    2501
    2502        return self.func(
    2503            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    2504            *expression.expressions,
    2505            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2506        )

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

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

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

    2511    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2512        null_handling = expression.args.get("null_handling")
    2513        null_handling = f" {null_handling}" if null_handling else ""
    2514        return_type = self.sql(expression, "return_type")
    2515        return_type = f" RETURNING {return_type}" if return_type else ""
    2516        strict = " STRICT" if expression.args.get("strict") else ""
    2517        return self.func(
    2518            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2519        )

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

    2521    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2522        this = self.sql(expression, "this")
    2523        order = self.sql(expression, "order")
    2524        null_handling = expression.args.get("null_handling")
    2525        null_handling = f" {null_handling}" if null_handling else ""
    2526        return_type = self.sql(expression, "return_type")
    2527        return_type = f" RETURNING {return_type}" if return_type else ""
    2528        strict = " STRICT" if expression.args.get("strict") else ""
    2529        return self.func(
    2530            "JSON_ARRAYAGG",
    2531            this,
    2532            suffix=f"{order}{null_handling}{return_type}{strict})",
    2533        )

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

    2535    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2536        path = self.sql(expression, "path")
    2537        path = f" PATH {path}" if path else ""
    2538        nested_schema = self.sql(expression, "nested_schema")
    2539
    2540        if nested_schema:
    2541            return f"NESTED{path} {nested_schema}"
    2542
    2543        this = self.sql(expression, "this")
    2544        kind = self.sql(expression, "kind")
    2545        kind = f" {kind}" if kind else ""
    2546        return f"{this}{kind}{path}"

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

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

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

    2551    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    2552        this = self.sql(expression, "this")
    2553        path = self.sql(expression, "path")
    2554        path = f", {path}" if path else ""
    2555        error_handling = expression.args.get("error_handling")
    2556        error_handling = f" {error_handling}" if error_handling else ""
    2557        empty_handling = expression.args.get("empty_handling")
    2558        empty_handling = f" {empty_handling}" if empty_handling else ""
    2559        schema = self.sql(expression, "schema")
    2560        return self.func(
    2561            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    2562        )

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

    2564    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    2565        this = self.sql(expression, "this")
    2566        kind = self.sql(expression, "kind")
    2567        path = self.sql(expression, "path")
    2568        path = f" {path}" if path else ""
    2569        as_json = " AS JSON" if expression.args.get("as_json") else ""
    2570        return f"{this} {kind}{path}{as_json}"

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

    2572    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    2573        this = self.sql(expression, "this")
    2574        path = self.sql(expression, "path")
    2575        path = f", {path}" if path else ""
    2576        expressions = self.expressions(expression)
    2577        with_ = (
    2578            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2579            if expressions
    2580            else ""
    2581        )
    2582        return f"OPENJSON({this}{path}){with_}"

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

    2584    def in_sql(self, expression: exp.In) -> str:
    2585        query = expression.args.get("query")
    2586        unnest = expression.args.get("unnest")
    2587        field = expression.args.get("field")
    2588        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    2589
    2590        if query:
    2591            in_sql = self.wrap(self.sql(query))
    2592        elif unnest:
    2593            in_sql = self.in_unnest_op(unnest)
    2594        elif field:
    2595            in_sql = self.sql(field)
    2596        else:
    2597            in_sql = f"({self.expressions(expression, flat=True)})"
    2598
    2599        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    2604    def interval_sql(self, expression: exp.Interval) -> str:
    2605        unit = self.sql(expression, "unit")
    2606        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    2607            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    2608        unit = f" {unit}" if unit else ""
    2609
    2610        if self.SINGLE_STRING_INTERVAL:
    2611            this = expression.this.name if expression.this else ""
    2612            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    2613
    2614        this = self.sql(expression, "this")
    2615        if this:
    2616            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    2617            this = f" {this}" if unwrapped else f" ({this})"
    2618
    2619        return f"INTERVAL{this}{unit}"

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

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

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

    2624    def reference_sql(self, expression: exp.Reference) -> str:
    2625        this = self.sql(expression, "this")
    2626        expressions = self.expressions(expression, flat=True)
    2627        expressions = f"({expressions})" if expressions else ""
    2628        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2629        options = f" {options}" if options else ""
    2630        return f"REFERENCES {this}{expressions}{options}"

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

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

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

    2635    def paren_sql(self, expression: exp.Paren) -> str:
    2636        if isinstance(expression.unnest(), exp.Select):
    2637            sql = self.wrap(expression)
    2638        else:
    2639            sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
    2640            sql = f"({sql}{self.seg(')', sep='')}"
    2641
    2642        return self.prepend_ctes(expression, sql)

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

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

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

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

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

    2653    def alias_sql(self, expression: exp.Alias) -> str:
    2654        alias = self.sql(expression, "alias")
    2655        alias = f" AS {alias}" if alias else ""
    2656        return f"{self.sql(expression, 'this')}{alias}"

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

    2658    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    2659        alias = expression.args["alias"]
    2660        identifier_alias = isinstance(alias, exp.Identifier)
    2661
    2662        if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2663            alias.replace(exp.Literal.string(alias.output_name))
    2664        elif not identifier_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2665            alias.replace(exp.to_identifier(alias.output_name))
    2666
    2667        return self.alias_sql(expression)

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

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

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

    2672    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    2673        this = self.sql(expression, "this")
    2674        index = self.sql(expression, "expression")
    2675        return f"{this} AT {index}"

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

    2677    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    2678        this = self.sql(expression, "this")
    2679        zone = self.sql(expression, "zone")
    2680        return f"{this} AT TIME ZONE {zone}"

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

    2682    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    2683        this = self.sql(expression, "this")
    2684        zone = self.sql(expression, "zone")
    2685        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"

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

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

def and_sql(self, expression: sqlglot.expressions.And) -> str: View Source

    2690    def and_sql(self, expression: exp.And) -> str:
    2691        return self.connector_sql(expression, "AND")

def xor_sql(self, expression: sqlglot.expressions.Xor) -> str: View Source

    2693    def xor_sql(self, expression: exp.Xor) -> str:
    2694        return self.connector_sql(expression, "XOR")

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

    2696    def connector_sql(self, expression: exp.Connector, op: str) -> str:
    2697        if not self.pretty:
    2698            return self.binary(expression, op)
    2699
    2700        sqls = tuple(
    2701            self.maybe_comment(self.sql(e), e, e.parent.comments or []) if i != 1 else self.sql(e)
    2702            for i, e in enumerate(expression.flatten(unnest=False))
    2703        )
    2704
    2705        sep = "\n" if self.text_width(sqls) > self.max_text_width else " "
    2706        return f"{sep}{op} ".join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

    2726    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    2727        format_sql = self.sql(expression, "format")
    2728        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    2729        to_sql = self.sql(expression, "to")
    2730        to_sql = f" {to_sql}" if to_sql else ""
    2731        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{format_sql})"

def currentdate_sql(self, expression: sqlglot.expressions.CurrentDate) -> str: View Source

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

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

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

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

    2740    def collate_sql(self, expression: exp.Collate) -> str:
    2741        if self.COLLATE_IS_FUNC:
    2742            return self.function_fallback_sql(expression)
    2743        return self.binary(expression, "COLLATE")

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

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

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

    2748    def comment_sql(self, expression: exp.Comment) -> str:
    2749        this = self.sql(expression, "this")
    2750        kind = expression.args["kind"]
    2751        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    2752        expression_sql = self.sql(expression, "expression")
    2753        return f"COMMENT{exists_sql}ON {kind} {this} IS {expression_sql}"

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

    2755    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    2756        this = self.sql(expression, "this")
    2757        delete = " DELETE" if expression.args.get("delete") else ""
    2758        recompress = self.sql(expression, "recompress")
    2759        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    2760        to_disk = self.sql(expression, "to_disk")
    2761        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    2762        to_volume = self.sql(expression, "to_volume")
    2763        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    2764        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    2766    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    2767        where = self.sql(expression, "where")
    2768        group = self.sql(expression, "group")
    2769        aggregates = self.expressions(expression, key="aggregates")
    2770        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    2771
    2772        if not (where or group or aggregates) and len(expression.expressions) == 1:
    2773            return f"TTL {self.expressions(expression, flat=True)}"
    2774
    2775        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    2780    def commit_sql(self, expression: exp.Commit) -> str:
    2781        chain = expression.args.get("chain")
    2782        if chain is not None:
    2783            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    2784
    2785        return f"COMMIT{chain or ''}"

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

    2787    def rollback_sql(self, expression: exp.Rollback) -> str:
    2788        savepoint = expression.args.get("savepoint")
    2789        savepoint = f" TO {savepoint}" if savepoint else ""
    2790        return f"ROLLBACK{savepoint}"

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

    2792    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    2793        this = self.sql(expression, "this")
    2794
    2795        dtype = self.sql(expression, "dtype")
    2796        if dtype:
    2797            collate = self.sql(expression, "collate")
    2798            collate = f" COLLATE {collate}" if collate else ""
    2799            using = self.sql(expression, "using")
    2800            using = f" USING {using}" if using else ""
    2801            return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}"
    2802
    2803        default = self.sql(expression, "default")
    2804        if default:
    2805            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    2806
    2807        comment = self.sql(expression, "comment")
    2808        if comment:
    2809            return f"ALTER COLUMN {this} COMMENT {comment}"
    2810
    2811        if not expression.args.get("drop"):
    2812            self.unsupported("Unsupported ALTER COLUMN syntax")
    2813
    2814        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    2816    def renametable_sql(self, expression: exp.RenameTable) -> str:
    2817        if not self.RENAME_TABLE_WITH_DB:
    2818            # Remove db from tables
    2819            expression = expression.transform(
    2820                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    2821            )
    2822        this = self.sql(expression, "this")
    2823        return f"RENAME TO {this}"

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

    2825    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    2826        exists = " IF EXISTS" if expression.args.get("exists") else ""
    2827        old_column = self.sql(expression, "this")
    2828        new_column = self.sql(expression, "to")
    2829        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"

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

    2831    def altertable_sql(self, expression: exp.AlterTable) -> str:
    2832        actions = expression.args["actions"]
    2833
    2834        if isinstance(actions[0], exp.ColumnDef):
    2835            actions = self.add_column_sql(expression)
    2836        elif isinstance(actions[0], exp.Schema):
    2837            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    2838        elif isinstance(actions[0], exp.Delete):
    2839            actions = self.expressions(expression, key="actions", flat=True)
    2840        else:
    2841            actions = self.expressions(expression, key="actions", flat=True)
    2842
    2843        exists = " IF EXISTS" if expression.args.get("exists") else ""
    2844        only = " ONLY" if expression.args.get("only") else ""
    2845        options = self.expressions(expression, key="options")
    2846        options = f", {options}" if options else ""
    2847        return f"ALTER TABLE{exists}{only} {self.sql(expression, 'this')} {actions}{options}"

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

    2849    def add_column_sql(self, expression: exp.AlterTable) -> str:
    2850        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    2851            return self.expressions(
    2852                expression,
    2853                key="actions",
    2854                prefix="ADD COLUMN ",
    2855            )
    2856        return f"ADD {self.expressions(expression, key='actions', flat=True)}"

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

    2858    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    2859        expressions = self.expressions(expression)
    2860        exists = " IF EXISTS " if expression.args.get("exists") else " "
    2861        return f"DROP{exists}{expressions}"

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

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

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

    2866    def distinct_sql(self, expression: exp.Distinct) -> str:
    2867        this = self.expressions(expression, flat=True)
    2868
    2869        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    2870            case = exp.case()
    2871            for arg in expression.expressions:
    2872                case = case.when(arg.is_(exp.null()), exp.null())
    2873            this = self.sql(case.else_(f"({this})"))
    2874
    2875        this = f" {this}" if this else ""
    2876
    2877        on = self.sql(expression, "on")
    2878        on = f" ON {on}" if on else ""
    2879        return f"DISTINCT{this}{on}"

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

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

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

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

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

    2887    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    2888        this_sql = self.sql(expression, "this")
    2889        expression_sql = self.sql(expression, "expression")
    2890        kind = "MAX" if expression.args.get("max") else "MIN"
    2891        return f"{this_sql} HAVING {kind} {expression_sql}"

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

    2917    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    2918        return self.sql(
    2919            exp.Cast(
    2920                this=exp.Div(this=expression.this, expression=expression.expression),
    2921                to=exp.DataType(this=exp.DataType.Type.INT),
    2922            )
    2923        )

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

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

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

    2930    def div_sql(self, expression: exp.Div) -> str:
    2931        l, r = expression.left, expression.right
    2932
    2933        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    2934            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    2935
    2936        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    2937            if not l.is_type(*exp.DataType.FLOAT_TYPES) and not r.is_type(
    2938                *exp.DataType.FLOAT_TYPES
    2939            ):
    2940                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    2941
    2942        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    2943            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    2944                return self.sql(
    2945                    exp.cast(
    2946                        l / r,
    2947                        to=exp.DataType.Type.BIGINT,
    2948                    )
    2949                )
    2950
    2951        return self.binary(expression, "/")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2986    def is_sql(self, expression: exp.Is) -> str:
    2987        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    2988            return self.sql(
    2989                expression.this if expression.expression.this else exp.not_(expression.this)
    2990            )
    2991        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

def or_sql(self, expression: sqlglot.expressions.Or) -> str: View Source

    3023    def or_sql(self, expression: exp.Or) -> str:
    3024        return self.connector_sql(expression, "OR")

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

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

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

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

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

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

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

    3035    def log_sql(self, expression: exp.Log) -> str:
    3036        this = expression.this
    3037        expr = expression.expression
    3038
    3039        if not self.dialect.LOG_BASE_FIRST:
    3040            this, expr = expr, this
    3041
    3042        return self.func("LOG", this, expr)

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

    3044    def use_sql(self, expression: exp.Use) -> str:
    3045        kind = self.sql(expression, "kind")
    3046        kind = f" {kind}" if kind else ""
    3047        this = self.sql(expression, "this")
    3048        this = f" {this}" if this else ""
    3049        return f"USE{kind}{this}"

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

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

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

    3055    def function_fallback_sql(self, expression: exp.Func) -> str:
    3056        args = []
    3057
    3058        for key in expression.arg_types:
    3059            arg_value = expression.args.get(key)
    3060
    3061            if isinstance(arg_value, list):
    3062                for value in arg_value:
    3063                    args.append(value)
    3064            elif arg_value is not None:
    3065                args.append(arg_value)
    3066
    3067        if self.normalize_functions:
    3068            name = expression.sql_name()
    3069        else:
    3070            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3071
    3072        return self.func(name, *args)

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

    3074    def func(
    3075        self,
    3076        name: str,
    3077        *args: t.Optional[exp.Expression | str],
    3078        prefix: str = "(",
    3079        suffix: str = ")",
    3080    ) -> str:
    3081        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

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

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

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

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

    3092    def format_time(self, expression: exp.Expression) -> t.Optional[str]:
    3093        return format_time(
    3094            self.sql(expression, "format"),
    3095            self.dialect.INVERSE_TIME_MAPPING,
    3096            self.dialect.INVERSE_TIME_TRIE,
    3097        )

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

    3099    def expressions(
    3100        self,
    3101        expression: t.Optional[exp.Expression] = None,
    3102        key: t.Optional[str] = None,
    3103        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    3104        flat: bool = False,
    3105        indent: bool = True,
    3106        skip_first: bool = False,
    3107        sep: str = ", ",
    3108        prefix: str = "",
    3109    ) -> str:
    3110        expressions = expression.args.get(key or "expressions") if expression else sqls
    3111
    3112        if not expressions:
    3113            return ""
    3114
    3115        if flat:
    3116            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    3117
    3118        num_sqls = len(expressions)
    3119
    3120        # These are calculated once in case we have the leading_comma / pretty option set, correspondingly
    3121        pad = " " * self.pad
    3122        stripped_sep = sep.strip()
    3123
    3124        result_sqls = []
    3125        for i, e in enumerate(expressions):
    3126            sql = self.sql(e, comment=False)
    3127            if not sql:
    3128                continue
    3129
    3130            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    3131
    3132            if self.pretty:
    3133                if self.leading_comma:
    3134                    result_sqls.append(f"{sep if i > 0 else pad}{prefix}{sql}{comments}")
    3135                else:
    3136                    result_sqls.append(
    3137                        f"{prefix}{sql}{stripped_sep if i + 1 < num_sqls else ''}{comments}"
    3138                    )
    3139            else:
    3140                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    3141
    3142        result_sql = "\n".join(result_sqls) if self.pretty else "".join(result_sqls)
    3143        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

    3145    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3146        flat = flat or isinstance(expression.parent, exp.Properties)
    3147        expressions_sql = self.expressions(expression, flat=flat)
    3148        if flat:
    3149            return f"{op} {expressions_sql}"
    3150        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    3152    def naked_property(self, expression: exp.Property) -> str:
    3153        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3154        if not property_name:
    3155            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3156        return f"{property_name} {self.sql(expression, 'this')}"

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

    3158    def set_operation(self, expression: exp.Union, op: str) -> str:
    3159        this = self.maybe_comment(self.sql(expression, "this"), comments=expression.comments)
    3160        op = self.seg(op)
    3161        return self.query_modifiers(
    3162            expression, f"{this}{op}{self.sep()}{self.sql(expression, 'expression')}"
    3163        )

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

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

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

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

    3171    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3172        this = self.sql(expression, "this")
    3173        expressions = self.no_identify(self.expressions, expression)
    3174        expressions = (
    3175            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3176        )
    3177        return f"{this}{expressions}"

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

    3179    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3180        this = self.sql(expression, "this")
    3181        expressions = self.expressions(expression, flat=True)
    3182        return f"{this}({expressions})"

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

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

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

    3187    def when_sql(self, expression: exp.When) -> str:
    3188        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3189        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3190        condition = self.sql(expression, "condition")
    3191        condition = f" AND {condition}" if condition else ""
    3192
    3193        then_expression = expression.args.get("then")
    3194        if isinstance(then_expression, exp.Insert):
    3195            then = f"INSERT {self.sql(then_expression, 'this')}"
    3196            if "expression" in then_expression.args:
    3197                then += f" VALUES {self.sql(then_expression, 'expression')}"
    3198        elif isinstance(then_expression, exp.Update):
    3199            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3200                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3201            else:
    3202                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    3203        else:
    3204            then = self.sql(then_expression)
    3205        return f"WHEN {matched}{source}{condition} THEN {then}"

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

    3207    def merge_sql(self, expression: exp.Merge) -> str:
    3208        table = expression.this
    3209        table_alias = ""
    3210
    3211        hints = table.args.get("hints")
    3212        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3213            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3214            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3215
    3216        this = self.sql(table)
    3217        using = f"USING {self.sql(expression, 'using')}"
    3218        on = f"ON {self.sql(expression, 'on')}"
    3219        expressions = self.expressions(expression, sep=" ")
    3220
    3221        return self.prepend_ctes(
    3222            expression, f"MERGE INTO {this}{table_alias} {using} {on} {expressions}"
    3223        )

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

    3225    def tochar_sql(self, expression: exp.ToChar) -> str:
    3226        if expression.args.get("format"):
    3227            self.unsupported("Format argument unsupported for TO_CHAR/TO_VARCHAR function")
    3228
    3229        return self.sql(exp.cast(expression.this, "text"))

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

    3231    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3232        this = self.sql(expression, "this")
    3233        kind = self.sql(expression, "kind")
    3234        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3235        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3236        return f"{this}({kind}{args})"

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

    3238    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3239        this = self.sql(expression, "this")
    3240        max = self.sql(expression, "max")
    3241        min = self.sql(expression, "min")
    3242        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

    3250    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3251        expressions = self.expressions(expression, key="expressions", flat=True)
    3252        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3253        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3254        buckets = self.sql(expression, "buckets")
    3255        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    3257    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3258        this = self.sql(expression, "this")
    3259        having = self.sql(expression, "having")
    3260
    3261        if having:
    3262            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3263
    3264        return self.func("ANY_VALUE", this)

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

    3266    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3267        transform = self.func("TRANSFORM", *expression.expressions)
    3268        row_format_before = self.sql(expression, "row_format_before")
    3269        row_format_before = f" {row_format_before}" if row_format_before else ""
    3270        record_writer = self.sql(expression, "record_writer")
    3271        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3272        using = f" USING {self.sql(expression, 'command_script')}"
    3273        schema = self.sql(expression, "schema")
    3274        schema = f" AS {schema}" if schema else ""
    3275        row_format_after = self.sql(expression, "row_format_after")
    3276        row_format_after = f" {row_format_after}" if row_format_after else ""
    3277        record_reader = self.sql(expression, "record_reader")
    3278        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3279        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

    3281    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3282        key_block_size = self.sql(expression, "key_block_size")
    3283        if key_block_size:
    3284            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3285
    3286        using = self.sql(expression, "using")
    3287        if using:
    3288            return f"USING {using}"
    3289
    3290        parser = self.sql(expression, "parser")
    3291        if parser:
    3292            return f"WITH PARSER {parser}"
    3293
    3294        comment = self.sql(expression, "comment")
    3295        if comment:
    3296            return f"COMMENT {comment}"
    3297
    3298        visible = expression.args.get("visible")
    3299        if visible is not None:
    3300            return "VISIBLE" if visible else "INVISIBLE"
    3301
    3302        engine_attr = self.sql(expression, "engine_attr")
    3303        if engine_attr:
    3304            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3305
    3306        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3307        if secondary_engine_attr:
    3308            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3309
    3310        self.unsupported("Unsupported index constraint option.")
    3311        return ""

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

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

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

    3317    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3318        kind = self.sql(expression, "kind")
    3319        kind = f"{kind} INDEX" if kind else "INDEX"
    3320        this = self.sql(expression, "this")
    3321        this = f" {this}" if this else ""
    3322        index_type = self.sql(expression, "index_type")
    3323        index_type = f" USING {index_type}" if index_type else ""
    3324        schema = self.sql(expression, "schema")
    3325        schema = f" {schema}" if schema else ""
    3326        options = self.expressions(expression, key="options", sep=" ")
    3327        options = f" {options}" if options else ""
    3328        return f"{kind}{this}{index_type}{schema}{options}"

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

    3330    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3331        if self.NVL2_SUPPORTED:
    3332            return self.function_fallback_sql(expression)
    3333
    3334        case = exp.Case().when(
    3335            expression.this.is_(exp.null()).not_(copy=False),
    3336            expression.args["true"],
    3337            copy=False,
    3338        )
    3339        else_cond = expression.args.get("false")
    3340        if else_cond:
    3341            case.else_(else_cond, copy=False)
    3342
    3343        return self.sql(case)

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

    3345    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3346        this = self.sql(expression, "this")
    3347        expr = self.sql(expression, "expression")
    3348        iterator = self.sql(expression, "iterator")
    3349        condition = self.sql(expression, "condition")
    3350        condition = f" IF {condition}" if condition else ""
    3351        return f"{this} FOR {expr} IN {iterator}{condition}"

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

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

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

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

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

    3359    def predict_sql(self, expression: exp.Predict) -> str:
    3360        model = self.sql(expression, "this")
    3361        model = f"MODEL {model}"
    3362        table = self.sql(expression, "expression")
    3363        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    3364        parameters = self.sql(expression, "params_struct")
    3365        return self.func("PREDICT", model, table, parameters or None)

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

    3367    def forin_sql(self, expression: exp.ForIn) -> str:
    3368        this = self.sql(expression, "this")
    3369        expression_sql = self.sql(expression, "expression")
    3370        return f"FOR {this} DO {expression_sql}"

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

    3372    def refresh_sql(self, expression: exp.Refresh) -> str:
    3373        this = self.sql(expression, "this")
    3374        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    3375        return f"REFRESH {table}{this}"

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

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

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

    3380    def toarray_sql(self, expression: exp.ToArray) -> str:
    3381        arg = expression.this
    3382        if not arg.type:
    3383            from sqlglot.optimizer.annotate_types import annotate_types
    3384
    3385            arg = annotate_types(arg)
    3386
    3387        if arg.is_type(exp.DataType.Type.ARRAY):
    3388            return self.sql(arg)
    3389
    3390        cond_for_null = arg.is_(exp.null())
    3391        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

    3393    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    3394        this = expression.this
    3395        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    3396            return self.sql(this)
    3397
    3398        return self.sql(exp.cast(this, "time"))

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

    3400    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    3401        this = expression.this
    3402        time_format = self.format_time(expression)
    3403
    3404        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    3405            return self.sql(
    3406                exp.cast(exp.StrToTime(this=this, format=expression.args["format"]), "date")
    3407            )
    3408
    3409        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    3410            return self.sql(this)
    3411
    3412        return self.sql(exp.cast(this, "date"))

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

    3414    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    3415        return self.sql(
    3416            exp.func(
    3417                "DATEDIFF",
    3418                expression.this,
    3419                exp.cast(exp.Literal.string("1970-01-01"), "date"),
    3420                "day",
    3421            )
    3422        )

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

    3424    def lastday_sql(self, expression: exp.LastDay) -> str:
    3425        if self.LAST_DAY_SUPPORTS_DATE_PART:
    3426            return self.function_fallback_sql(expression)
    3427
    3428        unit = expression.text("unit")
    3429        if unit and unit != "MONTH":
    3430            self.unsupported("Date parts are not supported in LAST_DAY.")
    3431
    3432        return self.func("LAST_DAY", expression.this)

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

    3434    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    3435        if self.CAN_IMPLEMENT_ARRAY_ANY:
    3436            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    3437            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    3438            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    3439            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    3440
    3441        from sqlglot.dialects import Dialect
    3442
    3443        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    3444        if self.dialect.__class__ != Dialect:
    3445            self.unsupported("ARRAY_ANY is unsupported")
    3446
    3447        return self.function_fallback_sql(expression)

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

    3473    def generateseries_sql(self, expression: exp.GenerateSeries) -> str:
    3474        expression.set("is_end_exclusive", None)
    3475        return self.function_fallback_sql(expression)

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

    3477    def struct_sql(self, expression: exp.Struct) -> str:
    3478        expression.set(
    3479            "expressions",
    3480            [
    3481                exp.alias_(e.expression, e.this) if isinstance(e, exp.PropertyEQ) else e
    3482                for e in expression.expressions
    3483            ],
    3484        )
    3485
    3486        return self.function_fallback_sql(expression)

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

    3488    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    3489        low = self.sql(expression, "this")
    3490        high = self.sql(expression, "expression")
    3491
    3492        return f"{low} TO {high}"

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

    3494    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    3495        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    3496        tables = f" {self.expressions(expression)}"
    3497
    3498        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3499
    3500        on_cluster = self.sql(expression, "cluster")
    3501        on_cluster = f" {on_cluster}" if on_cluster else ""
    3502
    3503        identity = self.sql(expression, "identity")
    3504        identity = f" {identity} IDENTITY" if identity else ""
    3505
    3506        option = self.sql(expression, "option")
    3507        option = f" {option}" if option else ""
    3508
    3509        partition = self.sql(expression, "partition")
    3510        partition = f" {partition}" if partition else ""
    3511
    3512        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"

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

    3516    def convert_sql(self, expression: exp.Convert) -> str:
    3517        to = expression.this
    3518        value = expression.expression
    3519        style = expression.args.get("style")
    3520        safe = expression.args.get("safe")
    3521        strict = expression.args.get("strict")
    3522
    3523        if not to or not value:
    3524            return ""
    3525
    3526        # Retrieve length of datatype and override to default if not specified
    3527        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3528            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    3529
    3530        transformed: t.Optional[exp.Expression] = None
    3531        cast = exp.Cast if strict else exp.TryCast
    3532
    3533        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
    3534        if isinstance(style, exp.Literal) and style.is_int:
    3535            from sqlglot.dialects.tsql import TSQL
    3536
    3537            style_value = style.name
    3538            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
    3539            if not converted_style:
    3540                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
    3541
    3542            fmt = exp.Literal.string(converted_style)
    3543
    3544            if to.this == exp.DataType.Type.DATE:
    3545                transformed = exp.StrToDate(this=value, format=fmt)
    3546            elif to.this == exp.DataType.Type.DATETIME:
    3547                transformed = exp.StrToTime(this=value, format=fmt)
    3548            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3549                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
    3550            elif to.this == exp.DataType.Type.TEXT:
    3551                transformed = exp.TimeToStr(this=value, format=fmt)
    3552
    3553        if not transformed:
    3554            transformed = cast(this=value, to=to, safe=safe)
    3555
    3556        return self.sql(transformed)