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

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

TRANSFORMS: Dict[Type[sqlglot.expressions.Expression], Callable[..., str]] = {<class 'sqlglot.expressions.JSONPathFilter'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathKey'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRecursive'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRoot'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathScript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSelector'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSlice'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSubscript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathUnion'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathWildcard'>: <function <lambda>>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateAdd'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExcludeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.GlobalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.JSONExtract'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.JSONExtractScalar'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SharingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Timestamp'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithOperator'>: <function Generator.<lambda>>}
NULL_ORDERING_SUPPORTED: Optional[bool] = True
IGNORE_NULLS_IN_FUNC = False
LOCKING_READS_SUPPORTED = False
EXPLICIT_UNION = False
WRAP_DERIVED_VALUES = True
CREATE_FUNCTION_RETURN_AS = True
MATCHED_BY_SOURCE = True
SINGLE_STRING_INTERVAL = False
INTERVAL_ALLOWS_PLURAL_FORM = True
LIMIT_FETCH = 'ALL'
LIMIT_ONLY_LITERALS = False
RENAME_TABLE_WITH_DB = True
GROUPINGS_SEP = ','
INDEX_ON = 'ON'
JOIN_HINTS = True
TABLE_HINTS = True
QUERY_HINTS = True
QUERY_HINT_SEP = ', '
IS_BOOL_ALLOWED = True
DUPLICATE_KEY_UPDATE_WITH_SET = True
LIMIT_IS_TOP = False
RETURNING_END = True
COLUMN_JOIN_MARKS_SUPPORTED = False
EXTRACT_ALLOWS_QUOTES = True
TZ_TO_WITH_TIME_ZONE = False
NVL2_SUPPORTED = True
SELECT_KINDS: Tuple[str, ...] = ('STRUCT', 'VALUE')
VALUES_AS_TABLE = True
ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True
UNNEST_WITH_ORDINALITY = True
AGGREGATE_FILTER_SUPPORTED = True
SEMI_ANTI_JOIN_WITH_SIDE = True
COMPUTED_COLUMN_WITH_TYPE = True
SUPPORTS_TABLE_COPY = True
TABLESAMPLE_REQUIRES_PARENS = True
TABLESAMPLE_SIZE_IS_ROWS = True
TABLESAMPLE_KEYWORDS = 'TABLESAMPLE'
TABLESAMPLE_WITH_METHOD = True
TABLESAMPLE_SEED_KEYWORD = 'SEED'
COLLATE_IS_FUNC = False
DATA_TYPE_SPECIFIERS_ALLOWED = False
ENSURE_BOOLS = False
CTE_RECURSIVE_KEYWORD_REQUIRED = True
SUPPORTS_SINGLE_ARG_CONCAT = True
LAST_DAY_SUPPORTS_DATE_PART = True
SUPPORTS_TABLE_ALIAS_COLUMNS = True
UNPIVOT_ALIASES_ARE_IDENTIFIERS = True
JSON_KEY_VALUE_PAIR_SEP = ':'
INSERT_OVERWRITE = ' OVERWRITE TABLE'
SUPPORTS_SELECT_INTO = False
SUPPORTS_UNLOGGED_TABLES = False
SUPPORTS_CREATE_TABLE_LIKE = True
LIKE_PROPERTY_INSIDE_SCHEMA = False
MULTI_ARG_DISTINCT = True
JSON_TYPE_REQUIRED_FOR_EXTRACTION = False
JSON_PATH_BRACKETED_KEY_SUPPORTED = True
JSON_PATH_SINGLE_QUOTE_ESCAPE = False
SUPPORTED_JSON_PATH_PARTS = {<class 'sqlglot.expressions.JSONPathFilter'>, <class 'sqlglot.expressions.JSONPathUnion'>, <class 'sqlglot.expressions.JSONPathSubscript'>, <class 'sqlglot.expressions.JSONPathSelector'>, <class 'sqlglot.expressions.JSONPathSlice'>, <class 'sqlglot.expressions.JSONPathWildcard'>, <class 'sqlglot.expressions.JSONPathScript'>, <class 'sqlglot.expressions.JSONPathRoot'>, <class 'sqlglot.expressions.JSONPathRecursive'>, <class 'sqlglot.expressions.JSONPathKey'>}
CAN_IMPLEMENT_ARRAY_ANY = False
SUPPORTS_TO_NUMBER = True
TYPE_MAPPING = {<Type.NCHAR: 'NCHAR'>: 'CHAR', <Type.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <Type.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <Type.LONGTEXT: 'LONGTEXT'>: 'TEXT', <Type.TINYTEXT: 'TINYTEXT'>: 'TEXT', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <Type.LONGBLOB: 'LONGBLOB'>: 'BLOB', <Type.TINYBLOB: 'TINYBLOB'>: 'BLOB', <Type.INET: 'INET'>: 'INET'}
STAR_MAPPING = {'except': 'EXCEPT', 'replace': 'REPLACE'}
TIME_PART_SINGULARS = {'MICROSECONDS': 'MICROSECOND', 'SECONDS': 'SECOND', 'MINUTES': 'MINUTE', 'HOURS': 'HOUR', 'DAYS': 'DAY', 'WEEKS': 'WEEK', 'MONTHS': 'MONTH', 'QUARTERS': 'QUARTER', 'YEARS': 'YEAR'}
AFTER_HAVING_MODIFIER_TRANSFORMS = {'cluster': <function Generator.<lambda>>, 'distribute': <function Generator.<lambda>>, 'qualify': <function Generator.<lambda>>, 'sort': <function Generator.<lambda>>, 'windows': <function Generator.<lambda>>}
TOKEN_MAPPING: Dict[sqlglot.tokens.TokenType, str] = {}
STRUCT_DELIMITER = ('<', '>')
PARAMETER_TOKEN = '@'
NAMED_PLACEHOLDER_TOKEN = ':'
PROPERTIES_LOCATION = {<class 'sqlglot.expressions.AlgorithmProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.AutoIncrementProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BackupProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BlockCompressionProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CharacterSetProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ChecksumProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CollateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Cluster'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ClusteredByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DataBlocksizeProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.DefinerProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DictRange'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistStyleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EngineProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExternalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.FallbackProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.FileFormatProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.FreespaceProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.GlobalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.HeapProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.InheritsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.InputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IsolatedLoadingProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.JournalProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.LanguageProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LikeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LocationProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockingProperty'>: <Location.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.LogProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.MaterializedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeBlockRatioProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.OnProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OnCommitProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.Order'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OutputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PartitionedByProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.PartitionedOfProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ReturnsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatDelimitedProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatSerdeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SampleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SchemaCommentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SerdeProperties'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Set'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SettingsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SetProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SetConfigProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SharingProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.SequenceProperties'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.SortKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StabilityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TemporaryProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ToTableProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TransientProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.TransformModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.MergeTreeTTL'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.UnloggedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.WithSystemVersioningProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>}
RESERVED_KEYWORDS: Set[str] = set()
WITH_SEPARATED_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Create'>, <class 'sqlglot.expressions.Delete'>, <class 'sqlglot.expressions.Drop'>, <class 'sqlglot.expressions.From'>, <class 'sqlglot.expressions.Insert'>, <class 'sqlglot.expressions.Join'>, <class 'sqlglot.expressions.Select'>, <class 'sqlglot.expressions.Union'>, <class 'sqlglot.expressions.Update'>, <class 'sqlglot.expressions.Where'>, <class 'sqlglot.expressions.With'>)
EXCLUDE_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Binary'>, <class 'sqlglot.expressions.Union'>)
UNWRAPPED_INTERVAL_VALUES: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Column'>, <class 'sqlglot.expressions.Literal'>, <class 'sqlglot.expressions.Neg'>, <class 'sqlglot.expressions.Paren'>)
PARAMETERIZABLE_TEXT_TYPES = {<Type.NVARCHAR: 'NVARCHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.CHAR: 'CHAR'>, <Type.NCHAR: 'NCHAR'>}
EXPRESSIONS_WITHOUT_NESTED_CTES: Set[Type[sqlglot.expressions.Expression]] = set()
SENTINEL_LINE_BREAK = '__SQLGLOT__LB__'
pretty
identify
normalize
pad
unsupported_level
max_unsupported
leading_comma
max_text_width
comments
dialect
normalize_functions
unsupported_messages: List[str]
def generate( self, expression: sqlglot.expressions.Expression, copy: bool = True) -> str: View Source

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

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

Apply generic preprocessing transformations to a given expression.

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

    616    def unsupported(self, message: str) -> None:
    617        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    618            raise UnsupportedError(message)
    619        self.unsupported_messages.append(message)

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

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

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

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

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

    627    def pad_comment(self, comment: str) -> str:
    628        comment = " " + comment if comment[0].strip() else comment
    629        comment = comment + " " if comment[-1].strip() else comment
    630        return comment

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

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

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

    663    def wrap(self, expression: exp.Expression | str) -> str:
    664        this_sql = self.indent(
    665            (
    666                self.sql(expression)
    667                if isinstance(expression, exp.UNWRAPPED_QUERIES)
    668                else self.sql(expression, "this")
    669            ),
    670            level=1,
    671            pad=0,
    672        )
    673        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"

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

    675    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    676        original = self.identify
    677        self.identify = False
    678        result = func(*args, **kwargs)
    679        self.identify = original
    680        return result

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

    682    def normalize_func(self, name: str) -> str:
    683        if self.normalize_functions == "upper" or self.normalize_functions is True:
    684            return name.upper()
    685        if self.normalize_functions == "lower":
    686            return name.lower()
    687        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

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

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

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

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

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

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

    755    def cache_sql(self, expression: exp.Cache) -> str:
    756        lazy = " LAZY" if expression.args.get("lazy") else ""
    757        table = self.sql(expression, "this")
    758        options = expression.args.get("options")
    759        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
    760        sql = self.sql(expression, "expression")
    761        sql = f" AS{self.sep()}{sql}" if sql else ""
    762        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
    763        return self.prepend_ctes(expression, sql)

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

    765    def characterset_sql(self, expression: exp.CharacterSet) -> str:
    766        if isinstance(expression.parent, exp.Cast):
    767            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
    768        default = "DEFAULT " if expression.args.get("default") else ""
    769        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"

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

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

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

    791    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    792        this = self.sql(expression, "this")
    793        this = f" {this}" if this else ""
    794        position = self.sql(expression, "position")
    795        return f"{position}{this}"

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

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

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

    812    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    813        this = self.sql(expression, "this")
    814        kind_sql = self.sql(expression, "kind").strip()
    815        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

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

    817    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
    818        this = self.sql(expression, "this")
    819        if expression.args.get("not_null"):
    820            persisted = " PERSISTED NOT NULL"
    821        elif expression.args.get("persisted"):
    822            persisted = " PERSISTED"
    823        else:
    824            persisted = ""
    825        return f"AS {this}{persisted}"

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

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

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

    830    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
    831        if isinstance(expression.this, list):
    832            this = self.wrap(self.expressions(expression, key="this", flat=True))
    833        else:
    834            this = self.sql(expression, "this")
    835
    836        return f"COMPRESS {this}"

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

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

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

    871    def generatedasrowcolumnconstraint_sql(
    872        self, expression: exp.GeneratedAsRowColumnConstraint
    873    ) -> str:
    874        start = "START" if expression.args.get("start") else "END"
    875        hidden = " HIDDEN" if expression.args.get("hidden") else ""
    876        return f"GENERATED ALWAYS AS ROW {start}{hidden}"

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

    878    def periodforsystemtimeconstraint_sql(
    879        self, expression: exp.PeriodForSystemTimeConstraint
    880    ) -> str:
    881        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

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

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

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

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

    889    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    890        desc = expression.args.get("desc")
    891        if desc is not None:
    892            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    893        return "PRIMARY KEY"

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

    895    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    896        this = self.sql(expression, "this")
    897        this = f" {this}" if this else ""
    898        index_type = expression.args.get("index_type")
    899        index_type = f" USING {index_type}" if index_type else ""
    900        on_conflict = self.sql(expression, "on_conflict")
    901        on_conflict = f" {on_conflict}" if on_conflict else ""
    902        return f"UNIQUE{this}{index_type}{on_conflict}"

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

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

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

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

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

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

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

    1019    def clone_sql(self, expression: exp.Clone) -> str:
    1020        this = self.sql(expression, "this")
    1021        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    1022        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
    1023        return f"{shallow}{keyword} {this}"

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

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

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

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

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

    1033    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    1034        with_ = self.sql(expression, "with")
    1035        if with_:
    1036            sql = f"{with_}{self.sep()}{sql}"
    1037        return sql

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

    1039    def with_sql(self, expression: exp.With) -> str:
    1040        sql = self.expressions(expression, flat=True)
    1041        recursive = (
    1042            "RECURSIVE "
    1043            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
    1044            else ""
    1045        )
    1046
    1047        return f"WITH {recursive}{sql}"

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

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

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

    1053    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    1054        alias = self.sql(expression, "this")
    1055        columns = self.expressions(expression, key="columns", flat=True)
    1056        columns = f"({columns})" if columns else ""
    1057
    1058        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
    1059            columns = ""
    1060            self.unsupported("Named columns are not supported in table alias.")
    1061
    1062        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
    1063            alias = "_t"
    1064
    1065        return f"{alias}{columns}"

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

    1067    def bitstring_sql(self, expression: exp.BitString) -> str:
    1068        this = self.sql(expression, "this")
    1069        if self.dialect.BIT_START:
    1070            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    1071        return f"{int(this, 2)}"

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

    1073    def hexstring_sql(self, expression: exp.HexString) -> str:
    1074        this = self.sql(expression, "this")
    1075        if self.dialect.HEX_START:
    1076            return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
    1077        return f"{int(this, 16)}"

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

    1079    def bytestring_sql(self, expression: exp.ByteString) -> str:
    1080        this = self.sql(expression, "this")
    1081        if self.dialect.BYTE_START:
    1082            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    1083        return this

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

    1085    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
    1086        this = self.sql(expression, "this")
    1087        escape = expression.args.get("escape")
    1088
    1089        if self.dialect.UNICODE_START:
    1090            escape = f" UESCAPE {self.sql(escape)}" if escape else ""
    1091            return f"{self.dialect.UNICODE_START}{this}{self.dialect.UNICODE_END}{escape}"
    1092
    1093        if escape:
    1094            pattern = re.compile(rf"{escape.name}(\d+)")
    1095        else:
    1096            pattern = ESCAPED_UNICODE_RE
    1097
    1098        this = pattern.sub(r"\\u\1", this)
    1099        return f"{self.dialect.QUOTE_START}{this}{self.dialect.QUOTE_END}"

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

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

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

    1105    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    1106        this = self.sql(expression, "this")
    1107        specifier = self.sql(expression, "expression")
    1108        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    1109        return f"{this}{specifier}"

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

    1111    def datatype_sql(self, expression: exp.DataType) -> str:
    1112        type_value = expression.this
    1113
    1114        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
    1115            type_sql = self.sql(expression, "kind")
    1116        else:
    1117            type_sql = (
    1118                self.TYPE_MAPPING.get(type_value, type_value.value)
    1119                if isinstance(type_value, exp.DataType.Type)
    1120                else type_value
    1121            )
    1122
    1123        nested = ""
    1124        interior = self.expressions(expression, flat=True)
    1125        values = ""
    1126
    1127        if interior:
    1128            if expression.args.get("nested"):
    1129                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    1130                if expression.args.get("values") is not None:
    1131                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    1132                    values = self.expressions(expression, key="values", flat=True)
    1133                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    1134            elif type_value == exp.DataType.Type.INTERVAL:
    1135                nested = f" {interior}"
    1136            else:
    1137                nested = f"({interior})"
    1138
    1139        type_sql = f"{type_sql}{nested}{values}"
    1140        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
    1141            exp.DataType.Type.TIMETZ,
    1142            exp.DataType.Type.TIMESTAMPTZ,
    1143        ):
    1144            type_sql = f"{type_sql} WITH TIME ZONE"
    1145
    1146        return type_sql

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

    1148    def directory_sql(self, expression: exp.Directory) -> str:
    1149        local = "LOCAL " if expression.args.get("local") else ""
    1150        row_format = self.sql(expression, "row_format")
    1151        row_format = f" {row_format}" if row_format else ""
    1152        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

    1154    def delete_sql(self, expression: exp.Delete) -> str:
    1155        this = self.sql(expression, "this")
    1156        this = f" FROM {this}" if this else ""
    1157        using = self.sql(expression, "using")
    1158        using = f" USING {using}" if using else ""
    1159        where = self.sql(expression, "where")
    1160        returning = self.sql(expression, "returning")
    1161        limit = self.sql(expression, "limit")
    1162        tables = self.expressions(expression, key="tables")
    1163        tables = f" {tables}" if tables else ""
    1164        if self.RETURNING_END:
    1165            expression_sql = f"{this}{using}{where}{returning}{limit}"
    1166        else:
    1167            expression_sql = f"{returning}{this}{using}{where}{limit}"
    1168        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

    1170    def drop_sql(self, expression: exp.Drop) -> str:
    1171        this = self.sql(expression, "this")
    1172        kind = expression.args["kind"]
    1173        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    1174        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1175        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    1176        cascade = " CASCADE" if expression.args.get("cascade") else ""
    1177        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    1178        purge = " PURGE" if expression.args.get("purge") else ""
    1179        return (
    1180            f"DROP{temporary}{materialized} {kind}{exists_sql}{this}{cascade}{constraints}{purge}"
    1181        )

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

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

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

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

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

    1189    def fetch_sql(self, expression: exp.Fetch) -> str:
    1190        direction = expression.args.get("direction")
    1191        direction = f" {direction}" if direction else ""
    1192        count = expression.args.get("count")
    1193        count = f" {count}" if count else ""
    1194        if expression.args.get("percent"):
    1195            count = f"{count} PERCENT"
    1196        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    1197        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"

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

    1199    def filter_sql(self, expression: exp.Filter) -> str:
    1200        if self.AGGREGATE_FILTER_SUPPORTED:
    1201            this = self.sql(expression, "this")
    1202            where = self.sql(expression, "expression").strip()
    1203            return f"{this} FILTER({where})"
    1204
    1205        agg = expression.this
    1206        agg_arg = agg.this
    1207        cond = expression.expression.this
    1208        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1209        return self.sql(agg)

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

    1211    def hint_sql(self, expression: exp.Hint) -> str:
    1212        if not self.QUERY_HINTS:
    1213            self.unsupported("Hints are not supported")
    1214            return ""
    1215
    1216        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

    1218    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
    1219        using = self.sql(expression, "using")
    1220        using = f" USING {using}" if using else ""
    1221        columns = self.expressions(expression, key="columns", flat=True)
    1222        columns = f"({columns})" if columns else ""
    1223        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1224        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1225        where = self.sql(expression, "where")
    1226        include = self.expressions(expression, key="include", flat=True)
    1227        if include:
    1228            include = f" INCLUDE ({include})"
    1229        with_storage = self.expressions(expression, key="with_storage", flat=True)
    1230        with_storage = f" WITH ({with_storage})" if with_storage else ""
    1231        tablespace = self.sql(expression, "tablespace")
    1232        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
    1233
    1234        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}"

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

    1236    def index_sql(self, expression: exp.Index) -> str:
    1237        unique = "UNIQUE " if expression.args.get("unique") else ""
    1238        primary = "PRIMARY " if expression.args.get("primary") else ""
    1239        amp = "AMP " if expression.args.get("amp") else ""
    1240        name = self.sql(expression, "this")
    1241        name = f"{name} " if name else ""
    1242        table = self.sql(expression, "table")
    1243        table = f"{self.INDEX_ON} {table}" if table else ""
    1244
    1245        index = "INDEX " if not table else ""
    1246
    1247        params = self.sql(expression, "params")
    1248        return f"{unique}{primary}{amp}{index}{name}{table}{params}"

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

    1250    def identifier_sql(self, expression: exp.Identifier) -> str:
    1251        text = expression.name
    1252        lower = text.lower()
    1253        text = lower if self.normalize and not expression.quoted else text
    1254        text = text.replace(self.dialect.IDENTIFIER_END, self._escaped_identifier_end)
    1255        if (
    1256            expression.quoted
    1257            or self.dialect.can_identify(text, self.identify)
    1258            or lower in self.RESERVED_KEYWORDS
    1259            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1260        ):
    1261            text = f"{self.dialect.IDENTIFIER_START}{text}{self.dialect.IDENTIFIER_END}"
    1262        return text

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

    1264    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1265        input_format = self.sql(expression, "input_format")
    1266        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1267        output_format = self.sql(expression, "output_format")
    1268        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1269        return self.sep().join((input_format, output_format))

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

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

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

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

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

    1278    def properties_sql(self, expression: exp.Properties) -> str:
    1279        root_properties = []
    1280        with_properties = []
    1281
    1282        for p in expression.expressions:
    1283            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1284            if p_loc == exp.Properties.Location.POST_WITH:
    1285                with_properties.append(p)
    1286            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1287                root_properties.append(p)
    1288
    1289        return self.root_properties(
    1290            exp.Properties(expressions=root_properties)
    1291        ) + self.with_properties(exp.Properties(expressions=with_properties))

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

    1293    def root_properties(self, properties: exp.Properties) -> str:
    1294        if properties.expressions:
    1295            return self.sep() + self.expressions(properties, indent=False, sep=" ")
    1296        return ""

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

    1298    def properties(
    1299        self,
    1300        properties: exp.Properties,
    1301        prefix: str = "",
    1302        sep: str = ", ",
    1303        suffix: str = "",
    1304        wrapped: bool = True,
    1305    ) -> str:
    1306        if properties.expressions:
    1307            expressions = self.expressions(properties, sep=sep, indent=False)
    1308            if expressions:
    1309                expressions = self.wrap(expressions) if wrapped else expressions
    1310                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1311        return ""

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

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

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

    1316    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1317        properties_locs = defaultdict(list)
    1318        for p in properties.expressions:
    1319            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1320            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1321                properties_locs[p_loc].append(p)
    1322            else:
    1323                self.unsupported(f"Unsupported property {p.key}")
    1324
    1325        return properties_locs

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

    1327    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1328        if isinstance(expression.this, exp.Dot):
    1329            return self.sql(expression, "this")
    1330        return f"'{expression.name}'" if string_key else expression.name

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

    1332    def property_sql(self, expression: exp.Property) -> str:
    1333        property_cls = expression.__class__
    1334        if property_cls == exp.Property:
    1335            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1336
    1337        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1338        if not property_name:
    1339            self.unsupported(f"Unsupported property {expression.key}")
    1340
    1341        return f"{property_name}={self.sql(expression, 'this')}"

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

    1343    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1344        if self.SUPPORTS_CREATE_TABLE_LIKE:
    1345            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1346            options = f" {options}" if options else ""
    1347
    1348            like = f"LIKE {self.sql(expression, 'this')}{options}"
    1349            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
    1350                like = f"({like})"
    1351
    1352            return like
    1353
    1354        if expression.expressions:
    1355            self.unsupported("Transpilation of LIKE property options is unsupported")
    1356
    1357        select = exp.select("*").from_(expression.this).limit(0)
    1358        return f"AS {self.sql(select)}"

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

    1360    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1361        no = "NO " if expression.args.get("no") else ""
    1362        protection = " PROTECTION" if expression.args.get("protection") else ""
    1363        return f"{no}FALLBACK{protection}"

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

    1365    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1366        no = "NO " if expression.args.get("no") else ""
    1367        local = expression.args.get("local")
    1368        local = f"{local} " if local else ""
    1369        dual = "DUAL " if expression.args.get("dual") else ""
    1370        before = "BEFORE " if expression.args.get("before") else ""
    1371        after = "AFTER " if expression.args.get("after") else ""
    1372        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1374    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1375        freespace = self.sql(expression, "this")
    1376        percent = " PERCENT" if expression.args.get("percent") else ""
    1377        return f"FREESPACE={freespace}{percent}"

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

    1379    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1380        if expression.args.get("default"):
    1381            property = "DEFAULT"
    1382        elif expression.args.get("on"):
    1383            property = "ON"
    1384        else:
    1385            property = "OFF"
    1386        return f"CHECKSUM={property}"

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

    1388    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1389        if expression.args.get("no"):
    1390            return "NO MERGEBLOCKRATIO"
    1391        if expression.args.get("default"):
    1392            return "DEFAULT MERGEBLOCKRATIO"
    1393
    1394        percent = " PERCENT" if expression.args.get("percent") else ""
    1395        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1397    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1398        default = expression.args.get("default")
    1399        minimum = expression.args.get("minimum")
    1400        maximum = expression.args.get("maximum")
    1401        if default or minimum or maximum:
    1402            if default:
    1403                prop = "DEFAULT"
    1404            elif minimum:
    1405                prop = "MINIMUM"
    1406            else:
    1407                prop = "MAXIMUM"
    1408            return f"{prop} DATABLOCKSIZE"
    1409        units = expression.args.get("units")
    1410        units = f" {units}" if units else ""
    1411        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1413    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1414        autotemp = expression.args.get("autotemp")
    1415        always = expression.args.get("always")
    1416        default = expression.args.get("default")
    1417        manual = expression.args.get("manual")
    1418        never = expression.args.get("never")
    1419
    1420        if autotemp is not None:
    1421            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1422        elif always:
    1423            prop = "ALWAYS"
    1424        elif default:
    1425            prop = "DEFAULT"
    1426        elif manual:
    1427            prop = "MANUAL"
    1428        elif never:
    1429            prop = "NEVER"
    1430        return f"BLOCKCOMPRESSION={prop}"

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

    1432    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1433        no = expression.args.get("no")
    1434        no = " NO" if no else ""
    1435        concurrent = expression.args.get("concurrent")
    1436        concurrent = " CONCURRENT" if concurrent else ""
    1437
    1438        for_ = ""
    1439        if expression.args.get("for_all"):
    1440            for_ = " FOR ALL"
    1441        elif expression.args.get("for_insert"):
    1442            for_ = " FOR INSERT"
    1443        elif expression.args.get("for_none"):
    1444            for_ = " FOR NONE"
    1445        return f"WITH{no}{concurrent} ISOLATED LOADING{for_}"

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

    1447    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1448        if isinstance(expression.this, list):
    1449            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1450        if expression.this:
    1451            modulus = self.sql(expression, "this")
    1452            remainder = self.sql(expression, "expression")
    1453            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1454
    1455        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1456        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1457        return f"FROM ({from_expressions}) TO ({to_expressions})"

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

    1459    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1460        this = self.sql(expression, "this")
    1461
    1462        for_values_or_default = expression.expression
    1463        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1464            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1465        else:
    1466            for_values_or_default = " DEFAULT"
    1467
    1468        return f"PARTITION OF {this}{for_values_or_default}"

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

    1470    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1471        kind = expression.args.get("kind")
    1472        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1473        for_or_in = expression.args.get("for_or_in")
    1474        for_or_in = f" {for_or_in}" if for_or_in else ""
    1475        lock_type = expression.args.get("lock_type")
    1476        override = " OVERRIDE" if expression.args.get("override") else ""
    1477        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"

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

    1479    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1480        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1481        statistics = expression.args.get("statistics")
    1482        statistics_sql = ""
    1483        if statistics is not None:
    1484            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1485        return f"{data_sql}{statistics_sql}"

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

    1487    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1488        sql = "WITH(SYSTEM_VERSIONING=ON"
    1489
    1490        if expression.this:
    1491            history_table = self.sql(expression, "this")
    1492            sql = f"{sql}(HISTORY_TABLE={history_table}"
    1493
    1494            if expression.expression:
    1495                data_consistency_check = self.sql(expression, "expression")
    1496                sql = f"{sql}, DATA_CONSISTENCY_CHECK={data_consistency_check}"
    1497
    1498            sql = f"{sql})"
    1499
    1500        return f"{sql})"

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

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

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

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

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

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

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

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

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

    1546    def kill_sql(self, expression: exp.Kill) -> str:
    1547        kind = self.sql(expression, "kind")
    1548        kind = f" {kind}" if kind else ""
    1549        this = self.sql(expression, "this")
    1550        this = f" {this}" if this else ""
    1551        return f"KILL{kind}{this}"

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

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

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

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

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

    1559    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1560        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1561
    1562        constraint = self.sql(expression, "constraint")
    1563        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
    1564
    1565        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
    1566        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
    1567        action = self.sql(expression, "action")
    1568
    1569        expressions = self.expressions(expression, flat=True)
    1570        if expressions:
    1571            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1572            expressions = f" {set_keyword}{expressions}"
    1573
    1574        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}"

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

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

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

    1579    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1580        fields = expression.args.get("fields")
    1581        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1582        escaped = expression.args.get("escaped")
    1583        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1584        items = expression.args.get("collection_items")
    1585        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1586        keys = expression.args.get("map_keys")
    1587        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1588        lines = expression.args.get("lines")
    1589        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1590        null = expression.args.get("null")
    1591        null = f" NULL DEFINED AS {null}" if null else ""
    1592        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1597    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1598        this = f"{self.sql(expression, 'this')} INDEX"
    1599        target = self.sql(expression, "target")
    1600        target = f" FOR {target}" if target else ""
    1601        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1603    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1604        this = self.sql(expression, "this")
    1605        kind = self.sql(expression, "kind")
    1606        expr = self.sql(expression, "expression")
    1607        return f"{this} ({kind} => {expr})"

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

    1609    def table_parts(self, expression: exp.Table) -> str:
    1610        return ".".join(
    1611            self.sql(part)
    1612            for part in (
    1613                expression.args.get("catalog"),
    1614                expression.args.get("db"),
    1615                expression.args.get("this"),
    1616            )
    1617            if part is not None
    1618        )

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

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

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

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

    1692    def pivot_sql(self, expression: exp.Pivot) -> str:
    1693        expressions = self.expressions(expression, flat=True)
    1694
    1695        if expression.this:
    1696            this = self.sql(expression, "this")
    1697            if not expressions:
    1698                return f"UNPIVOT {this}"
    1699
    1700            on = f"{self.seg('ON')} {expressions}"
    1701            using = self.expressions(expression, key="using", flat=True)
    1702            using = f"{self.seg('USING')} {using}" if using else ""
    1703            group = self.sql(expression, "group")
    1704            return f"PIVOT {this}{on}{using}{group}"
    1705
    1706        alias = self.sql(expression, "alias")
    1707        alias = f" AS {alias}" if alias else ""
    1708        direction = "UNPIVOT" if expression.unpivot else "PIVOT"
    1709        field = self.sql(expression, "field")
    1710        include_nulls = expression.args.get("include_nulls")
    1711        if include_nulls is not None:
    1712            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    1713        else:
    1714            nulls = ""
    1715        return f"{direction}{nulls}({expressions} FOR {field}){alias}"

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

    1717    def version_sql(self, expression: exp.Version) -> str:
    1718        this = f"FOR {expression.name}"
    1719        kind = expression.text("kind")
    1720        expr = self.sql(expression, "expression")
    1721        return f"{this} {kind} {expr}"

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

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

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

    1726    def update_sql(self, expression: exp.Update) -> str:
    1727        this = self.sql(expression, "this")
    1728        set_sql = self.expressions(expression, flat=True)
    1729        from_sql = self.sql(expression, "from")
    1730        where_sql = self.sql(expression, "where")
    1731        returning = self.sql(expression, "returning")
    1732        order = self.sql(expression, "order")
    1733        limit = self.sql(expression, "limit")
    1734        if self.RETURNING_END:
    1735            expression_sql = f"{from_sql}{where_sql}{returning}"
    1736        else:
    1737            expression_sql = f"{returning}{from_sql}{where_sql}"
    1738        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    1739        return self.prepend_ctes(expression, sql)

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

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

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

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

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

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

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

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

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

    1792    def group_sql(self, expression: exp.Group) -> str:
    1793        group_by = self.op_expressions("GROUP BY", expression)
    1794
    1795        if expression.args.get("all"):
    1796            return f"{group_by} ALL"
    1797
    1798        grouping_sets = self.expressions(expression, key="grouping_sets", indent=False)
    1799        grouping_sets = (
    1800            f"{self.seg('GROUPING SETS')} {self.wrap(grouping_sets)}" if grouping_sets else ""
    1801        )
    1802
    1803        cube = expression.args.get("cube", [])
    1804        if seq_get(cube, 0) is True:
    1805            return f"{group_by}{self.seg('WITH CUBE')}"
    1806        else:
    1807            cube_sql = self.expressions(expression, key="cube", indent=False)
    1808            cube_sql = f"{self.seg('CUBE')} {self.wrap(cube_sql)}" if cube_sql else ""
    1809
    1810        rollup = expression.args.get("rollup", [])
    1811        if seq_get(rollup, 0) is True:
    1812            return f"{group_by}{self.seg('WITH ROLLUP')}"
    1813        else:
    1814            rollup_sql = self.expressions(expression, key="rollup", indent=False)
    1815            rollup_sql = f"{self.seg('ROLLUP')} {self.wrap(rollup_sql)}" if rollup_sql else ""
    1816
    1817        groupings = csv(
    1818            grouping_sets,
    1819            cube_sql,
    1820            rollup_sql,
    1821            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    1822            sep=self.GROUPINGS_SEP,
    1823        )
    1824
    1825        if expression.args.get("expressions") and groupings:
    1826            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    1827
    1828        return f"{group_by}{groupings}"

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

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

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

    1834    def connect_sql(self, expression: exp.Connect) -> str:
    1835        start = self.sql(expression, "start")
    1836        start = self.seg(f"START WITH {start}") if start else ""
    1837        connect = self.sql(expression, "connect")
    1838        connect = self.seg(f"CONNECT BY {connect}")
    1839        return start + connect

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

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

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

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

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

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

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

    1891    def lateral_op(self, expression: exp.Lateral) -> str:
    1892        cross_apply = expression.args.get("cross_apply")
    1893
    1894        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    1895        if cross_apply is True:
    1896            op = "INNER JOIN "
    1897        elif cross_apply is False:
    1898            op = "LEFT JOIN "
    1899        else:
    1900            op = ""
    1901
    1902        return f"{op}LATERAL"

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

    1904    def lateral_sql(self, expression: exp.Lateral) -> str:
    1905        this = self.sql(expression, "this")
    1906
    1907        if expression.args.get("view"):
    1908            alias = expression.args["alias"]
    1909            columns = self.expressions(alias, key="columns", flat=True)
    1910            table = f" {alias.name}" if alias.name else ""
    1911            columns = f" AS {columns}" if columns else ""
    1912            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    1913            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    1914
    1915        alias = self.sql(expression, "alias")
    1916        alias = f" AS {alias}" if alias else ""
    1917        return f"{self.lateral_op(expression)} {this}{alias}"

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

    1919    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    1920        this = self.sql(expression, "this")
    1921
    1922        args = [
    1923            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    1924            for e in (expression.args.get(k) for k in ("offset", "expression"))
    1925            if e
    1926        ]
    1927
    1928        args_sql = ", ".join(self.sql(e) for e in args)
    1929        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
    1930        expressions = self.expressions(expression, flat=True)
    1931        expressions = f" BY {expressions}" if expressions else ""
    1932
    1933        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}"

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

    1935    def offset_sql(self, expression: exp.Offset) -> str:
    1936        this = self.sql(expression, "this")
    1937        value = expression.expression
    1938        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    1939        expressions = self.expressions(expression, flat=True)
    1940        expressions = f" BY {expressions}" if expressions else ""
    1941        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"

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

    1943    def setitem_sql(self, expression: exp.SetItem) -> str:
    1944        kind = self.sql(expression, "kind")
    1945        kind = f"{kind} " if kind else ""
    1946        this = self.sql(expression, "this")
    1947        expressions = self.expressions(expression)
    1948        collate = self.sql(expression, "collate")
    1949        collate = f" COLLATE {collate}" if collate else ""
    1950        global_ = "GLOBAL " if expression.args.get("global") else ""
    1951        return f"{global_}{kind}{this}{expressions}{collate}"

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

    1953    def set_sql(self, expression: exp.Set) -> str:
    1954        expressions = (
    1955            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    1956        )
    1957        tag = " TAG" if expression.args.get("tag") else ""
    1958        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"

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

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

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

    1963    def lock_sql(self, expression: exp.Lock) -> str:
    1964        if not self.LOCKING_READS_SUPPORTED:
    1965            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    1966            return ""
    1967
    1968        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    1969        expressions = self.expressions(expression, flat=True)
    1970        expressions = f" OF {expressions}" if expressions else ""
    1971        wait = expression.args.get("wait")
    1972
    1973        if wait is not None:
    1974            if isinstance(wait, exp.Literal):
    1975                wait = f" WAIT {self.sql(wait)}"
    1976            else:
    1977                wait = " NOWAIT" if wait else " SKIP LOCKED"
    1978
    1979        return f"{lock_type}{expressions}{wait or ''}"

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

    1981    def literal_sql(self, expression: exp.Literal) -> str:
    1982        text = expression.this or ""
    1983        if expression.is_string:
    1984            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    1985        return text

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

    1987    def escape_str(self, text: str) -> str:
    1988        text = text.replace(self.dialect.QUOTE_END, self._escaped_quote_end)
    1989        if self.dialect.INVERSE_ESCAPE_SEQUENCES:
    1990            text = "".join(self.dialect.INVERSE_ESCAPE_SEQUENCES.get(ch, ch) for ch in text)
    1991        elif self.pretty:
    1992            text = text.replace("\n", self.SENTINEL_LINE_BREAK)
    1993        return text

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

    1995    def loaddata_sql(self, expression: exp.LoadData) -> str:
    1996        local = " LOCAL" if expression.args.get("local") else ""
    1997        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    1998        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    1999        this = f" INTO TABLE {self.sql(expression, 'this')}"
    2000        partition = self.sql(expression, "partition")
    2001        partition = f" {partition}" if partition else ""
    2002        input_format = self.sql(expression, "input_format")
    2003        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    2004        serde = self.sql(expression, "serde")
    2005        serde = f" SERDE {serde}" if serde else ""
    2006        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    2008    def null_sql(self, *_) -> str:
    2009        return "NULL"

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

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

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

    2014    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2015        this = self.sql(expression, "this")
    2016        this = f"{this} " if this else this
    2017        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2018        order = self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat)  # type: ignore
    2019        interpolated_values = [
    2020            f"{self.sql(named_expression, 'alias')} AS {self.sql(named_expression, 'this')}"
    2021            for named_expression in expression.args.get("interpolate") or []
    2022        ]
    2023        interpolate = (
    2024            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    2025        )
    2026        return f"{order}{interpolate}"

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

    2028    def withfill_sql(self, expression: exp.WithFill) -> str:
    2029        from_sql = self.sql(expression, "from")
    2030        from_sql = f" FROM {from_sql}" if from_sql else ""
    2031        to_sql = self.sql(expression, "to")
    2032        to_sql = f" TO {to_sql}" if to_sql else ""
    2033        step_sql = self.sql(expression, "step")
    2034        step_sql = f" STEP {step_sql}" if step_sql else ""
    2035        return f"WITH FILL{from_sql}{to_sql}{step_sql}"

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

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

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

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

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

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

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

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

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

    2094    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    2095        partition = self.partition_by_sql(expression)
    2096        order = self.sql(expression, "order")
    2097        measures = self.expressions(expression, key="measures")
    2098        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    2099        rows = self.sql(expression, "rows")
    2100        rows = self.seg(rows) if rows else ""
    2101        after = self.sql(expression, "after")
    2102        after = self.seg(after) if after else ""
    2103        pattern = self.sql(expression, "pattern")
    2104        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    2105        definition_sqls = [
    2106            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    2107            for definition in expression.args.get("define", [])
    2108        ]
    2109        definitions = self.expressions(sqls=definition_sqls)
    2110        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    2111        body = "".join(
    2112            (
    2113                partition,
    2114                order,
    2115                measures,
    2116                rows,
    2117                after,
    2118                pattern,
    2119                define,
    2120            )
    2121        )
    2122        alias = self.sql(expression, "alias")
    2123        alias = f" {alias}" if alias else ""
    2124        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    2126    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    2127        limit: t.Optional[exp.Fetch | exp.Limit] = expression.args.get("limit")
    2128
    2129        # If the limit is generated as TOP, we need to ensure it's not generated twice
    2130        with_offset_limit_modifiers = not isinstance(limit, exp.Limit) or not self.LIMIT_IS_TOP
    2131
    2132        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    2133            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    2134        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    2135            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    2136
    2137        fetch = isinstance(limit, exp.Fetch)
    2138
    2139        offset_limit_modifiers = (
    2140            self.offset_limit_modifiers(expression, fetch, limit)
    2141            if with_offset_limit_modifiers
    2142            else []
    2143        )
    2144
    2145        options = self.expressions(expression, key="options")
    2146        if options:
    2147            options = f" OPTION{self.wrap(options)}"
    2148
    2149        return csv(
    2150            *sqls,
    2151            *[self.sql(join) for join in expression.args.get("joins") or []],
    2152            self.sql(expression, "connect"),
    2153            self.sql(expression, "match"),
    2154            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2155            self.sql(expression, "prewhere"),
    2156            self.sql(expression, "where"),
    2157            self.sql(expression, "group"),
    2158            self.sql(expression, "having"),
    2159            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
    2160            self.sql(expression, "order"),
    2161            *offset_limit_modifiers,
    2162            *self.after_limit_modifiers(expression),
    2163            options,
    2164            sep="",
    2165        )

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

    2167    def queryoption_sql(self, expression: exp.QueryOption) -> str:
    2168        return ""

def offset_limit_modifiers( self, expression: sqlglot.expressions.Expression, fetch: bool, limit: Union[sqlglot.expressions.Fetch, sqlglot.expressions.Limit, NoneType]) -> List[str]: View Source

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2707    def paren_sql(self, expression: exp.Paren) -> str:
    2708        if isinstance(expression.unnest(), exp.Select):
    2709            sql = self.wrap(expression)
    2710        else:
    2711            sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
    2712            sql = f"({sql}{self.seg(')', sep='')}"
    2713
    2714        return self.prepend_ctes(expression, sql)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2768    def connector_sql(self, expression: exp.Connector, op: str) -> str:
    2769        if not self.pretty:
    2770            return self.binary(expression, op)
    2771
    2772        sqls = tuple(
    2773            self.maybe_comment(self.sql(e), e, e.parent.comments or []) if i != 1 else self.sql(e)
    2774            for i, e in enumerate(expression.flatten(unnest=False))
    2775        )
    2776
    2777        sep = "\n" if self.text_width(sqls) > self.max_text_width else " "
    2778        return f"{sep}{op} ".join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

    2798    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    2799        format_sql = self.sql(expression, "format")
    2800        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    2801        to_sql = self.sql(expression, "to")
    2802        to_sql = f" {to_sql}" if to_sql else ""
    2803        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

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

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

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

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

    2812    def collate_sql(self, expression: exp.Collate) -> str:
    2813        if self.COLLATE_IS_FUNC:
    2814            return self.function_fallback_sql(expression)
    2815        return self.binary(expression, "COLLATE")

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

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

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

    2820    def comment_sql(self, expression: exp.Comment) -> str:
    2821        this = self.sql(expression, "this")
    2822        kind = expression.args["kind"]
    2823        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    2824        expression_sql = self.sql(expression, "expression")
    2825        return f"COMMENT{exists_sql}ON {kind} {this} IS {expression_sql}"

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

    2827    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    2828        this = self.sql(expression, "this")
    2829        delete = " DELETE" if expression.args.get("delete") else ""
    2830        recompress = self.sql(expression, "recompress")
    2831        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    2832        to_disk = self.sql(expression, "to_disk")
    2833        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    2834        to_volume = self.sql(expression, "to_volume")
    2835        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    2836        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    2838    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    2839        where = self.sql(expression, "where")
    2840        group = self.sql(expression, "group")
    2841        aggregates = self.expressions(expression, key="aggregates")
    2842        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    2843
    2844        if not (where or group or aggregates) and len(expression.expressions) == 1:
    2845            return f"TTL {self.expressions(expression, flat=True)}"
    2846
    2847        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    2852    def commit_sql(self, expression: exp.Commit) -> str:
    2853        chain = expression.args.get("chain")
    2854        if chain is not None:
    2855            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    2856
    2857        return f"COMMIT{chain or ''}"

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

    2859    def rollback_sql(self, expression: exp.Rollback) -> str:
    2860        savepoint = expression.args.get("savepoint")
    2861        savepoint = f" TO {savepoint}" if savepoint else ""
    2862        return f"ROLLBACK{savepoint}"

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

    2864    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    2865        this = self.sql(expression, "this")
    2866
    2867        dtype = self.sql(expression, "dtype")
    2868        if dtype:
    2869            collate = self.sql(expression, "collate")
    2870            collate = f" COLLATE {collate}" if collate else ""
    2871            using = self.sql(expression, "using")
    2872            using = f" USING {using}" if using else ""
    2873            return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}"
    2874
    2875        default = self.sql(expression, "default")
    2876        if default:
    2877            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    2878
    2879        comment = self.sql(expression, "comment")
    2880        if comment:
    2881            return f"ALTER COLUMN {this} COMMENT {comment}"
    2882
    2883        if not expression.args.get("drop"):
    2884            self.unsupported("Unsupported ALTER COLUMN syntax")
    2885
    2886        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    2888    def renametable_sql(self, expression: exp.RenameTable) -> str:
    2889        if not self.RENAME_TABLE_WITH_DB:
    2890            # Remove db from tables
    2891            expression = expression.transform(
    2892                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    2893            )
    2894        this = self.sql(expression, "this")
    2895        return f"RENAME TO {this}"

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

    2897    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    2898        exists = " IF EXISTS" if expression.args.get("exists") else ""
    2899        old_column = self.sql(expression, "this")
    2900        new_column = self.sql(expression, "to")
    2901        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"

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

    2903    def altertable_sql(self, expression: exp.AlterTable) -> str:
    2904        actions = expression.args["actions"]
    2905
    2906        if isinstance(actions[0], exp.ColumnDef):
    2907            actions = self.add_column_sql(expression)
    2908        elif isinstance(actions[0], exp.Schema):
    2909            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    2910        elif isinstance(actions[0], exp.Delete):
    2911            actions = self.expressions(expression, key="actions", flat=True)
    2912        else:
    2913            actions = self.expressions(expression, key="actions", flat=True)
    2914
    2915        exists = " IF EXISTS" if expression.args.get("exists") else ""
    2916        only = " ONLY" if expression.args.get("only") else ""
    2917        options = self.expressions(expression, key="options")
    2918        options = f", {options}" if options else ""
    2919        return f"ALTER TABLE{exists}{only} {self.sql(expression, 'this')} {actions}{options}"

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

    2921    def add_column_sql(self, expression: exp.AlterTable) -> str:
    2922        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    2923            return self.expressions(
    2924                expression,
    2925                key="actions",
    2926                prefix="ADD COLUMN ",
    2927            )
    2928        return f"ADD {self.expressions(expression, key='actions', flat=True)}"

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

    2930    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    2931        expressions = self.expressions(expression)
    2932        exists = " IF EXISTS " if expression.args.get("exists") else " "
    2933        return f"DROP{exists}{expressions}"

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

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

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

    2938    def distinct_sql(self, expression: exp.Distinct) -> str:
    2939        this = self.expressions(expression, flat=True)
    2940
    2941        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    2942            case = exp.case()
    2943            for arg in expression.expressions:
    2944                case = case.when(arg.is_(exp.null()), exp.null())
    2945            this = self.sql(case.else_(f"({this})"))
    2946
    2947        this = f" {this}" if this else ""
    2948
    2949        on = self.sql(expression, "on")
    2950        on = f" ON {on}" if on else ""
    2951        return f"DISTINCT{this}{on}"

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

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

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

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

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

    2959    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    2960        this_sql = self.sql(expression, "this")
    2961        expression_sql = self.sql(expression, "expression")
    2962        kind = "MAX" if expression.args.get("max") else "MIN"
    2963        return f"{this_sql} HAVING {kind} {expression_sql}"

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

    2989    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    2990        return self.sql(
    2991            exp.Cast(
    2992                this=exp.Div(this=expression.this, expression=expression.expression),
    2993                to=exp.DataType(this=exp.DataType.Type.INT),
    2994            )
    2995        )

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

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

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

    3002    def div_sql(self, expression: exp.Div) -> str:
    3003        l, r = expression.left, expression.right
    3004
    3005        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    3006            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    3007
    3008        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    3009            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
    3010                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    3011
    3012        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    3013            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    3014                return self.sql(
    3015                    exp.cast(
    3016                        l / r,
    3017                        to=exp.DataType.Type.BIGINT,
    3018                    )
    3019                )
    3020
    3021        return self.binary(expression, "/")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3056    def is_sql(self, expression: exp.Is) -> str:
    3057        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3058            return self.sql(
    3059                expression.this if expression.expression.this else exp.not_(expression.this)
    3060            )
    3061        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3105    def log_sql(self, expression: exp.Log) -> str:
    3106        this = expression.this
    3107        expr = expression.expression
    3108
    3109        if not self.dialect.LOG_BASE_FIRST:
    3110            this, expr = expr, this
    3111
    3112        return self.func("LOG", this, expr)

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

    3114    def use_sql(self, expression: exp.Use) -> str:
    3115        kind = self.sql(expression, "kind")
    3116        kind = f" {kind}" if kind else ""
    3117        this = self.sql(expression, "this")
    3118        this = f" {this}" if this else ""
    3119        return f"USE{kind}{this}"

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

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

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

    3125    def function_fallback_sql(self, expression: exp.Func) -> str:
    3126        args = []
    3127
    3128        for key in expression.arg_types:
    3129            arg_value = expression.args.get(key)
    3130
    3131            if isinstance(arg_value, list):
    3132                for value in arg_value:
    3133                    args.append(value)
    3134            elif arg_value is not None:
    3135                args.append(arg_value)
    3136
    3137        if self.normalize_functions:
    3138            name = expression.sql_name()
    3139        else:
    3140            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3141
    3142        return self.func(name, *args)

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

    3144    def func(
    3145        self,
    3146        name: str,
    3147        *args: t.Optional[exp.Expression | str],
    3148        prefix: str = "(",
    3149        suffix: str = ")",
    3150    ) -> str:
    3151        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

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

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

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

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

    3162    def format_time(self, expression: exp.Expression) -> t.Optional[str]:
    3163        return format_time(
    3164            self.sql(expression, "format"),
    3165            self.dialect.INVERSE_TIME_MAPPING,
    3166            self.dialect.INVERSE_TIME_TRIE,
    3167        )

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

    3169    def expressions(
    3170        self,
    3171        expression: t.Optional[exp.Expression] = None,
    3172        key: t.Optional[str] = None,
    3173        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    3174        flat: bool = False,
    3175        indent: bool = True,
    3176        skip_first: bool = False,
    3177        sep: str = ", ",
    3178        prefix: str = "",
    3179    ) -> str:
    3180        expressions = expression.args.get(key or "expressions") if expression else sqls
    3181
    3182        if not expressions:
    3183            return ""
    3184
    3185        if flat:
    3186            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    3187
    3188        num_sqls = len(expressions)
    3189
    3190        # These are calculated once in case we have the leading_comma / pretty option set, correspondingly
    3191        pad = " " * self.pad
    3192        stripped_sep = sep.strip()
    3193
    3194        result_sqls = []
    3195        for i, e in enumerate(expressions):
    3196            sql = self.sql(e, comment=False)
    3197            if not sql:
    3198                continue
    3199
    3200            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    3201
    3202            if self.pretty:
    3203                if self.leading_comma:
    3204                    result_sqls.append(f"{sep if i > 0 else pad}{prefix}{sql}{comments}")
    3205                else:
    3206                    result_sqls.append(
    3207                        f"{prefix}{sql}{stripped_sep if i + 1 < num_sqls else ''}{comments}"
    3208                    )
    3209            else:
    3210                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    3211
    3212        result_sql = "\n".join(result_sqls) if self.pretty else "".join(result_sqls)
    3213        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

    3215    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3216        flat = flat or isinstance(expression.parent, exp.Properties)
    3217        expressions_sql = self.expressions(expression, flat=flat)
    3218        if flat:
    3219            return f"{op} {expressions_sql}"
    3220        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    3222    def naked_property(self, expression: exp.Property) -> str:
    3223        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3224        if not property_name:
    3225            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3226        return f"{property_name} {self.sql(expression, 'this')}"

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

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

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

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

    3234    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3235        this = self.sql(expression, "this")
    3236        expressions = self.no_identify(self.expressions, expression)
    3237        expressions = (
    3238            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3239        )
    3240        return f"{this}{expressions}"

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

    3242    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3243        this = self.sql(expression, "this")
    3244        expressions = self.expressions(expression, flat=True)
    3245        return f"{this}({expressions})"

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

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

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

    3250    def when_sql(self, expression: exp.When) -> str:
    3251        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3252        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3253        condition = self.sql(expression, "condition")
    3254        condition = f" AND {condition}" if condition else ""
    3255
    3256        then_expression = expression.args.get("then")
    3257        if isinstance(then_expression, exp.Insert):
    3258            then = f"INSERT {self.sql(then_expression, 'this')}"
    3259            if "expression" in then_expression.args:
    3260                then += f" VALUES {self.sql(then_expression, 'expression')}"
    3261        elif isinstance(then_expression, exp.Update):
    3262            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3263                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3264            else:
    3265                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    3266        else:
    3267            then = self.sql(then_expression)
    3268        return f"WHEN {matched}{source}{condition} THEN {then}"

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

    3270    def merge_sql(self, expression: exp.Merge) -> str:
    3271        table = expression.this
    3272        table_alias = ""
    3273
    3274        hints = table.args.get("hints")
    3275        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3276            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3277            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3278
    3279        this = self.sql(table)
    3280        using = f"USING {self.sql(expression, 'using')}"
    3281        on = f"ON {self.sql(expression, 'on')}"
    3282        expressions = self.expressions(expression, sep=" ")
    3283
    3284        return self.prepend_ctes(
    3285            expression, f"MERGE INTO {this}{table_alias} {using} {on} {expressions}"
    3286        )

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

    3288    def tochar_sql(self, expression: exp.ToChar) -> str:
    3289        if expression.args.get("format"):
    3290            self.unsupported("Format argument unsupported for TO_CHAR/TO_VARCHAR function")
    3291
    3292        return self.sql(exp.cast(expression.this, "text"))

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

    3294    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3295        if not self.SUPPORTS_TO_NUMBER:
    3296            self.unsupported("Unsupported TO_NUMBER function")
    3297            return self.sql(exp.cast(expression.this, "double"))
    3298
    3299        fmt = expression.args.get("format")
    3300        if not fmt:
    3301            self.unsupported("Conversion format is required for TO_NUMBER")
    3302            return self.sql(exp.cast(expression.this, "double"))
    3303
    3304        return self.func("TO_NUMBER", expression.this, fmt)

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

    3306    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3307        this = self.sql(expression, "this")
    3308        kind = self.sql(expression, "kind")
    3309        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3310        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3311        return f"{this}({kind}{args})"

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

    3313    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3314        this = self.sql(expression, "this")
    3315        max = self.sql(expression, "max")
    3316        min = self.sql(expression, "min")
    3317        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

    3325    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3326        expressions = self.expressions(expression, key="expressions", flat=True)
    3327        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3328        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3329        buckets = self.sql(expression, "buckets")
    3330        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    3332    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3333        this = self.sql(expression, "this")
    3334        having = self.sql(expression, "having")
    3335
    3336        if having:
    3337            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3338
    3339        return self.func("ANY_VALUE", this)

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

    3341    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3342        transform = self.func("TRANSFORM", *expression.expressions)
    3343        row_format_before = self.sql(expression, "row_format_before")
    3344        row_format_before = f" {row_format_before}" if row_format_before else ""
    3345        record_writer = self.sql(expression, "record_writer")
    3346        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3347        using = f" USING {self.sql(expression, 'command_script')}"
    3348        schema = self.sql(expression, "schema")
    3349        schema = f" AS {schema}" if schema else ""
    3350        row_format_after = self.sql(expression, "row_format_after")
    3351        row_format_after = f" {row_format_after}" if row_format_after else ""
    3352        record_reader = self.sql(expression, "record_reader")
    3353        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3354        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

    3356    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3357        key_block_size = self.sql(expression, "key_block_size")
    3358        if key_block_size:
    3359            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3360
    3361        using = self.sql(expression, "using")
    3362        if using:
    3363            return f"USING {using}"
    3364
    3365        parser = self.sql(expression, "parser")
    3366        if parser:
    3367            return f"WITH PARSER {parser}"
    3368
    3369        comment = self.sql(expression, "comment")
    3370        if comment:
    3371            return f"COMMENT {comment}"
    3372
    3373        visible = expression.args.get("visible")
    3374        if visible is not None:
    3375            return "VISIBLE" if visible else "INVISIBLE"
    3376
    3377        engine_attr = self.sql(expression, "engine_attr")
    3378        if engine_attr:
    3379            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3380
    3381        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3382        if secondary_engine_attr:
    3383            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3384
    3385        self.unsupported("Unsupported index constraint option.")
    3386        return ""

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

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

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

    3392    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3393        kind = self.sql(expression, "kind")
    3394        kind = f"{kind} INDEX" if kind else "INDEX"
    3395        this = self.sql(expression, "this")
    3396        this = f" {this}" if this else ""
    3397        index_type = self.sql(expression, "index_type")
    3398        index_type = f" USING {index_type}" if index_type else ""
    3399        schema = self.sql(expression, "schema")
    3400        schema = f" {schema}" if schema else ""
    3401        options = self.expressions(expression, key="options", sep=" ")
    3402        options = f" {options}" if options else ""
    3403        return f"{kind}{this}{index_type}{schema}{options}"

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

    3405    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3406        if self.NVL2_SUPPORTED:
    3407            return self.function_fallback_sql(expression)
    3408
    3409        case = exp.Case().when(
    3410            expression.this.is_(exp.null()).not_(copy=False),
    3411            expression.args["true"],
    3412            copy=False,
    3413        )
    3414        else_cond = expression.args.get("false")
    3415        if else_cond:
    3416            case.else_(else_cond, copy=False)
    3417
    3418        return self.sql(case)

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

    3420    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3421        this = self.sql(expression, "this")
    3422        expr = self.sql(expression, "expression")
    3423        iterator = self.sql(expression, "iterator")
    3424        condition = self.sql(expression, "condition")
    3425        condition = f" IF {condition}" if condition else ""
    3426        return f"{this} FOR {expr} IN {iterator}{condition}"

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

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

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

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

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

    3434    def predict_sql(self, expression: exp.Predict) -> str:
    3435        model = self.sql(expression, "this")
    3436        model = f"MODEL {model}"
    3437        table = self.sql(expression, "expression")
    3438        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    3439        parameters = self.sql(expression, "params_struct")
    3440        return self.func("PREDICT", model, table, parameters or None)

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

    3442    def forin_sql(self, expression: exp.ForIn) -> str:
    3443        this = self.sql(expression, "this")
    3444        expression_sql = self.sql(expression, "expression")
    3445        return f"FOR {this} DO {expression_sql}"

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

    3447    def refresh_sql(self, expression: exp.Refresh) -> str:
    3448        this = self.sql(expression, "this")
    3449        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    3450        return f"REFRESH {table}{this}"

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

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

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

    3455    def toarray_sql(self, expression: exp.ToArray) -> str:
    3456        arg = expression.this
    3457        if not arg.type:
    3458            from sqlglot.optimizer.annotate_types import annotate_types
    3459
    3460            arg = annotate_types(arg)
    3461
    3462        if arg.is_type(exp.DataType.Type.ARRAY):
    3463            return self.sql(arg)
    3464
    3465        cond_for_null = arg.is_(exp.null())
    3466        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

    3468    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    3469        this = expression.this
    3470        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    3471            return self.sql(this)
    3472
    3473        return self.sql(exp.cast(this, "time"))

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

    3475    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    3476        this = expression.this
    3477        time_format = self.format_time(expression)
    3478
    3479        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    3480            return self.sql(
    3481                exp.cast(exp.StrToTime(this=this, format=expression.args["format"]), "date")
    3482            )
    3483
    3484        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    3485            return self.sql(this)
    3486
    3487        return self.sql(exp.cast(this, "date"))

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

    3489    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    3490        return self.sql(
    3491            exp.func(
    3492                "DATEDIFF",
    3493                expression.this,
    3494                exp.cast(exp.Literal.string("1970-01-01"), "date"),
    3495                "day",
    3496            )
    3497        )

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

    3499    def lastday_sql(self, expression: exp.LastDay) -> str:
    3500        if self.LAST_DAY_SUPPORTS_DATE_PART:
    3501            return self.function_fallback_sql(expression)
    3502
    3503        unit = expression.text("unit")
    3504        if unit and unit != "MONTH":
    3505            self.unsupported("Date parts are not supported in LAST_DAY.")
    3506
    3507        return self.func("LAST_DAY", expression.this)

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

    3509    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    3510        if self.CAN_IMPLEMENT_ARRAY_ANY:
    3511            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    3512            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    3513            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    3514            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    3515
    3516        from sqlglot.dialects import Dialect
    3517
    3518        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    3519        if self.dialect.__class__ != Dialect:
    3520            self.unsupported("ARRAY_ANY is unsupported")
    3521
    3522        return self.function_fallback_sql(expression)

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

    3548    def generateseries_sql(self, expression: exp.GenerateSeries) -> str:
    3549        expression.set("is_end_exclusive", None)
    3550        return self.function_fallback_sql(expression)

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

    3552    def struct_sql(self, expression: exp.Struct) -> str:
    3553        expression.set(
    3554            "expressions",
    3555            [
    3556                exp.alias_(e.expression, e.this) if isinstance(e, exp.PropertyEQ) else e
    3557                for e in expression.expressions
    3558            ],
    3559        )
    3560
    3561        return self.function_fallback_sql(expression)

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

    3563    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    3564        low = self.sql(expression, "this")
    3565        high = self.sql(expression, "expression")
    3566
    3567        return f"{low} TO {high}"

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

    3569    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    3570        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    3571        tables = f" {self.expressions(expression)}"
    3572
    3573        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3574
    3575        on_cluster = self.sql(expression, "cluster")
    3576        on_cluster = f" {on_cluster}" if on_cluster else ""
    3577
    3578        identity = self.sql(expression, "identity")
    3579        identity = f" {identity} IDENTITY" if identity else ""
    3580
    3581        option = self.sql(expression, "option")
    3582        option = f" {option}" if option else ""
    3583
    3584        partition = self.sql(expression, "partition")
    3585        partition = f" {partition}" if partition else ""
    3586
    3587        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"

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

    3591    def convert_sql(self, expression: exp.Convert) -> str:
    3592        to = expression.this
    3593        value = expression.expression
    3594        style = expression.args.get("style")
    3595        safe = expression.args.get("safe")
    3596        strict = expression.args.get("strict")
    3597
    3598        if not to or not value:
    3599            return ""
    3600
    3601        # Retrieve length of datatype and override to default if not specified
    3602        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3603            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    3604
    3605        transformed: t.Optional[exp.Expression] = None
    3606        cast = exp.Cast if strict else exp.TryCast
    3607
    3608        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
    3609        if isinstance(style, exp.Literal) and style.is_int:
    3610            from sqlglot.dialects.tsql import TSQL
    3611
    3612            style_value = style.name
    3613            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
    3614            if not converted_style:
    3615                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
    3616
    3617            fmt = exp.Literal.string(converted_style)
    3618
    3619            if to.this == exp.DataType.Type.DATE:
    3620                transformed = exp.StrToDate(this=value, format=fmt)
    3621            elif to.this == exp.DataType.Type.DATETIME:
    3622                transformed = exp.StrToTime(this=value, format=fmt)
    3623            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3624                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
    3625            elif to.this == exp.DataType.Type.TEXT:
    3626                transformed = exp.TimeToStr(this=value, format=fmt)
    3627
    3628        if not transformed:
    3629            transformed = cast(this=value, to=to, safe=safe)
    3630
    3631        return self.sql(transformed)