sqlglot.generator API documentation

Edit on GitHub

# sqlglot.generator

View Source

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

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

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

Generator converts a given syntax tree to the corresponding SQL string.

###### Arguments:

- pretty: Whether to format the produced SQL string. Default: False.
- identify: Determines when an identifier should be quoted. Possible values are: False (default): Never quote, except in cases where it's mandatory by the dialect. True or 'always': Always quote. 'safe': Only quote identifiers that are case insensitive.
- normalize: Whether to normalize identifiers to lowercase. Default: False.
- pad: The pad size in a formatted string. For example, this affects the indentation of a projection in a query, relative to its nesting level. Default: 2.
- indent: The indentation size in a formatted string. For example, this affects the indentation of subqueries and filters under a `WHERE` clause. Default: 2.
- normalize_functions: How to normalize function names. Possible values are: "upper" or True (default): Convert names to uppercase. "lower": Convert names to lowercase. False: Disables function name normalization.
- unsupported_level: Determines the generator's behavior when it encounters unsupported expressions. Default ErrorLevel.WARN.
- max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError. This is only relevant if unsupported_level is ErrorLevel.RAISE. Default: 3
- leading_comma: Whether the comma is leading or trailing in select expressions. This is only relevant when generating in pretty mode. Default: False
- max_text_width: The max number of characters in a segment before creating new lines in pretty mode. The default is on the smaller end because the length only represents a segment and not the true line length. Default: 80
- comments: Whether to preserve comments in the output SQL code. Default: True

Generator( pretty: Optional[bool] = None, identify: str | bool = False, normalize: bool = False, pad: int = 2, indent: int = 2, normalize_functions: Union[str, bool, NoneType] = None, unsupported_level: sqlglot.errors.ErrorLevel = <ErrorLevel.WARN: 'WARN'>, max_unsupported: int = 3, leading_comma: bool = False, max_text_width: int = 80, comments: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None) View Source

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

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

    648    def generate(self, expression: exp.Expression, copy: bool = True) -> str:
    649        """
    650        Generates the SQL string corresponding to the given syntax tree.
    651
    652        Args:
    653            expression: The syntax tree.
    654            copy: Whether to copy the expression. The generator performs mutations so
    655                it is safer to copy.
    656
    657        Returns:
    658            The SQL string corresponding to `expression`.
    659        """
    660        if copy:
    661            expression = expression.copy()
    662
    663        expression = self.preprocess(expression)
    664
    665        self.unsupported_messages = []
    666        sql = self.sql(expression).strip()
    667
    668        if self.pretty:
    669            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
    670
    671        if self.unsupported_level == ErrorLevel.IGNORE:
    672            return sql
    673
    674        if self.unsupported_level == ErrorLevel.WARN:
    675            for msg in self.unsupported_messages:
    676                logger.warning(msg)
    677        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
    678            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
    679
    680        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

    682    def preprocess(self, expression: exp.Expression) -> exp.Expression:
    683        """Apply generic preprocessing transformations to a given expression."""
    684        if (
    685            not expression.parent
    686            and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES
    687            and any(node.parent is not expression for node in expression.find_all(exp.With))
    688        ):
    689            from sqlglot.transforms import move_ctes_to_top_level
    690
    691            expression = move_ctes_to_top_level(expression)
    692
    693        if self.ENSURE_BOOLS:
    694            from sqlglot.transforms import ensure_bools
    695
    696            expression = ensure_bools(expression)
    697
    698        return expression

Apply generic preprocessing transformations to a given expression.

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

    700    def unsupported(self, message: str) -> None:
    701        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    702            raise UnsupportedError(message)
    703        self.unsupported_messages.append(message)

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

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

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

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

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

    711    def pad_comment(self, comment: str) -> str:
    712        comment = " " + comment if comment[0].strip() else comment
    713        comment = comment + " " if comment[-1].strip() else comment
    714        return comment

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

    716    def maybe_comment(
    717        self,
    718        sql: str,
    719        expression: t.Optional[exp.Expression] = None,
    720        comments: t.Optional[t.List[str]] = None,
    721        separated: bool = False,
    722    ) -> str:
    723        comments = (
    724            ((expression and expression.comments) if comments is None else comments)  # type: ignore
    725            if self.comments
    726            else None
    727        )
    728
    729        if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
    730            return sql
    731
    732        comments_sql = " ".join(
    733            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
    734        )
    735
    736        if not comments_sql:
    737            return sql
    738
    739        comments_sql = self._replace_line_breaks(comments_sql)
    740
    741        if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS):
    742            return (
    743                f"{self.sep()}{comments_sql}{sql}"
    744                if not sql or sql[0].isspace()
    745                else f"{comments_sql}{self.sep()}{sql}"
    746            )
    747
    748        return f"{sql} {comments_sql}"

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

    750    def wrap(self, expression: exp.Expression | str) -> str:
    751        this_sql = (
    752            self.sql(expression)
    753            if isinstance(expression, exp.UNWRAPPED_QUERIES)
    754            else self.sql(expression, "this")
    755        )
    756        if not this_sql:
    757            return "()"
    758
    759        this_sql = self.indent(this_sql, level=1, pad=0)
    760        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"

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

    762    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    763        original = self.identify
    764        self.identify = False
    765        result = func(*args, **kwargs)
    766        self.identify = original
    767        return result

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

    769    def normalize_func(self, name: str) -> str:
    770        if self.normalize_functions == "upper" or self.normalize_functions is True:
    771            return name.upper()
    772        if self.normalize_functions == "lower":
    773            return name.lower()
    774        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

    776    def indent(
    777        self,
    778        sql: str,
    779        level: int = 0,
    780        pad: t.Optional[int] = None,
    781        skip_first: bool = False,
    782        skip_last: bool = False,
    783    ) -> str:
    784        if not self.pretty or not sql:
    785            return sql
    786
    787        pad = self.pad if pad is None else pad
    788        lines = sql.split("\n")
    789
    790        return "\n".join(
    791            (
    792                line
    793                if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
    794                else f"{' ' * (level * self._indent + pad)}{line}"
    795            )
    796            for i, line in enumerate(lines)
    797        )

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

    799    def sql(
    800        self,
    801        expression: t.Optional[str | exp.Expression],
    802        key: t.Optional[str] = None,
    803        comment: bool = True,
    804    ) -> str:
    805        if not expression:
    806            return ""
    807
    808        if isinstance(expression, str):
    809            return expression
    810
    811        if key:
    812            value = expression.args.get(key)
    813            if value:
    814                return self.sql(value)
    815            return ""
    816
    817        transform = self.TRANSFORMS.get(expression.__class__)
    818
    819        if callable(transform):
    820            sql = transform(self, expression)
    821        elif isinstance(expression, exp.Expression):
    822            exp_handler_name = f"{expression.key}_sql"
    823
    824            if hasattr(self, exp_handler_name):
    825                sql = getattr(self, exp_handler_name)(expression)
    826            elif isinstance(expression, exp.Func):
    827                sql = self.function_fallback_sql(expression)
    828            elif isinstance(expression, exp.Property):
    829                sql = self.property_sql(expression)
    830            else:
    831                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
    832        else:
    833            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
    834
    835        return self.maybe_comment(sql, expression) if self.comments and comment else sql

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

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

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

    842    def cache_sql(self, expression: exp.Cache) -> str:
    843        lazy = " LAZY" if expression.args.get("lazy") else ""
    844        table = self.sql(expression, "this")
    845        options = expression.args.get("options")
    846        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
    847        sql = self.sql(expression, "expression")
    848        sql = f" AS{self.sep()}{sql}" if sql else ""
    849        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
    850        return self.prepend_ctes(expression, sql)

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

    852    def characterset_sql(self, expression: exp.CharacterSet) -> str:
    853        if isinstance(expression.parent, exp.Cast):
    854            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
    855        default = "DEFAULT " if expression.args.get("default") else ""
    856        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"

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

    858    def column_parts(self, expression: exp.Column) -> str:
    859        return ".".join(
    860            self.sql(part)
    861            for part in (
    862                expression.args.get("catalog"),
    863                expression.args.get("db"),
    864                expression.args.get("table"),
    865                expression.args.get("this"),
    866            )
    867            if part
    868        )

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

    870    def column_sql(self, expression: exp.Column) -> str:
    871        join_mark = " (+)" if expression.args.get("join_mark") else ""
    872
    873        if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS:
    874            join_mark = ""
    875            self.unsupported("Outer join syntax using the (+) operator is not supported.")
    876
    877        return f"{self.column_parts(expression)}{join_mark}"

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

    879    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    880        this = self.sql(expression, "this")
    881        this = f" {this}" if this else ""
    882        position = self.sql(expression, "position")
    883        return f"{position}{this}"

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

    885    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
    886        column = self.sql(expression, "this")
    887        kind = self.sql(expression, "kind")
    888        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
    889        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
    890        kind = f"{sep}{kind}" if kind else ""
    891        constraints = f" {constraints}" if constraints else ""
    892        position = self.sql(expression, "position")
    893        position = f" {position}" if position else ""
    894
    895        if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:
    896            kind = ""
    897
    898        return f"{exists}{column}{kind}{constraints}{position}"

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

    900    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    901        this = self.sql(expression, "this")
    902        kind_sql = self.sql(expression, "kind").strip()
    903        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

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

    905    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
    906        this = self.sql(expression, "this")
    907        if expression.args.get("not_null"):
    908            persisted = " PERSISTED NOT NULL"
    909        elif expression.args.get("persisted"):
    910            persisted = " PERSISTED"
    911        else:
    912            persisted = ""
    913        return f"AS {this}{persisted}"

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

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

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

    918    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
    919        if isinstance(expression.this, list):
    920            this = self.wrap(self.expressions(expression, key="this", flat=True))
    921        else:
    922            this = self.sql(expression, "this")
    923
    924        return f"COMPRESS {this}"

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

    926    def generatedasidentitycolumnconstraint_sql(
    927        self, expression: exp.GeneratedAsIdentityColumnConstraint
    928    ) -> str:
    929        this = ""
    930        if expression.this is not None:
    931            on_null = " ON NULL" if expression.args.get("on_null") else ""
    932            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
    933
    934        start = expression.args.get("start")
    935        start = f"START WITH {start}" if start else ""
    936        increment = expression.args.get("increment")
    937        increment = f" INCREMENT BY {increment}" if increment else ""
    938        minvalue = expression.args.get("minvalue")
    939        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    940        maxvalue = expression.args.get("maxvalue")
    941        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    942        cycle = expression.args.get("cycle")
    943        cycle_sql = ""
    944
    945        if cycle is not None:
    946            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
    947            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
    948
    949        sequence_opts = ""
    950        if start or increment or cycle_sql:
    951            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
    952            sequence_opts = f" ({sequence_opts.strip()})"
    953
    954        expr = self.sql(expression, "expression")
    955        expr = f"({expr})" if expr else "IDENTITY"
    956
    957        return f"GENERATED{this} AS {expr}{sequence_opts}"

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

    959    def generatedasrowcolumnconstraint_sql(
    960        self, expression: exp.GeneratedAsRowColumnConstraint
    961    ) -> str:
    962        start = "START" if expression.args.get("start") else "END"
    963        hidden = " HIDDEN" if expression.args.get("hidden") else ""
    964        return f"GENERATED ALWAYS AS ROW {start}{hidden}"

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

    966    def periodforsystemtimeconstraint_sql(
    967        self, expression: exp.PeriodForSystemTimeConstraint
    968    ) -> str:
    969        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

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

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

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

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

    977    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    978        desc = expression.args.get("desc")
    979        if desc is not None:
    980            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    981        return "PRIMARY KEY"

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

    983    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    984        this = self.sql(expression, "this")
    985        this = f" {this}" if this else ""
    986        index_type = expression.args.get("index_type")
    987        index_type = f" USING {index_type}" if index_type else ""
    988        on_conflict = self.sql(expression, "on_conflict")
    989        on_conflict = f" {on_conflict}" if on_conflict else ""
    990        nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else ""
    991        return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}"

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

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

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

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

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

    1100    def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str:
    1101        start = self.sql(expression, "start")
    1102        start = f"START WITH {start}" if start else ""
    1103        increment = self.sql(expression, "increment")
    1104        increment = f" INCREMENT BY {increment}" if increment else ""
    1105        minvalue = self.sql(expression, "minvalue")
    1106        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    1107        maxvalue = self.sql(expression, "maxvalue")
    1108        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    1109        owned = self.sql(expression, "owned")
    1110        owned = f" OWNED BY {owned}" if owned else ""
    1111
    1112        cache = expression.args.get("cache")
    1113        if cache is None:
    1114            cache_str = ""
    1115        elif cache is True:
    1116            cache_str = " CACHE"
    1117        else:
    1118            cache_str = f" CACHE {cache}"
    1119
    1120        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1121        options = f" {options}" if options else ""
    1122
    1123        return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()

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

    1125    def clone_sql(self, expression: exp.Clone) -> str:
    1126        this = self.sql(expression, "this")
    1127        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    1128        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
    1129        return f"{shallow}{keyword} {this}"

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

    1131    def describe_sql(self, expression: exp.Describe) -> str:
    1132        style = expression.args.get("style")
    1133        style = f" {style}" if style else ""
    1134        partition = self.sql(expression, "partition")
    1135        partition = f" {partition}" if partition else ""
    1136        return f"DESCRIBE{style} {self.sql(expression, 'this')}{partition}"

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

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

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

    1142    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    1143        with_ = self.sql(expression, "with")
    1144        if with_:
    1145            sql = f"{with_}{self.sep()}{sql}"
    1146        return sql

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

    1148    def with_sql(self, expression: exp.With) -> str:
    1149        sql = self.expressions(expression, flat=True)
    1150        recursive = (
    1151            "RECURSIVE "
    1152            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
    1153            else ""
    1154        )
    1155
    1156        return f"WITH {recursive}{sql}"

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

    1158    def cte_sql(self, expression: exp.CTE) -> str:
    1159        alias = self.sql(expression, "alias")
    1160
    1161        materialized = expression.args.get("materialized")
    1162        if materialized is False:
    1163            materialized = "NOT MATERIALIZED "
    1164        elif materialized:
    1165            materialized = "MATERIALIZED "
    1166
    1167        return f"{alias} AS {materialized or ''}{self.wrap(expression)}"

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

    1169    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    1170        alias = self.sql(expression, "this")
    1171        columns = self.expressions(expression, key="columns", flat=True)
    1172        columns = f"({columns})" if columns else ""
    1173
    1174        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
    1175            columns = ""
    1176            self.unsupported("Named columns are not supported in table alias.")
    1177
    1178        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
    1179            alias = self._next_name()
    1180
    1181        return f"{alias}{columns}"

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

    1183    def bitstring_sql(self, expression: exp.BitString) -> str:
    1184        this = self.sql(expression, "this")
    1185        if self.dialect.BIT_START:
    1186            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    1187        return f"{int(this, 2)}"

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

    1189    def hexstring_sql(self, expression: exp.HexString) -> str:
    1190        this = self.sql(expression, "this")
    1191        if self.dialect.HEX_START:
    1192            return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
    1193        return f"{int(this, 16)}"

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

    1195    def bytestring_sql(self, expression: exp.ByteString) -> str:
    1196        this = self.sql(expression, "this")
    1197        if self.dialect.BYTE_START:
    1198            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    1199        return this

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

    1201    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
    1202        this = self.sql(expression, "this")
    1203        escape = expression.args.get("escape")
    1204
    1205        if self.dialect.UNICODE_START:
    1206            escape_substitute = r"\\\1"
    1207            left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END
    1208        else:
    1209            escape_substitute = r"\\u\1"
    1210            left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END
    1211
    1212        if escape:
    1213            escape_pattern = re.compile(rf"{escape.name}(\d+)")
    1214            escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else ""
    1215        else:
    1216            escape_pattern = ESCAPED_UNICODE_RE
    1217            escape_sql = ""
    1218
    1219        if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE):
    1220            this = escape_pattern.sub(escape_substitute, this)
    1221
    1222        return f"{left_quote}{this}{right_quote}{escape_sql}"

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

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

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

    1228    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    1229        this = self.sql(expression, "this")
    1230        specifier = self.sql(expression, "expression")
    1231        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    1232        return f"{this}{specifier}"

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

    1234    def datatype_sql(self, expression: exp.DataType) -> str:
    1235        nested = ""
    1236        values = ""
    1237        interior = self.expressions(expression, flat=True)
    1238
    1239        type_value = expression.this
    1240        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
    1241            type_sql = self.sql(expression, "kind")
    1242        elif type_value != exp.DataType.Type.NULLABLE or self.SUPPORTS_NULLABLE_TYPES:
    1243            type_sql = (
    1244                self.TYPE_MAPPING.get(type_value, type_value.value)
    1245                if isinstance(type_value, exp.DataType.Type)
    1246                else type_value
    1247            )
    1248        else:
    1249            return interior
    1250
    1251        if interior:
    1252            if expression.args.get("nested"):
    1253                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    1254                if expression.args.get("values") is not None:
    1255                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    1256                    values = self.expressions(expression, key="values", flat=True)
    1257                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    1258            elif type_value == exp.DataType.Type.INTERVAL:
    1259                nested = f" {interior}"
    1260            else:
    1261                nested = f"({interior})"
    1262
    1263        type_sql = f"{type_sql}{nested}{values}"
    1264        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
    1265            exp.DataType.Type.TIMETZ,
    1266            exp.DataType.Type.TIMESTAMPTZ,
    1267        ):
    1268            type_sql = f"{type_sql} WITH TIME ZONE"
    1269
    1270        return type_sql

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

    1272    def directory_sql(self, expression: exp.Directory) -> str:
    1273        local = "LOCAL " if expression.args.get("local") else ""
    1274        row_format = self.sql(expression, "row_format")
    1275        row_format = f" {row_format}" if row_format else ""
    1276        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

    1278    def delete_sql(self, expression: exp.Delete) -> str:
    1279        this = self.sql(expression, "this")
    1280        this = f" FROM {this}" if this else ""
    1281        using = self.sql(expression, "using")
    1282        using = f" USING {using}" if using else ""
    1283        where = self.sql(expression, "where")
    1284        returning = self.sql(expression, "returning")
    1285        limit = self.sql(expression, "limit")
    1286        tables = self.expressions(expression, key="tables")
    1287        tables = f" {tables}" if tables else ""
    1288        if self.RETURNING_END:
    1289            expression_sql = f"{this}{using}{where}{returning}{limit}"
    1290        else:
    1291            expression_sql = f"{returning}{this}{using}{where}{limit}"
    1292        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

    1294    def drop_sql(self, expression: exp.Drop) -> str:
    1295        this = self.sql(expression, "this")
    1296        expressions = self.expressions(expression, flat=True)
    1297        expressions = f" ({expressions})" if expressions else ""
    1298        kind = expression.args["kind"]
    1299        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
    1300        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    1301        concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else ""
    1302        on_cluster = self.sql(expression, "cluster")
    1303        on_cluster = f" {on_cluster}" if on_cluster else ""
    1304        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1305        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    1306        cascade = " CASCADE" if expression.args.get("cascade") else ""
    1307        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    1308        purge = " PURGE" if expression.args.get("purge") else ""
    1309        return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}"

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

    1311    def set_operation(self, expression: exp.SetOperation) -> str:
    1312        op_type = type(expression)
    1313        op_name = op_type.key.upper()
    1314
    1315        distinct = expression.args.get("distinct")
    1316        if (
    1317            distinct is False
    1318            and op_type in (exp.Except, exp.Intersect)
    1319            and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
    1320        ):
    1321            self.unsupported(f"{op_name} ALL is not supported")
    1322
    1323        default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type]
    1324
    1325        if distinct is None:
    1326            distinct = default_distinct
    1327            if distinct is None:
    1328                self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified")
    1329
    1330        if distinct is default_distinct:
    1331            kind = ""
    1332        else:
    1333            kind = " DISTINCT" if distinct else " ALL"
    1334
    1335        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1336        return f"{op_name}{kind}{by_name}"

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

    1338    def set_operations(self, expression: exp.SetOperation) -> str:
    1339        if not self.SET_OP_MODIFIERS:
    1340            limit = expression.args.get("limit")
    1341            order = expression.args.get("order")
    1342
    1343            if limit or order:
    1344                select = exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
    1345
    1346                if limit:
    1347                    select = select.limit(limit.pop(), copy=False)
    1348                if order:
    1349                    select = select.order_by(order.pop(), copy=False)
    1350                return self.sql(select)
    1351
    1352        sqls: t.List[str] = []
    1353        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    1354
    1355        while stack:
    1356            node = stack.pop()
    1357
    1358            if isinstance(node, exp.SetOperation):
    1359                stack.append(node.expression)
    1360                stack.append(
    1361                    self.maybe_comment(
    1362                        self.set_operation(node), comments=node.comments, separated=True
    1363                    )
    1364                )
    1365                stack.append(node.this)
    1366            else:
    1367                sqls.append(self.sql(node))
    1368
    1369        this = self.sep().join(sqls)
    1370        this = self.query_modifiers(expression, this)
    1371        return self.prepend_ctes(expression, this)

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

    1373    def fetch_sql(self, expression: exp.Fetch) -> str:
    1374        direction = expression.args.get("direction")
    1375        direction = f" {direction}" if direction else ""
    1376        count = self.sql(expression, "count")
    1377        count = f" {count}" if count else ""
    1378        if expression.args.get("percent"):
    1379            count = f"{count} PERCENT"
    1380        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    1381        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"

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

    1383    def filter_sql(self, expression: exp.Filter) -> str:
    1384        if self.AGGREGATE_FILTER_SUPPORTED:
    1385            this = self.sql(expression, "this")
    1386            where = self.sql(expression, "expression").strip()
    1387            return f"{this} FILTER({where})"
    1388
    1389        agg = expression.this
    1390        agg_arg = agg.this
    1391        cond = expression.expression.this
    1392        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1393        return self.sql(agg)

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

    1395    def hint_sql(self, expression: exp.Hint) -> str:
    1396        if not self.QUERY_HINTS:
    1397            self.unsupported("Hints are not supported")
    1398            return ""
    1399
    1400        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

    1402    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
    1403        using = self.sql(expression, "using")
    1404        using = f" USING {using}" if using else ""
    1405        columns = self.expressions(expression, key="columns", flat=True)
    1406        columns = f"({columns})" if columns else ""
    1407        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1408        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1409        where = self.sql(expression, "where")
    1410        include = self.expressions(expression, key="include", flat=True)
    1411        if include:
    1412            include = f" INCLUDE ({include})"
    1413        with_storage = self.expressions(expression, key="with_storage", flat=True)
    1414        with_storage = f" WITH ({with_storage})" if with_storage else ""
    1415        tablespace = self.sql(expression, "tablespace")
    1416        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
    1417        on = self.sql(expression, "on")
    1418        on = f" ON {on}" if on else ""
    1419
    1420        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"

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

    1422    def index_sql(self, expression: exp.Index) -> str:
    1423        unique = "UNIQUE " if expression.args.get("unique") else ""
    1424        primary = "PRIMARY " if expression.args.get("primary") else ""
    1425        amp = "AMP " if expression.args.get("amp") else ""
    1426        name = self.sql(expression, "this")
    1427        name = f"{name} " if name else ""
    1428        table = self.sql(expression, "table")
    1429        table = f"{self.INDEX_ON} {table}" if table else ""
    1430
    1431        index = "INDEX " if not table else ""
    1432
    1433        params = self.sql(expression, "params")
    1434        return f"{unique}{primary}{amp}{index}{name}{table}{params}"

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

    1436    def identifier_sql(self, expression: exp.Identifier) -> str:
    1437        text = expression.name
    1438        lower = text.lower()
    1439        text = lower if self.normalize and not expression.quoted else text
    1440        text = text.replace(self._identifier_end, self._escaped_identifier_end)
    1441        if (
    1442            expression.quoted
    1443            or self.dialect.can_identify(text, self.identify)
    1444            or lower in self.RESERVED_KEYWORDS
    1445            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1446        ):
    1447            text = f"{self._identifier_start}{text}{self._identifier_end}"
    1448        return text

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

    1450    def hex_sql(self, expression: exp.Hex) -> str:
    1451        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1452        if self.dialect.HEX_LOWERCASE:
    1453            text = self.func("LOWER", text)
    1454
    1455        return text

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

    1457    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
    1458        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1459        if not self.dialect.HEX_LOWERCASE:
    1460            text = self.func("LOWER", text)
    1461        return text

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

    1463    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1464        input_format = self.sql(expression, "input_format")
    1465        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1466        output_format = self.sql(expression, "output_format")
    1467        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1468        return self.sep().join((input_format, output_format))

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

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

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

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

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

    1477    def properties_sql(self, expression: exp.Properties) -> str:
    1478        root_properties = []
    1479        with_properties = []
    1480
    1481        for p in expression.expressions:
    1482            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1483            if p_loc == exp.Properties.Location.POST_WITH:
    1484                with_properties.append(p)
    1485            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1486                root_properties.append(p)
    1487
    1488        root_props = self.root_properties(exp.Properties(expressions=root_properties))
    1489        with_props = self.with_properties(exp.Properties(expressions=with_properties))
    1490
    1491        if root_props and with_props and not self.pretty:
    1492            with_props = " " + with_props
    1493
    1494        return root_props + with_props

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

    1496    def root_properties(self, properties: exp.Properties) -> str:
    1497        if properties.expressions:
    1498            return self.expressions(properties, indent=False, sep=" ")
    1499        return ""

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

    1501    def properties(
    1502        self,
    1503        properties: exp.Properties,
    1504        prefix: str = "",
    1505        sep: str = ", ",
    1506        suffix: str = "",
    1507        wrapped: bool = True,
    1508    ) -> str:
    1509        if properties.expressions:
    1510            expressions = self.expressions(properties, sep=sep, indent=False)
    1511            if expressions:
    1512                expressions = self.wrap(expressions) if wrapped else expressions
    1513                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1514        return ""

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

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

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

    1519    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1520        properties_locs = defaultdict(list)
    1521        for p in properties.expressions:
    1522            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1523            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1524                properties_locs[p_loc].append(p)
    1525            else:
    1526                self.unsupported(f"Unsupported property {p.key}")
    1527
    1528        return properties_locs

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

    1530    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1531        if isinstance(expression.this, exp.Dot):
    1532            return self.sql(expression, "this")
    1533        return f"'{expression.name}'" if string_key else expression.name

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

    1535    def property_sql(self, expression: exp.Property) -> str:
    1536        property_cls = expression.__class__
    1537        if property_cls == exp.Property:
    1538            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1539
    1540        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1541        if not property_name:
    1542            self.unsupported(f"Unsupported property {expression.key}")
    1543
    1544        return f"{property_name}={self.sql(expression, 'this')}"

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

    1546    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1547        if self.SUPPORTS_CREATE_TABLE_LIKE:
    1548            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1549            options = f" {options}" if options else ""
    1550
    1551            like = f"LIKE {self.sql(expression, 'this')}{options}"
    1552            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
    1553                like = f"({like})"
    1554
    1555            return like
    1556
    1557        if expression.expressions:
    1558            self.unsupported("Transpilation of LIKE property options is unsupported")
    1559
    1560        select = exp.select("*").from_(expression.this).limit(0)
    1561        return f"AS {self.sql(select)}"

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

    1563    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1564        no = "NO " if expression.args.get("no") else ""
    1565        protection = " PROTECTION" if expression.args.get("protection") else ""
    1566        return f"{no}FALLBACK{protection}"

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

    1568    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1569        no = "NO " if expression.args.get("no") else ""
    1570        local = expression.args.get("local")
    1571        local = f"{local} " if local else ""
    1572        dual = "DUAL " if expression.args.get("dual") else ""
    1573        before = "BEFORE " if expression.args.get("before") else ""
    1574        after = "AFTER " if expression.args.get("after") else ""
    1575        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1577    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1578        freespace = self.sql(expression, "this")
    1579        percent = " PERCENT" if expression.args.get("percent") else ""
    1580        return f"FREESPACE={freespace}{percent}"

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

    1582    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1583        if expression.args.get("default"):
    1584            property = "DEFAULT"
    1585        elif expression.args.get("on"):
    1586            property = "ON"
    1587        else:
    1588            property = "OFF"
    1589        return f"CHECKSUM={property}"

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

    1591    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1592        if expression.args.get("no"):
    1593            return "NO MERGEBLOCKRATIO"
    1594        if expression.args.get("default"):
    1595            return "DEFAULT MERGEBLOCKRATIO"
    1596
    1597        percent = " PERCENT" if expression.args.get("percent") else ""
    1598        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1600    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1601        default = expression.args.get("default")
    1602        minimum = expression.args.get("minimum")
    1603        maximum = expression.args.get("maximum")
    1604        if default or minimum or maximum:
    1605            if default:
    1606                prop = "DEFAULT"
    1607            elif minimum:
    1608                prop = "MINIMUM"
    1609            else:
    1610                prop = "MAXIMUM"
    1611            return f"{prop} DATABLOCKSIZE"
    1612        units = expression.args.get("units")
    1613        units = f" {units}" if units else ""
    1614        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1616    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1617        autotemp = expression.args.get("autotemp")
    1618        always = expression.args.get("always")
    1619        default = expression.args.get("default")
    1620        manual = expression.args.get("manual")
    1621        never = expression.args.get("never")
    1622
    1623        if autotemp is not None:
    1624            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1625        elif always:
    1626            prop = "ALWAYS"
    1627        elif default:
    1628            prop = "DEFAULT"
    1629        elif manual:
    1630            prop = "MANUAL"
    1631        elif never:
    1632            prop = "NEVER"
    1633        return f"BLOCKCOMPRESSION={prop}"

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

    1635    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1636        no = expression.args.get("no")
    1637        no = " NO" if no else ""
    1638        concurrent = expression.args.get("concurrent")
    1639        concurrent = " CONCURRENT" if concurrent else ""
    1640        target = self.sql(expression, "target")
    1641        target = f" {target}" if target else ""
    1642        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"

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

    1644    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1645        if isinstance(expression.this, list):
    1646            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1647        if expression.this:
    1648            modulus = self.sql(expression, "this")
    1649            remainder = self.sql(expression, "expression")
    1650            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1651
    1652        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1653        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1654        return f"FROM ({from_expressions}) TO ({to_expressions})"

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

    1656    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1657        this = self.sql(expression, "this")
    1658
    1659        for_values_or_default = expression.expression
    1660        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1661            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1662        else:
    1663            for_values_or_default = " DEFAULT"
    1664
    1665        return f"PARTITION OF {this}{for_values_or_default}"

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

    1667    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1668        kind = expression.args.get("kind")
    1669        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1670        for_or_in = expression.args.get("for_or_in")
    1671        for_or_in = f" {for_or_in}" if for_or_in else ""
    1672        lock_type = expression.args.get("lock_type")
    1673        override = " OVERRIDE" if expression.args.get("override") else ""
    1674        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"

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

    1676    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1677        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1678        statistics = expression.args.get("statistics")
    1679        statistics_sql = ""
    1680        if statistics is not None:
    1681            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1682        return f"{data_sql}{statistics_sql}"

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

    1684    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1685        this = self.sql(expression, "this")
    1686        this = f"HISTORY_TABLE={this}" if this else ""
    1687        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
    1688        data_consistency = (
    1689            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
    1690        )
    1691        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    1692        retention_period = (
    1693            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
    1694        )
    1695
    1696        if this:
    1697            on_sql = self.func("ON", this, data_consistency, retention_period)
    1698        else:
    1699            on_sql = "ON" if expression.args.get("on") else "OFF"
    1700
    1701        sql = f"SYSTEM_VERSIONING={on_sql}"
    1702
    1703        return f"WITH({sql})" if expression.args.get("with") else sql

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

    1705    def insert_sql(self, expression: exp.Insert) -> str:
    1706        hint = self.sql(expression, "hint")
    1707        overwrite = expression.args.get("overwrite")
    1708
    1709        if isinstance(expression.this, exp.Directory):
    1710            this = " OVERWRITE" if overwrite else " INTO"
    1711        else:
    1712            this = self.INSERT_OVERWRITE if overwrite else " INTO"
    1713
    1714        stored = self.sql(expression, "stored")
    1715        stored = f" {stored}" if stored else ""
    1716        alternative = expression.args.get("alternative")
    1717        alternative = f" OR {alternative}" if alternative else ""
    1718        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1719        is_function = expression.args.get("is_function")
    1720        if is_function:
    1721            this = f"{this} FUNCTION"
    1722        this = f"{this} {self.sql(expression, 'this')}"
    1723
    1724        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1725        where = self.sql(expression, "where")
    1726        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1727        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1728        on_conflict = self.sql(expression, "conflict")
    1729        on_conflict = f" {on_conflict}" if on_conflict else ""
    1730        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1731        returning = self.sql(expression, "returning")
    1732
    1733        if self.RETURNING_END:
    1734            expression_sql = f"{expression_sql}{on_conflict}{returning}"
    1735        else:
    1736            expression_sql = f"{returning}{expression_sql}{on_conflict}"
    1737
    1738        partition_by = self.sql(expression, "partition")
    1739        partition_by = f" {partition_by}" if partition_by else ""
    1740        settings = self.sql(expression, "settings")
    1741        settings = f" {settings}" if settings else ""
    1742
    1743        source = self.sql(expression, "source")
    1744        source = f"TABLE {source}" if source else ""
    1745
    1746        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}"
    1747        return self.prepend_ctes(expression, sql)

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

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

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

    1752    def kill_sql(self, expression: exp.Kill) -> str:
    1753        kind = self.sql(expression, "kind")
    1754        kind = f" {kind}" if kind else ""
    1755        this = self.sql(expression, "this")
    1756        this = f" {this}" if this else ""
    1757        return f"KILL{kind}{this}"

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

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

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

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

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

    1765    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1766        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1767
    1768        constraint = self.sql(expression, "constraint")
    1769        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
    1770
    1771        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
    1772        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
    1773        action = self.sql(expression, "action")
    1774
    1775        expressions = self.expressions(expression, flat=True)
    1776        if expressions:
    1777            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1778            expressions = f" {set_keyword}{expressions}"
    1779
    1780        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}"

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

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

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

    1785    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1786        fields = self.sql(expression, "fields")
    1787        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1788        escaped = self.sql(expression, "escaped")
    1789        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1790        items = self.sql(expression, "collection_items")
    1791        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1792        keys = self.sql(expression, "map_keys")
    1793        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1794        lines = self.sql(expression, "lines")
    1795        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1796        null = self.sql(expression, "null")
    1797        null = f" NULL DEFINED AS {null}" if null else ""
    1798        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1803    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1804        this = f"{self.sql(expression, 'this')} INDEX"
    1805        target = self.sql(expression, "target")
    1806        target = f" FOR {target}" if target else ""
    1807        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1809    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1810        this = self.sql(expression, "this")
    1811        kind = self.sql(expression, "kind")
    1812        expr = self.sql(expression, "expression")
    1813        return f"{this} ({kind} => {expr})"

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

    1815    def table_parts(self, expression: exp.Table) -> str:
    1816        return ".".join(
    1817            self.sql(part)
    1818            for part in (
    1819                expression.args.get("catalog"),
    1820                expression.args.get("db"),
    1821                expression.args.get("this"),
    1822            )
    1823            if part is not None
    1824        )

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

    1826    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1827        table = self.table_parts(expression)
    1828        only = "ONLY " if expression.args.get("only") else ""
    1829        partition = self.sql(expression, "partition")
    1830        partition = f" {partition}" if partition else ""
    1831        version = self.sql(expression, "version")
    1832        version = f" {version}" if version else ""
    1833        alias = self.sql(expression, "alias")
    1834        alias = f"{sep}{alias}" if alias else ""
    1835
    1836        sample = self.sql(expression, "sample")
    1837        if self.dialect.ALIAS_POST_TABLESAMPLE:
    1838            sample_pre_alias = sample
    1839            sample_post_alias = ""
    1840        else:
    1841            sample_pre_alias = ""
    1842            sample_post_alias = sample
    1843
    1844        hints = self.expressions(expression, key="hints", sep=" ")
    1845        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1846        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    1847        joins = self.indent(
    1848            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    1849        )
    1850        laterals = self.expressions(expression, key="laterals", sep="")
    1851
    1852        file_format = self.sql(expression, "format")
    1853        if file_format:
    1854            pattern = self.sql(expression, "pattern")
    1855            pattern = f", PATTERN => {pattern}" if pattern else ""
    1856            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    1857
    1858        ordinality = expression.args.get("ordinality") or ""
    1859        if ordinality:
    1860            ordinality = f" WITH ORDINALITY{alias}"
    1861            alias = ""
    1862
    1863        when = self.sql(expression, "when")
    1864        if when:
    1865            table = f"{table} {when}"
    1866
    1867        changes = self.sql(expression, "changes")
    1868        changes = f" {changes}" if changes else ""
    1869
    1870        rows_from = self.expressions(expression, key="rows_from")
    1871        if rows_from:
    1872            table = f"ROWS FROM {self.wrap(rows_from)}"
    1873
    1874        return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}"

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

    1876    def tablesample_sql(
    1877        self,
    1878        expression: exp.TableSample,
    1879        tablesample_keyword: t.Optional[str] = None,
    1880    ) -> str:
    1881        method = self.sql(expression, "method")
    1882        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1883        numerator = self.sql(expression, "bucket_numerator")
    1884        denominator = self.sql(expression, "bucket_denominator")
    1885        field = self.sql(expression, "bucket_field")
    1886        field = f" ON {field}" if field else ""
    1887        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1888        seed = self.sql(expression, "seed")
    1889        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
    1890
    1891        size = self.sql(expression, "size")
    1892        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
    1893            size = f"{size} ROWS"
    1894
    1895        percent = self.sql(expression, "percent")
    1896        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
    1897            percent = f"{percent} PERCENT"
    1898
    1899        expr = f"{bucket}{percent}{size}"
    1900        if self.TABLESAMPLE_REQUIRES_PARENS:
    1901            expr = f"({expr})"
    1902
    1903        return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"

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

    1905    def pivot_sql(self, expression: exp.Pivot) -> str:
    1906        expressions = self.expressions(expression, flat=True)
    1907
    1908        if expression.this:
    1909            this = self.sql(expression, "this")
    1910            if not expressions:
    1911                return f"UNPIVOT {this}"
    1912
    1913            on = f"{self.seg('ON')} {expressions}"
    1914            using = self.expressions(expression, key="using", flat=True)
    1915            using = f"{self.seg('USING')} {using}" if using else ""
    1916            group = self.sql(expression, "group")
    1917            return f"PIVOT {this}{on}{using}{group}"
    1918
    1919        alias = self.sql(expression, "alias")
    1920        alias = f" AS {alias}" if alias else ""
    1921        direction = self.seg("UNPIVOT" if expression.unpivot else "PIVOT")
    1922
    1923        field = self.sql(expression, "field")
    1924        if field and isinstance(expression.args.get("field"), exp.PivotAny):
    1925            field = f"IN ({field})"
    1926
    1927        include_nulls = expression.args.get("include_nulls")
    1928        if include_nulls is not None:
    1929            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    1930        else:
    1931            nulls = ""
    1932
    1933        default_on_null = self.sql(expression, "default_on_null")
    1934        default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else ""
    1935        return f"{direction}{nulls}({expressions} FOR {field}{default_on_null}){alias}"

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

    1937    def version_sql(self, expression: exp.Version) -> str:
    1938        this = f"FOR {expression.name}"
    1939        kind = expression.text("kind")
    1940        expr = self.sql(expression, "expression")
    1941        return f"{this} {kind} {expr}"

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

    1943    def tuple_sql(self, expression: exp.Tuple) -> str:
    1944        return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"

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

    1946    def update_sql(self, expression: exp.Update) -> str:
    1947        this = self.sql(expression, "this")
    1948        set_sql = self.expressions(expression, flat=True)
    1949        from_sql = self.sql(expression, "from")
    1950        where_sql = self.sql(expression, "where")
    1951        returning = self.sql(expression, "returning")
    1952        order = self.sql(expression, "order")
    1953        limit = self.sql(expression, "limit")
    1954        if self.RETURNING_END:
    1955            expression_sql = f"{from_sql}{where_sql}{returning}"
    1956        else:
    1957            expression_sql = f"{returning}{from_sql}{where_sql}"
    1958        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    1959        return self.prepend_ctes(expression, sql)

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

    1961    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
    1962        values_as_table = values_as_table and self.VALUES_AS_TABLE
    1963
    1964        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    1965        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
    1966            args = self.expressions(expression)
    1967            alias = self.sql(expression, "alias")
    1968            values = f"VALUES{self.seg('')}{args}"
    1969            values = (
    1970                f"({values})"
    1971                if self.WRAP_DERIVED_VALUES and (alias or isinstance(expression.parent, exp.From))
    1972                else values
    1973            )
    1974            return f"{values} AS {alias}" if alias else values
    1975
    1976        # Converts `VALUES...` expression into a series of select unions.
    1977        alias_node = expression.args.get("alias")
    1978        column_names = alias_node and alias_node.columns
    1979
    1980        selects: t.List[exp.Query] = []
    1981
    1982        for i, tup in enumerate(expression.expressions):
    1983            row = tup.expressions
    1984
    1985            if i == 0 and column_names:
    1986                row = [
    1987                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    1988                ]
    1989
    1990            selects.append(exp.Select(expressions=row))
    1991
    1992        if self.pretty:
    1993            # This may result in poor performance for large-cardinality `VALUES` tables, due to
    1994            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
    1995            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
    1996            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
    1997            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
    1998
    1999        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
    2000        unions = " UNION ALL ".join(self.sql(select) for select in selects)
    2001        return f"({unions}){alias}"

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

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

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

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

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

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

def groupingsets_sql(self, expression: sqlglot.expressions.GroupingSets) -> str: View Source

    2014    def groupingsets_sql(self, expression: exp.GroupingSets) -> str:
    2015        grouping_sets = self.expressions(expression, indent=False)
    2016        return f"GROUPING SETS {self.wrap(grouping_sets)}"

def rollup_sql(self, expression: sqlglot.expressions.Rollup) -> str: View Source

    2018    def rollup_sql(self, expression: exp.Rollup) -> str:
    2019        expressions = self.expressions(expression, indent=False)
    2020        return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP"

def cube_sql(self, expression: sqlglot.expressions.Cube) -> str: View Source

    2022    def cube_sql(self, expression: exp.Cube) -> str:
    2023        expressions = self.expressions(expression, indent=False)
    2024        return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE"

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

    2026    def group_sql(self, expression: exp.Group) -> str:
    2027        group_by_all = expression.args.get("all")
    2028        if group_by_all is True:
    2029            modifier = " ALL"
    2030        elif group_by_all is False:
    2031            modifier = " DISTINCT"
    2032        else:
    2033            modifier = ""
    2034
    2035        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
    2036
    2037        grouping_sets = self.expressions(expression, key="grouping_sets")
    2038        cube = self.expressions(expression, key="cube")
    2039        rollup = self.expressions(expression, key="rollup")
    2040
    2041        groupings = csv(
    2042            self.seg(grouping_sets) if grouping_sets else "",
    2043            self.seg(cube) if cube else "",
    2044            self.seg(rollup) if rollup else "",
    2045            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    2046            sep=self.GROUPINGS_SEP,
    2047        )
    2048
    2049        if (
    2050            expression.expressions
    2051            and groupings
    2052            and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP")
    2053        ):
    2054            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    2055
    2056        return f"{group_by}{groupings}"

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

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

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

    2062    def connect_sql(self, expression: exp.Connect) -> str:
    2063        start = self.sql(expression, "start")
    2064        start = self.seg(f"START WITH {start}") if start else ""
    2065        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
    2066        connect = self.sql(expression, "connect")
    2067        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
    2068        return start + connect

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

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

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

    2073    def join_sql(self, expression: exp.Join) -> str:
    2074        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    2075            side = None
    2076        else:
    2077            side = expression.side
    2078
    2079        op_sql = " ".join(
    2080            op
    2081            for op in (
    2082                expression.method,
    2083                "GLOBAL" if expression.args.get("global") else None,
    2084                side,
    2085                expression.kind,
    2086                expression.hint if self.JOIN_HINTS else None,
    2087            )
    2088            if op
    2089        )
    2090        match_cond = self.sql(expression, "match_condition")
    2091        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
    2092        on_sql = self.sql(expression, "on")
    2093        using = expression.args.get("using")
    2094
    2095        if not on_sql and using:
    2096            on_sql = csv(*(self.sql(column) for column in using))
    2097
    2098        this = expression.this
    2099        this_sql = self.sql(this)
    2100
    2101        if on_sql:
    2102            on_sql = self.indent(on_sql, skip_first=True)
    2103            space = self.seg(" " * self.pad) if self.pretty else " "
    2104            if using:
    2105                on_sql = f"{space}USING ({on_sql})"
    2106            else:
    2107                on_sql = f"{space}ON {on_sql}"
    2108        elif not op_sql:
    2109            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
    2110                return f" {this_sql}"
    2111
    2112            return f", {this_sql}"
    2113
    2114        if op_sql != "STRAIGHT_JOIN":
    2115            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    2116
    2117        return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}"

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

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

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

    2124    def lateral_op(self, expression: exp.Lateral) -> str:
    2125        cross_apply = expression.args.get("cross_apply")
    2126
    2127        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    2128        if cross_apply is True:
    2129            op = "INNER JOIN "
    2130        elif cross_apply is False:
    2131            op = "LEFT JOIN "
    2132        else:
    2133            op = ""
    2134
    2135        return f"{op}LATERAL"

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

    2137    def lateral_sql(self, expression: exp.Lateral) -> str:
    2138        this = self.sql(expression, "this")
    2139
    2140        if expression.args.get("view"):
    2141            alias = expression.args["alias"]
    2142            columns = self.expressions(alias, key="columns", flat=True)
    2143            table = f" {alias.name}" if alias.name else ""
    2144            columns = f" AS {columns}" if columns else ""
    2145            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    2146            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    2147
    2148        alias = self.sql(expression, "alias")
    2149        alias = f" AS {alias}" if alias else ""
    2150        return f"{self.lateral_op(expression)} {this}{alias}"

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

    2152    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    2153        this = self.sql(expression, "this")
    2154
    2155        args = [
    2156            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    2157            for e in (expression.args.get(k) for k in ("offset", "expression"))
    2158            if e
    2159        ]
    2160
    2161        args_sql = ", ".join(self.sql(e) for e in args)
    2162        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
    2163        expressions = self.expressions(expression, flat=True)
    2164        expressions = f" BY {expressions}" if expressions else ""
    2165
    2166        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}"

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

    2168    def offset_sql(self, expression: exp.Offset) -> str:
    2169        this = self.sql(expression, "this")
    2170        value = expression.expression
    2171        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    2172        expressions = self.expressions(expression, flat=True)
    2173        expressions = f" BY {expressions}" if expressions else ""
    2174        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"

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

    2176    def setitem_sql(self, expression: exp.SetItem) -> str:
    2177        kind = self.sql(expression, "kind")
    2178        kind = f"{kind} " if kind else ""
    2179        this = self.sql(expression, "this")
    2180        expressions = self.expressions(expression)
    2181        collate = self.sql(expression, "collate")
    2182        collate = f" COLLATE {collate}" if collate else ""
    2183        global_ = "GLOBAL " if expression.args.get("global") else ""
    2184        return f"{global_}{kind}{this}{expressions}{collate}"

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

    2186    def set_sql(self, expression: exp.Set) -> str:
    2187        expressions = (
    2188            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    2189        )
    2190        tag = " TAG" if expression.args.get("tag") else ""
    2191        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"

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

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

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

    2196    def lock_sql(self, expression: exp.Lock) -> str:
    2197        if not self.LOCKING_READS_SUPPORTED:
    2198            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    2199            return ""
    2200
    2201        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    2202        expressions = self.expressions(expression, flat=True)
    2203        expressions = f" OF {expressions}" if expressions else ""
    2204        wait = expression.args.get("wait")
    2205
    2206        if wait is not None:
    2207            if isinstance(wait, exp.Literal):
    2208                wait = f" WAIT {self.sql(wait)}"
    2209            else:
    2210                wait = " NOWAIT" if wait else " SKIP LOCKED"
    2211
    2212        return f"{lock_type}{expressions}{wait or ''}"

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

    2214    def literal_sql(self, expression: exp.Literal) -> str:
    2215        text = expression.this or ""
    2216        if expression.is_string:
    2217            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    2218        return text

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

    2220    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
    2221        if self.dialect.ESCAPED_SEQUENCES:
    2222            to_escaped = self.dialect.ESCAPED_SEQUENCES
    2223            text = "".join(
    2224                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
    2225            )
    2226
    2227        return self._replace_line_breaks(text).replace(
    2228            self.dialect.QUOTE_END, self._escaped_quote_end
    2229        )

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

    2231    def loaddata_sql(self, expression: exp.LoadData) -> str:
    2232        local = " LOCAL" if expression.args.get("local") else ""
    2233        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    2234        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    2235        this = f" INTO TABLE {self.sql(expression, 'this')}"
    2236        partition = self.sql(expression, "partition")
    2237        partition = f" {partition}" if partition else ""
    2238        input_format = self.sql(expression, "input_format")
    2239        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    2240        serde = self.sql(expression, "serde")
    2241        serde = f" SERDE {serde}" if serde else ""
    2242        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    2244    def null_sql(self, *_) -> str:
    2245        return "NULL"

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

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

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

    2250    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2251        this = self.sql(expression, "this")
    2252        this = f"{this} " if this else this
    2253        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2254        return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat)  # type: ignore

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

    2256    def withfill_sql(self, expression: exp.WithFill) -> str:
    2257        from_sql = self.sql(expression, "from")
    2258        from_sql = f" FROM {from_sql}" if from_sql else ""
    2259        to_sql = self.sql(expression, "to")
    2260        to_sql = f" TO {to_sql}" if to_sql else ""
    2261        step_sql = self.sql(expression, "step")
    2262        step_sql = f" STEP {step_sql}" if step_sql else ""
    2263        interpolated_values = [
    2264            f"{self.sql(named_expression, 'alias')} AS {self.sql(named_expression, 'this')}"
    2265            for named_expression in expression.args.get("interpolate") or []
    2266        ]
    2267        interpolate = (
    2268            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    2269        )
    2270        return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"

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

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

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

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

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

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

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

    2281    def ordered_sql(self, expression: exp.Ordered) -> str:
    2282        desc = expression.args.get("desc")
    2283        asc = not desc
    2284
    2285        nulls_first = expression.args.get("nulls_first")
    2286        nulls_last = not nulls_first
    2287        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
    2288        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
    2289        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
    2290
    2291        this = self.sql(expression, "this")
    2292
    2293        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
    2294        nulls_sort_change = ""
    2295        if nulls_first and (
    2296            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    2297        ):
    2298            nulls_sort_change = " NULLS FIRST"
    2299        elif (
    2300            nulls_last
    2301            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    2302            and not nulls_are_last
    2303        ):
    2304            nulls_sort_change = " NULLS LAST"
    2305
    2306        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
    2307        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    2308            window = expression.find_ancestor(exp.Window, exp.Select)
    2309            if isinstance(window, exp.Window) and window.args.get("spec"):
    2310                self.unsupported(
    2311                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
    2312                )
    2313                nulls_sort_change = ""
    2314            elif self.NULL_ORDERING_SUPPORTED is None:
    2315                if expression.this.is_int:
    2316                    self.unsupported(
    2317                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
    2318                    )
    2319                elif not isinstance(expression.this, exp.Rand):
    2320                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
    2321                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
    2322                nulls_sort_change = ""
    2323
    2324        with_fill = self.sql(expression, "with_fill")
    2325        with_fill = f" {with_fill}" if with_fill else ""
    2326
    2327        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"

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

    2329    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
    2330        window_frame = self.sql(expression, "window_frame")
    2331        window_frame = f"{window_frame} " if window_frame else ""
    2332
    2333        this = self.sql(expression, "this")
    2334
    2335        return f"{window_frame}{this}"

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

    2337    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    2338        partition = self.partition_by_sql(expression)
    2339        order = self.sql(expression, "order")
    2340        measures = self.expressions(expression, key="measures")
    2341        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    2342        rows = self.sql(expression, "rows")
    2343        rows = self.seg(rows) if rows else ""
    2344        after = self.sql(expression, "after")
    2345        after = self.seg(after) if after else ""
    2346        pattern = self.sql(expression, "pattern")
    2347        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    2348        definition_sqls = [
    2349            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    2350            for definition in expression.args.get("define", [])
    2351        ]
    2352        definitions = self.expressions(sqls=definition_sqls)
    2353        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    2354        body = "".join(
    2355            (
    2356                partition,
    2357                order,
    2358                measures,
    2359                rows,
    2360                after,
    2361                pattern,
    2362                define,
    2363            )
    2364        )
    2365        alias = self.sql(expression, "alias")
    2366        alias = f" {alias}" if alias else ""
    2367        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    2369    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    2370        limit = expression.args.get("limit")
    2371
    2372        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    2373            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    2374        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    2375            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    2376
    2377        return csv(
    2378            *sqls,
    2379            *[self.sql(join) for join in expression.args.get("joins") or []],
    2380            self.sql(expression, "connect"),
    2381            self.sql(expression, "match"),
    2382            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2383            self.sql(expression, "prewhere"),
    2384            self.sql(expression, "where"),
    2385            self.sql(expression, "group"),
    2386            self.sql(expression, "having"),
    2387            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
    2388            self.sql(expression, "order"),
    2389            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
    2390            *self.after_limit_modifiers(expression),
    2391            self.options_modifier(expression),
    2392            sep="",
    2393        )

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

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

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

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

    2402    def offset_limit_modifiers(
    2403        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2404    ) -> t.List[str]:
    2405        return [
    2406            self.sql(expression, "offset") if fetch else self.sql(limit),
    2407            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2408        ]

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

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

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

    2415    def select_sql(self, expression: exp.Select) -> str:
    2416        into = expression.args.get("into")
    2417        if not self.SUPPORTS_SELECT_INTO and into:
    2418            into.pop()
    2419
    2420        hint = self.sql(expression, "hint")
    2421        distinct = self.sql(expression, "distinct")
    2422        distinct = f" {distinct}" if distinct else ""
    2423        kind = self.sql(expression, "kind")
    2424
    2425        limit = expression.args.get("limit")
    2426        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
    2427            top = self.limit_sql(limit, top=True)
    2428            limit.pop()
    2429        else:
    2430            top = ""
    2431
    2432        expressions = self.expressions(expression)
    2433
    2434        if kind:
    2435            if kind in self.SELECT_KINDS:
    2436                kind = f" AS {kind}"
    2437            else:
    2438                if kind == "STRUCT":
    2439                    expressions = self.expressions(
    2440                        sqls=[
    2441                            self.sql(
    2442                                exp.Struct(
    2443                                    expressions=[
    2444                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
    2445                                        if isinstance(e, exp.Alias)
    2446                                        else e
    2447                                        for e in expression.expressions
    2448                                    ]
    2449                                )
    2450                            )
    2451                        ]
    2452                    )
    2453                kind = ""
    2454
    2455        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
    2456        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
    2457        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
    2458        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    2459        sql = self.query_modifiers(
    2460            expression,
    2461            f"SELECT{top_distinct}{kind}{expressions}",
    2462            self.sql(expression, "into", comment=False),
    2463            self.sql(expression, "from", comment=False),
    2464        )
    2465
    2466        sql = self.prepend_ctes(expression, sql)
    2467
    2468        if not self.SUPPORTS_SELECT_INTO and into:
    2469            if into.args.get("temporary"):
    2470                table_kind = " TEMPORARY"
    2471            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
    2472                table_kind = " UNLOGGED"
    2473            else:
    2474                table_kind = ""
    2475            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
    2476
    2477        return sql

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

    2479    def schema_sql(self, expression: exp.Schema) -> str:
    2480        this = self.sql(expression, "this")
    2481        sql = self.schema_columns_sql(expression)
    2482        return f"{this} {sql}" if this and sql else this or sql

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

    2484    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2485        if expression.expressions:
    2486            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2487        return ""

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

    2489    def star_sql(self, expression: exp.Star) -> str:
    2490        except_ = self.expressions(expression, key="except", flat=True)
    2491        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
    2492        replace = self.expressions(expression, key="replace", flat=True)
    2493        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
    2494        rename = self.expressions(expression, key="rename", flat=True)
    2495        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
    2496        return f"*{except_}{replace}{rename}"

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

    2498    def parameter_sql(self, expression: exp.Parameter) -> str:
    2499        this = self.sql(expression, "this")
    2500        return f"{self.PARAMETER_TOKEN}{this}"

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

    2502    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2503        this = self.sql(expression, "this")
    2504        kind = expression.text("kind")
    2505        if kind:
    2506            kind = f"{kind}."
    2507        return f"@@{kind}{this}"

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

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

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

    2512    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2513        alias = self.sql(expression, "alias")
    2514        alias = f"{sep}{alias}" if alias else ""
    2515        sample = self.sql(expression, "sample")
    2516        if self.dialect.ALIAS_POST_TABLESAMPLE and sample:
    2517            alias = f"{sample}{alias}"
    2518
    2519            # Set to None so it's not generated again by self.query_modifiers()
    2520            expression.set("sample", None)
    2521
    2522        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2523        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2524        return self.prepend_ctes(expression, sql)

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

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

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

    2530    def unnest_sql(self, expression: exp.Unnest) -> str:
    2531        args = self.expressions(expression, flat=True)
    2532
    2533        alias = expression.args.get("alias")
    2534        offset = expression.args.get("offset")
    2535
    2536        if self.UNNEST_WITH_ORDINALITY:
    2537            if alias and isinstance(offset, exp.Expression):
    2538                alias.append("columns", offset)
    2539
    2540        if alias and self.dialect.UNNEST_COLUMN_ONLY:
    2541            columns = alias.columns
    2542            alias = self.sql(columns[0]) if columns else ""
    2543        else:
    2544            alias = self.sql(alias)
    2545
    2546        alias = f" AS {alias}" if alias else alias
    2547        if self.UNNEST_WITH_ORDINALITY:
    2548            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2549        else:
    2550            if isinstance(offset, exp.Expression):
    2551                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2552            elif offset:
    2553                suffix = f"{alias} WITH OFFSET"
    2554            else:
    2555                suffix = alias
    2556
    2557        return f"UNNEST({args}){suffix}"

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

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

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

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

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

    2566    def window_sql(self, expression: exp.Window) -> str:
    2567        this = self.sql(expression, "this")
    2568        partition = self.partition_by_sql(expression)
    2569        order = expression.args.get("order")
    2570        order = self.order_sql(order, flat=True) if order else ""
    2571        spec = self.sql(expression, "spec")
    2572        alias = self.sql(expression, "alias")
    2573        over = self.sql(expression, "over") or "OVER"
    2574
    2575        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2576
    2577        first = expression.args.get("first")
    2578        if first is None:
    2579            first = ""
    2580        else:
    2581            first = "FIRST" if first else "LAST"
    2582
    2583        if not partition and not order and not spec and alias:
    2584            return f"{this} {alias}"
    2585
    2586        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    2587        return f"{this} ({args})"

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

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

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

    2593    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2594        kind = self.sql(expression, "kind")
    2595        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2596        end = (
    2597            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2598            or "CURRENT ROW"
    2599        )
    2600        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    2607    def between_sql(self, expression: exp.Between) -> str:
    2608        this = self.sql(expression, "this")
    2609        low = self.sql(expression, "low")
    2610        high = self.sql(expression, "high")
    2611        return f"{this} BETWEEN {low} AND {high}"

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

    2613    def bracket_offset_expressions(self, expression: exp.Bracket) -> t.List[exp.Expression]:
    2614        return apply_index_offset(
    2615            expression.this,
    2616            expression.expressions,
    2617            self.dialect.INDEX_OFFSET - expression.args.get("offset", 0),
    2618        )

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

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

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

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

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

    2628    def any_sql(self, expression: exp.Any) -> str:
    2629        this = self.sql(expression, "this")
    2630        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
    2631            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2632                this = self.wrap(this)
    2633            return f"ANY{this}"
    2634        return f"ANY {this}"

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

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

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

    2639    def case_sql(self, expression: exp.Case) -> str:
    2640        this = self.sql(expression, "this")
    2641        statements = [f"CASE {this}" if this else "CASE"]
    2642
    2643        for e in expression.args["ifs"]:
    2644            statements.append(f"WHEN {self.sql(e, 'this')}")
    2645            statements.append(f"THEN {self.sql(e, 'true')}")
    2646
    2647        default = self.sql(expression, "default")
    2648
    2649        if default:
    2650            statements.append(f"ELSE {default}")
    2651
    2652        statements.append("END")
    2653
    2654        if self.pretty and self.too_wide(statements):
    2655            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2656
    2657        return " ".join(statements)

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

    2659    def constraint_sql(self, expression: exp.Constraint) -> str:
    2660        this = self.sql(expression, "this")
    2661        expressions = self.expressions(expression, flat=True)
    2662        return f"CONSTRAINT {this} {expressions}"

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

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

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

    2669    def extract_sql(self, expression: exp.Extract) -> str:
    2670        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2671        expression_sql = self.sql(expression, "expression")
    2672        return f"EXTRACT({this} FROM {expression_sql})"

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

    2674    def trim_sql(self, expression: exp.Trim) -> str:
    2675        trim_type = self.sql(expression, "position")
    2676
    2677        if trim_type == "LEADING":
    2678            func_name = "LTRIM"
    2679        elif trim_type == "TRAILING":
    2680            func_name = "RTRIM"
    2681        else:
    2682            func_name = "TRIM"
    2683
    2684        return self.func(func_name, expression.this, expression.expression)

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

    2686    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2687        args = expression.expressions
    2688        if isinstance(expression, exp.ConcatWs):
    2689            args = args[1:]  # Skip the delimiter
    2690
    2691        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2692            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
    2693
    2694        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2695            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2696
    2697        return args

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

    2699    def concat_sql(self, expression: exp.Concat) -> str:
    2700        expressions = self.convert_concat_args(expression)
    2701
    2702        # Some dialects don't allow a single-argument CONCAT call
    2703        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2704            return self.sql(expressions[0])
    2705
    2706        return self.func("CONCAT", *expressions)

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

    2708    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2709        return self.func(
    2710            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2711        )

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

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

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

    2717    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2718        expressions = self.expressions(expression, flat=True)
    2719        reference = self.sql(expression, "reference")
    2720        reference = f" {reference}" if reference else ""
    2721        delete = self.sql(expression, "delete")
    2722        delete = f" ON DELETE {delete}" if delete else ""
    2723        update = self.sql(expression, "update")
    2724        update = f" ON UPDATE {update}" if update else ""
    2725        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"

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

    2727    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2728        expressions = self.expressions(expression, flat=True)
    2729        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2730        options = f" {options}" if options else ""
    2731        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

    2744    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
    2745        path = self.expressions(expression, sep="", flat=True).lstrip(".")
    2746        if self.QUOTE_JSON_PATH:
    2747            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
    2748
    2749        return path

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

    2751    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
    2752        if isinstance(expression, exp.JSONPathPart):
    2753            transform = self.TRANSFORMS.get(expression.__class__)
    2754            if not callable(transform):
    2755                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
    2756                return ""
    2757
    2758            return transform(self, expression)
    2759
    2760        if isinstance(expression, int):
    2761            return str(expression)
    2762
    2763        if self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
    2764            escaped = expression.replace("'", "\\'")
    2765            escaped = f"\\'{expression}\\'"
    2766        else:
    2767            escaped = expression.replace('"', '\\"')
    2768            escaped = f'"{escaped}"'
    2769
    2770        return escaped

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

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

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

    2775    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    2776        null_handling = expression.args.get("null_handling")
    2777        null_handling = f" {null_handling}" if null_handling else ""
    2778
    2779        unique_keys = expression.args.get("unique_keys")
    2780        if unique_keys is not None:
    2781            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2782        else:
    2783            unique_keys = ""
    2784
    2785        return_type = self.sql(expression, "return_type")
    2786        return_type = f" RETURNING {return_type}" if return_type else ""
    2787        encoding = self.sql(expression, "encoding")
    2788        encoding = f" ENCODING {encoding}" if encoding else ""
    2789
    2790        return self.func(
    2791            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    2792            *expression.expressions,
    2793            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2794        )

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

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

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

    2799    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2800        null_handling = expression.args.get("null_handling")
    2801        null_handling = f" {null_handling}" if null_handling else ""
    2802        return_type = self.sql(expression, "return_type")
    2803        return_type = f" RETURNING {return_type}" if return_type else ""
    2804        strict = " STRICT" if expression.args.get("strict") else ""
    2805        return self.func(
    2806            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2807        )

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

    2809    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2810        this = self.sql(expression, "this")
    2811        order = self.sql(expression, "order")
    2812        null_handling = expression.args.get("null_handling")
    2813        null_handling = f" {null_handling}" if null_handling else ""
    2814        return_type = self.sql(expression, "return_type")
    2815        return_type = f" RETURNING {return_type}" if return_type else ""
    2816        strict = " STRICT" if expression.args.get("strict") else ""
    2817        return self.func(
    2818            "JSON_ARRAYAGG",
    2819            this,
    2820            suffix=f"{order}{null_handling}{return_type}{strict})",
    2821        )

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

    2823    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2824        path = self.sql(expression, "path")
    2825        path = f" PATH {path}" if path else ""
    2826        nested_schema = self.sql(expression, "nested_schema")
    2827
    2828        if nested_schema:
    2829            return f"NESTED{path} {nested_schema}"
    2830
    2831        this = self.sql(expression, "this")
    2832        kind = self.sql(expression, "kind")
    2833        kind = f" {kind}" if kind else ""
    2834        return f"{this}{kind}{path}"

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

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

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

    2839    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    2840        this = self.sql(expression, "this")
    2841        path = self.sql(expression, "path")
    2842        path = f", {path}" if path else ""
    2843        error_handling = expression.args.get("error_handling")
    2844        error_handling = f" {error_handling}" if error_handling else ""
    2845        empty_handling = expression.args.get("empty_handling")
    2846        empty_handling = f" {empty_handling}" if empty_handling else ""
    2847        schema = self.sql(expression, "schema")
    2848        return self.func(
    2849            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    2850        )

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

    2852    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    2853        this = self.sql(expression, "this")
    2854        kind = self.sql(expression, "kind")
    2855        path = self.sql(expression, "path")
    2856        path = f" {path}" if path else ""
    2857        as_json = " AS JSON" if expression.args.get("as_json") else ""
    2858        return f"{this} {kind}{path}{as_json}"

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

    2860    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    2861        this = self.sql(expression, "this")
    2862        path = self.sql(expression, "path")
    2863        path = f", {path}" if path else ""
    2864        expressions = self.expressions(expression)
    2865        with_ = (
    2866            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2867            if expressions
    2868            else ""
    2869        )
    2870        return f"OPENJSON({this}{path}){with_}"

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

    2872    def in_sql(self, expression: exp.In) -> str:
    2873        query = expression.args.get("query")
    2874        unnest = expression.args.get("unnest")
    2875        field = expression.args.get("field")
    2876        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    2877
    2878        if query:
    2879            in_sql = self.sql(query)
    2880        elif unnest:
    2881            in_sql = self.in_unnest_op(unnest)
    2882        elif field:
    2883            in_sql = self.sql(field)
    2884        else:
    2885            in_sql = f"({self.expressions(expression, flat=True)})"
    2886
    2887        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    2892    def interval_sql(self, expression: exp.Interval) -> str:
    2893        unit = self.sql(expression, "unit")
    2894        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    2895            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    2896        unit = f" {unit}" if unit else ""
    2897
    2898        if self.SINGLE_STRING_INTERVAL:
    2899            this = expression.this.name if expression.this else ""
    2900            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    2901
    2902        this = self.sql(expression, "this")
    2903        if this:
    2904            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    2905            this = f" {this}" if unwrapped else f" ({this})"
    2906
    2907        return f"INTERVAL{this}{unit}"

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

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

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

    2912    def reference_sql(self, expression: exp.Reference) -> str:
    2913        this = self.sql(expression, "this")
    2914        expressions = self.expressions(expression, flat=True)
    2915        expressions = f"({expressions})" if expressions else ""
    2916        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2917        options = f" {options}" if options else ""
    2918        return f"REFERENCES {this}{expressions}{options}"

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

    2920    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    2921        # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive
    2922        parent = expression.parent
    2923        is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression
    2924        return self.func(
    2925            self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified
    2926        )

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

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

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

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

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

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

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

    2941    def alias_sql(self, expression: exp.Alias) -> str:
    2942        alias = self.sql(expression, "alias")
    2943        alias = f" AS {alias}" if alias else ""
    2944        return f"{self.sql(expression, 'this')}{alias}"

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

    2946    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    2947        alias = expression.args["alias"]
    2948
    2949        identifier_alias = isinstance(alias, exp.Identifier)
    2950        literal_alias = isinstance(alias, exp.Literal)
    2951
    2952        if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2953            alias.replace(exp.Literal.string(alias.output_name))
    2954        elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2955            alias.replace(exp.to_identifier(alias.output_name))
    2956
    2957        return self.alias_sql(expression)

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

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

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

    2962    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    2963        this = self.sql(expression, "this")
    2964        index = self.sql(expression, "expression")
    2965        return f"{this} AT {index}"

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

    2967    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    2968        this = self.sql(expression, "this")
    2969        zone = self.sql(expression, "zone")
    2970        return f"{this} AT TIME ZONE {zone}"

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

    2972    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    2973        this = self.sql(expression, "this")
    2974        zone = self.sql(expression, "zone")
    2975        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"

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

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

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

    2980    def and_sql(
    2981        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
    2982    ) -> str:
    2983        return self.connector_sql(expression, "AND", stack)

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

    2985    def or_sql(
    2986        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
    2987    ) -> str:
    2988        return self.connector_sql(expression, "OR", stack)

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

    2990    def xor_sql(
    2991        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
    2992    ) -> str:
    2993        return self.connector_sql(expression, "XOR", stack)

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

    2995    def connector_sql(
    2996        self,
    2997        expression: exp.Connector,
    2998        op: str,
    2999        stack: t.Optional[t.List[str | exp.Expression]] = None,
    3000    ) -> str:
    3001        if stack is not None:
    3002            if expression.expressions:
    3003                stack.append(self.expressions(expression, sep=f" {op} "))
    3004            else:
    3005                stack.append(expression.right)
    3006                if expression.comments and self.comments:
    3007                    for comment in expression.comments:
    3008                        if comment:
    3009                            op += f" /*{self.pad_comment(comment)}*/"
    3010                stack.extend((op, expression.left))
    3011            return op
    3012
    3013        stack = [expression]
    3014        sqls: t.List[str] = []
    3015        ops = set()
    3016
    3017        while stack:
    3018            node = stack.pop()
    3019            if isinstance(node, exp.Connector):
    3020                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
    3021            else:
    3022                sql = self.sql(node)
    3023                if sqls and sqls[-1] in ops:
    3024                    sqls[-1] += f" {sql}"
    3025                else:
    3026                    sqls.append(sql)
    3027
    3028        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
    3029        return sep.join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

    3049    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    3050        format_sql = self.sql(expression, "format")
    3051        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    3052        to_sql = self.sql(expression, "to")
    3053        to_sql = f" {to_sql}" if to_sql else ""
    3054        action = self.sql(expression, "action")
    3055        action = f" {action}" if action else ""
    3056        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{format_sql}{action})"

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

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

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

    3062    def collate_sql(self, expression: exp.Collate) -> str:
    3063        if self.COLLATE_IS_FUNC:
    3064            return self.function_fallback_sql(expression)
    3065        return self.binary(expression, "COLLATE")

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

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

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

    3070    def comment_sql(self, expression: exp.Comment) -> str:
    3071        this = self.sql(expression, "this")
    3072        kind = expression.args["kind"]
    3073        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    3074        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    3075        expression_sql = self.sql(expression, "expression")
    3076        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"

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

    3078    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    3079        this = self.sql(expression, "this")
    3080        delete = " DELETE" if expression.args.get("delete") else ""
    3081        recompress = self.sql(expression, "recompress")
    3082        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    3083        to_disk = self.sql(expression, "to_disk")
    3084        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    3085        to_volume = self.sql(expression, "to_volume")
    3086        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    3087        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    3089    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    3090        where = self.sql(expression, "where")
    3091        group = self.sql(expression, "group")
    3092        aggregates = self.expressions(expression, key="aggregates")
    3093        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    3094
    3095        if not (where or group or aggregates) and len(expression.expressions) == 1:
    3096            return f"TTL {self.expressions(expression, flat=True)}"
    3097
    3098        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    3103    def commit_sql(self, expression: exp.Commit) -> str:
    3104        chain = expression.args.get("chain")
    3105        if chain is not None:
    3106            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    3107
    3108        return f"COMMIT{chain or ''}"

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

    3110    def rollback_sql(self, expression: exp.Rollback) -> str:
    3111        savepoint = expression.args.get("savepoint")
    3112        savepoint = f" TO {savepoint}" if savepoint else ""
    3113        return f"ROLLBACK{savepoint}"

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

    3115    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    3116        this = self.sql(expression, "this")
    3117
    3118        dtype = self.sql(expression, "dtype")
    3119        if dtype:
    3120            collate = self.sql(expression, "collate")
    3121            collate = f" COLLATE {collate}" if collate else ""
    3122            using = self.sql(expression, "using")
    3123            using = f" USING {using}" if using else ""
    3124            return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}"
    3125
    3126        default = self.sql(expression, "default")
    3127        if default:
    3128            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    3129
    3130        comment = self.sql(expression, "comment")
    3131        if comment:
    3132            return f"ALTER COLUMN {this} COMMENT {comment}"
    3133
    3134        allow_null = expression.args.get("allow_null")
    3135        drop = expression.args.get("drop")
    3136
    3137        if not drop and not allow_null:
    3138            self.unsupported("Unsupported ALTER COLUMN syntax")
    3139
    3140        if allow_null is not None:
    3141            keyword = "DROP" if drop else "SET"
    3142            return f"ALTER COLUMN {this} {keyword} NOT NULL"
    3143
    3144        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    3146    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
    3147        this = self.sql(expression, "this")
    3148        if not isinstance(expression.this, exp.Var):
    3149            this = f"KEY DISTKEY {this}"
    3150        return f"ALTER DISTSTYLE {this}"

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

    3152    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
    3153        compound = " COMPOUND" if expression.args.get("compound") else ""
    3154        this = self.sql(expression, "this")
    3155        expressions = self.expressions(expression, flat=True)
    3156        expressions = f"({expressions})" if expressions else ""
    3157        return f"ALTER{compound} SORTKEY {this or expressions}"

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

    3159    def renametable_sql(self, expression: exp.RenameTable) -> str:
    3160        if not self.RENAME_TABLE_WITH_DB:
    3161            # Remove db from tables
    3162            expression = expression.transform(
    3163                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    3164            ).assert_is(exp.RenameTable)
    3165        this = self.sql(expression, "this")
    3166        return f"RENAME TO {this}"

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

    3168    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    3169        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3170        old_column = self.sql(expression, "this")
    3171        new_column = self.sql(expression, "to")
    3172        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"

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

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

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

    3178    def alter_sql(self, expression: exp.Alter) -> str:
    3179        actions = expression.args["actions"]
    3180
    3181        if isinstance(actions[0], exp.ColumnDef):
    3182            actions = self.add_column_sql(expression)
    3183        elif isinstance(actions[0], exp.Schema):
    3184            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    3185        elif isinstance(actions[0], exp.Delete):
    3186            actions = self.expressions(expression, key="actions", flat=True)
    3187        elif isinstance(actions[0], exp.Query):
    3188            actions = "AS " + self.expressions(expression, key="actions")
    3189        else:
    3190            actions = self.expressions(expression, key="actions", flat=True)
    3191
    3192        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3193        on_cluster = self.sql(expression, "cluster")
    3194        on_cluster = f" {on_cluster}" if on_cluster else ""
    3195        only = " ONLY" if expression.args.get("only") else ""
    3196        options = self.expressions(expression, key="options")
    3197        options = f", {options}" if options else ""
    3198        kind = self.sql(expression, "kind")
    3199        not_valid = " NOT VALID" if expression.args.get("not_valid") else ""
    3200
    3201        return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}"

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

    3203    def add_column_sql(self, expression: exp.Alter) -> str:
    3204        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    3205            return self.expressions(
    3206                expression,
    3207                key="actions",
    3208                prefix="ADD COLUMN ",
    3209                skip_first=True,
    3210            )
    3211        return f"ADD {self.expressions(expression, key='actions', flat=True)}"

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

    3213    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    3214        expressions = self.expressions(expression)
    3215        exists = " IF EXISTS " if expression.args.get("exists") else " "
    3216        return f"DROP{exists}{expressions}"

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

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

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

    3221    def distinct_sql(self, expression: exp.Distinct) -> str:
    3222        this = self.expressions(expression, flat=True)
    3223
    3224        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    3225            case = exp.case()
    3226            for arg in expression.expressions:
    3227                case = case.when(arg.is_(exp.null()), exp.null())
    3228            this = self.sql(case.else_(f"({this})"))
    3229
    3230        this = f" {this}" if this else ""
    3231
    3232        on = self.sql(expression, "on")
    3233        on = f" ON {on}" if on else ""
    3234        return f"DISTINCT{this}{on}"

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

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

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

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

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

    3242    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    3243        this_sql = self.sql(expression, "this")
    3244        expression_sql = self.sql(expression, "expression")
    3245        kind = "MAX" if expression.args.get("max") else "MIN"
    3246        return f"{this_sql} HAVING {kind} {expression_sql}"

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

    3248    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    3249        return self.sql(
    3250            exp.Cast(
    3251                this=exp.Div(this=expression.this, expression=expression.expression),
    3252                to=exp.DataType(this=exp.DataType.Type.INT),
    3253            )
    3254        )

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

    3256    def dpipe_sql(self, expression: exp.DPipe) -> str:
    3257        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    3258            return self.func(
    3259                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
    3260            )
    3261        return self.binary(expression, "||")

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

    3263    def div_sql(self, expression: exp.Div) -> str:
    3264        l, r = expression.left, expression.right
    3265
    3266        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    3267            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    3268
    3269        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    3270            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
    3271                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    3272
    3273        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    3274            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    3275                return self.sql(
    3276                    exp.cast(
    3277                        l / r,
    3278                        to=exp.DataType.Type.BIGINT,
    3279                    )
    3280                )
    3281
    3282        return self.binary(expression, "/")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3317    def is_sql(self, expression: exp.Is) -> str:
    3318        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3319            return self.sql(
    3320                expression.this if expression.expression.this else exp.not_(expression.this)
    3321            )
    3322        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3363    def try_sql(self, expression: exp.Try) -> str:
    3364        if not self.TRY_SUPPORTED:
    3365            self.unsupported("Unsupported TRY function")
    3366            return self.sql(expression, "this")
    3367
    3368        return self.func("TRY", expression.this)

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

    3370    def log_sql(self, expression: exp.Log) -> str:
    3371        this = expression.this
    3372        expr = expression.expression
    3373
    3374        if self.dialect.LOG_BASE_FIRST is False:
    3375            this, expr = expr, this
    3376        elif self.dialect.LOG_BASE_FIRST is None and expr:
    3377            if this.name in ("2", "10"):
    3378                return self.func(f"LOG{this.name}", expr)
    3379
    3380            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
    3381
    3382        return self.func("LOG", this, expr)

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

    3384    def use_sql(self, expression: exp.Use) -> str:
    3385        kind = self.sql(expression, "kind")
    3386        kind = f" {kind}" if kind else ""
    3387        this = self.sql(expression, "this")
    3388        this = f" {this}" if this else ""
    3389        return f"USE{kind}{this}"

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

    3391    def binary(self, expression: exp.Binary, op: str) -> str:
    3392        sqls: t.List[str] = []
    3393        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    3394        binary_type = type(expression)
    3395
    3396        while stack:
    3397            node = stack.pop()
    3398
    3399            if type(node) is binary_type:
    3400                op_func = node.args.get("operator")
    3401                if op_func:
    3402                    op = f"OPERATOR({self.sql(op_func)})"
    3403
    3404                stack.append(node.right)
    3405                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
    3406                stack.append(node.left)
    3407            else:
    3408                sqls.append(self.sql(node))
    3409
    3410        return "".join(sqls)

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

    3412    def function_fallback_sql(self, expression: exp.Func) -> str:
    3413        args = []
    3414
    3415        for key in expression.arg_types:
    3416            arg_value = expression.args.get(key)
    3417
    3418            if isinstance(arg_value, list):
    3419                for value in arg_value:
    3420                    args.append(value)
    3421            elif arg_value is not None:
    3422                args.append(arg_value)
    3423
    3424        if self.normalize_functions:
    3425            name = expression.sql_name()
    3426        else:
    3427            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3428
    3429        return self.func(name, *args)

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

    3431    def func(
    3432        self,
    3433        name: str,
    3434        *args: t.Optional[exp.Expression | str],
    3435        prefix: str = "(",
    3436        suffix: str = ")",
    3437        normalize: bool = True,
    3438    ) -> str:
    3439        name = self.normalize_func(name) if normalize else name
    3440        return f"{name}{prefix}{self.format_args(*args)}{suffix}"

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

    3442    def format_args(self, *args: t.Optional[str | exp.Expression]) -> str:
    3443        arg_sqls = tuple(
    3444            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
    3445        )
    3446        if self.pretty and self.too_wide(arg_sqls):
    3447            return self.indent("\n" + ",\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True)
    3448        return ", ".join(arg_sqls)

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

    3450    def too_wide(self, args: t.Iterable) -> bool:
    3451        return sum(len(arg) for arg in args) > self.max_text_width

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

    3453    def format_time(
    3454        self,
    3455        expression: exp.Expression,
    3456        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
    3457        inverse_time_trie: t.Optional[t.Dict] = None,
    3458    ) -> t.Optional[str]:
    3459        return format_time(
    3460            self.sql(expression, "format"),
    3461            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
    3462            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
    3463        )

def expressions( self, expression: Optional[sqlglot.expressions.Expression] = None, key: Optional[str] = None, sqls: Optional[Collection[Union[str, sqlglot.expressions.Expression]]] = None, flat: bool = False, indent: bool = True, skip_first: bool = False, skip_last: bool = False, sep: str = ', ', prefix: str = '', dynamic: bool = False, new_line: bool = False) -> str: View Source

    3465    def expressions(
    3466        self,
    3467        expression: t.Optional[exp.Expression] = None,
    3468        key: t.Optional[str] = None,
    3469        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    3470        flat: bool = False,
    3471        indent: bool = True,
    3472        skip_first: bool = False,
    3473        skip_last: bool = False,
    3474        sep: str = ", ",
    3475        prefix: str = "",
    3476        dynamic: bool = False,
    3477        new_line: bool = False,
    3478    ) -> str:
    3479        expressions = expression.args.get(key or "expressions") if expression else sqls
    3480
    3481        if not expressions:
    3482            return ""
    3483
    3484        if flat:
    3485            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    3486
    3487        num_sqls = len(expressions)
    3488        result_sqls = []
    3489
    3490        for i, e in enumerate(expressions):
    3491            sql = self.sql(e, comment=False)
    3492            if not sql:
    3493                continue
    3494
    3495            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    3496
    3497            if self.pretty:
    3498                if self.leading_comma:
    3499                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
    3500                else:
    3501                    result_sqls.append(
    3502                        f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}"
    3503                    )
    3504            else:
    3505                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    3506
    3507        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
    3508            if new_line:
    3509                result_sqls.insert(0, "")
    3510                result_sqls.append("")
    3511            result_sql = "\n".join(s.rstrip() for s in result_sqls)
    3512        else:
    3513            result_sql = "".join(result_sqls)
    3514
    3515        return (
    3516            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
    3517            if indent
    3518            else result_sql
    3519        )

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

    3521    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3522        flat = flat or isinstance(expression.parent, exp.Properties)
    3523        expressions_sql = self.expressions(expression, flat=flat)
    3524        if flat:
    3525            return f"{op} {expressions_sql}"
    3526        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    3528    def naked_property(self, expression: exp.Property) -> str:
    3529        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3530        if not property_name:
    3531            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3532        return f"{property_name} {self.sql(expression, 'this')}"

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

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

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

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

    3540    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3541        this = self.sql(expression, "this")
    3542        expressions = self.no_identify(self.expressions, expression)
    3543        expressions = (
    3544            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3545        )
    3546        return f"{this}{expressions}"

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

    3548    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3549        this = self.sql(expression, "this")
    3550        expressions = self.expressions(expression, flat=True)
    3551        return f"{this}({expressions})"

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

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

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

    3556    def when_sql(self, expression: exp.When) -> str:
    3557        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3558        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3559        condition = self.sql(expression, "condition")
    3560        condition = f" AND {condition}" if condition else ""
    3561
    3562        then_expression = expression.args.get("then")
    3563        if isinstance(then_expression, exp.Insert):
    3564            this = self.sql(then_expression, "this")
    3565            this = f"INSERT {this}" if this else "INSERT"
    3566            then = self.sql(then_expression, "expression")
    3567            then = f"{this} VALUES {then}" if then else this
    3568        elif isinstance(then_expression, exp.Update):
    3569            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3570                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3571            else:
    3572                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    3573        else:
    3574            then = self.sql(then_expression)
    3575        return f"WHEN {matched}{source}{condition} THEN {then}"

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

    3577    def merge_sql(self, expression: exp.Merge) -> str:
    3578        table = expression.this
    3579        table_alias = ""
    3580
    3581        hints = table.args.get("hints")
    3582        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3583            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3584            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3585
    3586        this = self.sql(table)
    3587        using = f"USING {self.sql(expression, 'using')}"
    3588        on = f"ON {self.sql(expression, 'on')}"
    3589        expressions = self.expressions(expression, sep=" ", indent=False)
    3590        sep = self.sep()
    3591
    3592        return self.prepend_ctes(
    3593            expression, f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{expressions}"
    3594        )

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

    3596    def tochar_sql(self, expression: exp.ToChar) -> str:
    3597        if expression.args.get("format"):
    3598            self.unsupported("Format argument unsupported for TO_CHAR/TO_VARCHAR function")
    3599
    3600        return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT))

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

    3602    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3603        if not self.SUPPORTS_TO_NUMBER:
    3604            self.unsupported("Unsupported TO_NUMBER function")
    3605            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3606
    3607        fmt = expression.args.get("format")
    3608        if not fmt:
    3609            self.unsupported("Conversion format is required for TO_NUMBER")
    3610            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3611
    3612        return self.func("TO_NUMBER", expression.this, fmt)

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

    3614    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3615        this = self.sql(expression, "this")
    3616        kind = self.sql(expression, "kind")
    3617        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3618        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3619        return f"{this}({kind}{args})"

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

    3621    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3622        this = self.sql(expression, "this")
    3623        max = self.sql(expression, "max")
    3624        min = self.sql(expression, "min")
    3625        return f"{this}(MIN {min} MAX {max})"

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

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

def duplicatekeyproperty_sql(self, expression: sqlglot.expressions.DuplicateKeyProperty) -> str: View Source

    3630    def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str:
    3631        return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})"

def distributedbyproperty_sql(self, expression: sqlglot.expressions.DistributedByProperty) -> str: View Source

    3634    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
    3635        expressions = self.expressions(expression, flat=True)
    3636        expressions = f" {self.wrap(expressions)}" if expressions else ""
    3637        buckets = self.sql(expression, "buckets")
    3638        kind = self.sql(expression, "kind")
    3639        buckets = f" BUCKETS {buckets}" if buckets else ""
    3640        order = self.sql(expression, "order")
    3641        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"

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

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

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

    3646    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3647        expressions = self.expressions(expression, key="expressions", flat=True)
    3648        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3649        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3650        buckets = self.sql(expression, "buckets")
    3651        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    3653    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3654        this = self.sql(expression, "this")
    3655        having = self.sql(expression, "having")
    3656
    3657        if having:
    3658            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3659
    3660        return self.func("ANY_VALUE", this)

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

    3662    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3663        transform = self.func("TRANSFORM", *expression.expressions)
    3664        row_format_before = self.sql(expression, "row_format_before")
    3665        row_format_before = f" {row_format_before}" if row_format_before else ""
    3666        record_writer = self.sql(expression, "record_writer")
    3667        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3668        using = f" USING {self.sql(expression, 'command_script')}"
    3669        schema = self.sql(expression, "schema")
    3670        schema = f" AS {schema}" if schema else ""
    3671        row_format_after = self.sql(expression, "row_format_after")
    3672        row_format_after = f" {row_format_after}" if row_format_after else ""
    3673        record_reader = self.sql(expression, "record_reader")
    3674        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3675        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

    3677    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3678        key_block_size = self.sql(expression, "key_block_size")
    3679        if key_block_size:
    3680            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3681
    3682        using = self.sql(expression, "using")
    3683        if using:
    3684            return f"USING {using}"
    3685
    3686        parser = self.sql(expression, "parser")
    3687        if parser:
    3688            return f"WITH PARSER {parser}"
    3689
    3690        comment = self.sql(expression, "comment")
    3691        if comment:
    3692            return f"COMMENT {comment}"
    3693
    3694        visible = expression.args.get("visible")
    3695        if visible is not None:
    3696            return "VISIBLE" if visible else "INVISIBLE"
    3697
    3698        engine_attr = self.sql(expression, "engine_attr")
    3699        if engine_attr:
    3700            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3701
    3702        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3703        if secondary_engine_attr:
    3704            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3705
    3706        self.unsupported("Unsupported index constraint option.")
    3707        return ""

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

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

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

    3713    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3714        kind = self.sql(expression, "kind")
    3715        kind = f"{kind} INDEX" if kind else "INDEX"
    3716        this = self.sql(expression, "this")
    3717        this = f" {this}" if this else ""
    3718        index_type = self.sql(expression, "index_type")
    3719        index_type = f" USING {index_type}" if index_type else ""
    3720        expressions = self.expressions(expression, flat=True)
    3721        expressions = f" ({expressions})" if expressions else ""
    3722        options = self.expressions(expression, key="options", sep=" ")
    3723        options = f" {options}" if options else ""
    3724        return f"{kind}{this}{index_type}{expressions}{options}"

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

    3726    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3727        if self.NVL2_SUPPORTED:
    3728            return self.function_fallback_sql(expression)
    3729
    3730        case = exp.Case().when(
    3731            expression.this.is_(exp.null()).not_(copy=False),
    3732            expression.args["true"],
    3733            copy=False,
    3734        )
    3735        else_cond = expression.args.get("false")
    3736        if else_cond:
    3737            case.else_(else_cond, copy=False)
    3738
    3739        return self.sql(case)

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

    3741    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3742        this = self.sql(expression, "this")
    3743        expr = self.sql(expression, "expression")
    3744        iterator = self.sql(expression, "iterator")
    3745        condition = self.sql(expression, "condition")
    3746        condition = f" IF {condition}" if condition else ""
    3747        return f"{this} FOR {expr} IN {iterator}{condition}"

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

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

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

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

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

    3755    def predict_sql(self, expression: exp.Predict) -> str:
    3756        model = self.sql(expression, "this")
    3757        model = f"MODEL {model}"
    3758        table = self.sql(expression, "expression")
    3759        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    3760        parameters = self.sql(expression, "params_struct")
    3761        return self.func("PREDICT", model, table, parameters or None)

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

    3763    def forin_sql(self, expression: exp.ForIn) -> str:
    3764        this = self.sql(expression, "this")
    3765        expression_sql = self.sql(expression, "expression")
    3766        return f"FOR {this} DO {expression_sql}"

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

    3768    def refresh_sql(self, expression: exp.Refresh) -> str:
    3769        this = self.sql(expression, "this")
    3770        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    3771        return f"REFRESH {table}{this}"

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

    3773    def toarray_sql(self, expression: exp.ToArray) -> str:
    3774        arg = expression.this
    3775        if not arg.type:
    3776            from sqlglot.optimizer.annotate_types import annotate_types
    3777
    3778            arg = annotate_types(arg)
    3779
    3780        if arg.is_type(exp.DataType.Type.ARRAY):
    3781            return self.sql(arg)
    3782
    3783        cond_for_null = arg.is_(exp.null())
    3784        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

    3786    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    3787        this = expression.this
    3788        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    3789            return self.sql(this)
    3790
    3791        return self.sql(exp.cast(this, exp.DataType.Type.TIME))

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

    3793    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
    3794        this = expression.this
    3795        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
    3796            return self.sql(this)
    3797
    3798        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP))

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

    3800    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    3801        this = expression.this
    3802        time_format = self.format_time(expression)
    3803
    3804        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    3805            return self.sql(
    3806                exp.cast(
    3807                    exp.StrToTime(this=this, format=expression.args["format"]),
    3808                    exp.DataType.Type.DATE,
    3809                )
    3810            )
    3811
    3812        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    3813            return self.sql(this)
    3814
    3815        return self.sql(exp.cast(this, exp.DataType.Type.DATE))

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

    3817    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    3818        return self.sql(
    3819            exp.func(
    3820                "DATEDIFF",
    3821                expression.this,
    3822                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
    3823                "day",
    3824            )
    3825        )

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

    3827    def lastday_sql(self, expression: exp.LastDay) -> str:
    3828        if self.LAST_DAY_SUPPORTS_DATE_PART:
    3829            return self.function_fallback_sql(expression)
    3830
    3831        unit = expression.text("unit")
    3832        if unit and unit != "MONTH":
    3833            self.unsupported("Date parts are not supported in LAST_DAY.")
    3834
    3835        return self.func("LAST_DAY", expression.this)

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

    3837    def dateadd_sql(self, expression: exp.DateAdd) -> str:
    3838        from sqlglot.dialects.dialect import unit_to_str
    3839
    3840        return self.func(
    3841            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
    3842        )

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

    3844    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    3845        if self.CAN_IMPLEMENT_ARRAY_ANY:
    3846            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    3847            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    3848            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    3849            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    3850
    3851        from sqlglot.dialects import Dialect
    3852
    3853        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    3854        if self.dialect.__class__ != Dialect:
    3855            self.unsupported("ARRAY_ANY is unsupported")
    3856
    3857        return self.function_fallback_sql(expression)

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

    3859    def struct_sql(self, expression: exp.Struct) -> str:
    3860        expression.set(
    3861            "expressions",
    3862            [
    3863                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    3864                if isinstance(e, exp.PropertyEQ)
    3865                else e
    3866                for e in expression.expressions
    3867            ],
    3868        )
    3869
    3870        return self.function_fallback_sql(expression)

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

    3872    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    3873        low = self.sql(expression, "this")
    3874        high = self.sql(expression, "expression")
    3875
    3876        return f"{low} TO {high}"

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

    3878    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    3879        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    3880        tables = f" {self.expressions(expression)}"
    3881
    3882        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3883
    3884        on_cluster = self.sql(expression, "cluster")
    3885        on_cluster = f" {on_cluster}" if on_cluster else ""
    3886
    3887        identity = self.sql(expression, "identity")
    3888        identity = f" {identity} IDENTITY" if identity else ""
    3889
    3890        option = self.sql(expression, "option")
    3891        option = f" {option}" if option else ""
    3892
    3893        partition = self.sql(expression, "partition")
    3894        partition = f" {partition}" if partition else ""
    3895
    3896        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"

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

    3900    def convert_sql(self, expression: exp.Convert) -> str:
    3901        to = expression.this
    3902        value = expression.expression
    3903        style = expression.args.get("style")
    3904        safe = expression.args.get("safe")
    3905        strict = expression.args.get("strict")
    3906
    3907        if not to or not value:
    3908            return ""
    3909
    3910        # Retrieve length of datatype and override to default if not specified
    3911        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3912            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    3913
    3914        transformed: t.Optional[exp.Expression] = None
    3915        cast = exp.Cast if strict else exp.TryCast
    3916
    3917        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
    3918        if isinstance(style, exp.Literal) and style.is_int:
    3919            from sqlglot.dialects.tsql import TSQL
    3920
    3921            style_value = style.name
    3922            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
    3923            if not converted_style:
    3924                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
    3925
    3926            fmt = exp.Literal.string(converted_style)
    3927
    3928            if to.this == exp.DataType.Type.DATE:
    3929                transformed = exp.StrToDate(this=value, format=fmt)
    3930            elif to.this == exp.DataType.Type.DATETIME:
    3931                transformed = exp.StrToTime(this=value, format=fmt)
    3932            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3933                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
    3934            elif to.this == exp.DataType.Type.TEXT:
    3935                transformed = exp.TimeToStr(this=value, format=fmt)
    3936
    3937        if not transformed:
    3938            transformed = cast(this=value, to=to, safe=safe)
    3939
    3940        return self.sql(transformed)

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

    3996    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
    3997        option = self.sql(expression, "this")
    3998
    3999        if expression.expressions:
    4000            upper = option.upper()
    4001
    4002            # Snowflake FILE_FORMAT options are separated by whitespace
    4003            sep = " " if upper == "FILE_FORMAT" else ", "
    4004
    4005            # Databricks copy/format options do not set their list of values with EQ
    4006            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
    4007            values = self.expressions(expression, flat=True, sep=sep)
    4008            return f"{option}{op}({values})"
    4009
    4010        value = self.sql(expression, "expression")
    4011
    4012        if not value:
    4013            return option
    4014
    4015        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
    4016
    4017        return f"{option}{op}{value}"

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

    4019    def credentials_sql(self, expression: exp.Credentials) -> str:
    4020        cred_expr = expression.args.get("credentials")
    4021        if isinstance(cred_expr, exp.Literal):
    4022            # Redshift case: CREDENTIALS <string>
    4023            credentials = self.sql(expression, "credentials")
    4024            credentials = f"CREDENTIALS {credentials}" if credentials else ""
    4025        else:
    4026            # Snowflake case: CREDENTIALS = (...)
    4027            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
    4028            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
    4029
    4030        storage = self.sql(expression, "storage")
    4031        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
    4032
    4033        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
    4034        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
    4035
    4036        iam_role = self.sql(expression, "iam_role")
    4037        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
    4038
    4039        region = self.sql(expression, "region")
    4040        region = f" REGION {region}" if region else ""
    4041
    4042        return f"{credentials}{storage}{encryption}{iam_role}{region}"

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

    4044    def copy_sql(self, expression: exp.Copy) -> str:
    4045        this = self.sql(expression, "this")
    4046        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
    4047
    4048        credentials = self.sql(expression, "credentials")
    4049        credentials = self.seg(credentials) if credentials else ""
    4050        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
    4051        files = self.expressions(expression, key="files", flat=True)
    4052
    4053        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
    4054        params = self.expressions(
    4055            expression,
    4056            key="params",
    4057            sep=sep,
    4058            new_line=True,
    4059            skip_last=True,
    4060            skip_first=True,
    4061            indent=self.COPY_PARAMS_ARE_WRAPPED,
    4062        )
    4063
    4064        if params:
    4065            if self.COPY_PARAMS_ARE_WRAPPED:
    4066                params = f" WITH ({params})"
    4067            elif not self.pretty:
    4068                params = f" {params}"
    4069
    4070        return f"COPY{this}{kind} {files}{credentials}{params}"

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

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

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

    4075    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
    4076        on_sql = "ON" if expression.args.get("on") else "OFF"
    4077        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
    4078        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
    4079        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    4080        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
    4081
    4082        if filter_col or retention_period:
    4083            on_sql = self.func("ON", filter_col, retention_period)
    4084
    4085        return f"DATA_DELETION={on_sql}"

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

    4087    def maskingpolicycolumnconstraint_sql(
    4088        self, expression: exp.MaskingPolicyColumnConstraint
    4089    ) -> str:
    4090        this = self.sql(expression, "this")
    4091        expressions = self.expressions(expression, flat=True)
    4092        expressions = f" USING ({expressions})" if expressions else ""
    4093        return f"MASKING POLICY {this}{expressions}"

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

    4095    def gapfill_sql(self, expression: exp.GapFill) -> str:
    4096        this = self.sql(expression, "this")
    4097        this = f"TABLE {this}"
    4098        return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"])

def scope_resolution(self, rhs: str, scope_name: str) -> str: View Source

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

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

    4103    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
    4104        this = self.sql(expression, "this")
    4105        expr = expression.expression
    4106
    4107        if isinstance(expr, exp.Func):
    4108            # T-SQL's CLR functions are case sensitive
    4109            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
    4110        else:
    4111            expr = self.sql(expression, "expression")
    4112
    4113        return self.scope_resolution(expr, this)

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

    4115    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
    4116        if self.PARSE_JSON_NAME is None:
    4117            return self.sql(expression.this)
    4118
    4119        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)

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

    4121    def rand_sql(self, expression: exp.Rand) -> str:
    4122        lower = self.sql(expression, "lower")
    4123        upper = self.sql(expression, "upper")
    4124
    4125        if lower and upper:
    4126            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
    4127        return self.func("RAND", expression.this)

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

    4129    def changes_sql(self, expression: exp.Changes) -> str:
    4130        information = self.sql(expression, "information")
    4131        information = f"INFORMATION => {information}"
    4132        at_before = self.sql(expression, "at_before")
    4133        at_before = f"{self.seg('')}{at_before}" if at_before else ""
    4134        end = self.sql(expression, "end")
    4135        end = f"{self.seg('')}{end}" if end else ""
    4136
    4137        return f"CHANGES ({information}){at_before}{end}"

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

    4139    def pad_sql(self, expression: exp.Pad) -> str:
    4140        prefix = "L" if expression.args.get("is_left") else "R"
    4141
    4142        fill_pattern = self.sql(expression, "fill_pattern") or None
    4143        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
    4144            fill_pattern = "' '"
    4145
    4146        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)

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

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

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

    4152    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
    4153        generate_series = exp.GenerateSeries(**expression.args)
    4154
    4155        parent = expression.parent
    4156        if isinstance(parent, (exp.Alias, exp.TableAlias)):
    4157            parent = parent.parent
    4158
    4159        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
    4160            return self.sql(exp.Unnest(expressions=[generate_series]))
    4161
    4162        if isinstance(parent, exp.Select):
    4163            self.unsupported("GenerateSeries projection unnesting is not supported.")
    4164
    4165        return self.sql(generate_series)

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

    4167    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
    4168        exprs = expression.expressions
    4169        if not self.ARRAY_CONCAT_IS_VAR_LEN:
    4170            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
    4171        else:
    4172            rhs = self.expressions(expression)
    4173
    4174        return self.func(name, expression.this, rhs)

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

    4176    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
    4177        if self.SUPPORTS_CONVERT_TIMEZONE:
    4178            return self.function_fallback_sql(expression)
    4179
    4180        source_tz = expression.args.get("source_tz")
    4181        target_tz = expression.args.get("target_tz")
    4182        timestamp = expression.args.get("timestamp")
    4183
    4184        if source_tz and timestamp:
    4185            timestamp = exp.AtTimeZone(
    4186                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
    4187            )
    4188
    4189        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
    4190
    4191        return self.sql(expr)

def json_sql(self, expression: sqlglot.expressions.JSON) -> str: View Source

    4193    def json_sql(self, expression: exp.JSON) -> str:
    4194        this = self.sql(expression, "this")
    4195        this = f" {this}" if this else ""
    4196
    4197        _with = expression.args.get("with")
    4198
    4199        if _with is None:
    4200            with_sql = ""
    4201        elif not _with:
    4202            with_sql = " WITHOUT"
    4203        else:
    4204            with_sql = " WITH"
    4205
    4206        unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else ""
    4207
    4208        return f"JSON{this}{with_sql}{unique_sql}"

def jsonvalue_sql(self, expression: sqlglot.expressions.JSONValue) -> str: View Source

    4210    def jsonvalue_sql(self, expression: exp.JSONValue) -> str:
    4211        def _generate_on_options(arg: t.Any) -> str:
    4212            return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}"
    4213
    4214        path = self.sql(expression, "path")
    4215        returning = self.sql(expression, "returning")
    4216        returning = f" RETURNING {returning}" if returning else ""
    4217
    4218        on_condition = self.sql(expression, "on_condition")
    4219        on_condition = f" {on_condition}" if on_condition else ""
    4220
    4221        return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")

def conditionalinsert_sql(self, expression: sqlglot.expressions.ConditionalInsert) -> str: View Source

    4223    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
    4224        else_ = "ELSE " if expression.args.get("else_") else ""
    4225        condition = self.sql(expression, "expression")
    4226        condition = f"WHEN {condition} THEN " if condition else else_
    4227        insert = self.sql(expression, "this")[len("INSERT") :].strip()
    4228        return f"{condition}{insert}"

def multitableinserts_sql(self, expression: sqlglot.expressions.MultitableInserts) -> str: View Source

    4230    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
    4231        kind = self.sql(expression, "kind")
    4232        expressions = self.seg(self.expressions(expression, sep=" "))
    4233        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
    4234        return res

def oncondition_sql(self, expression: sqlglot.expressions.OnCondition) -> str: View Source

    4236    def oncondition_sql(self, expression: exp.OnCondition) -> str:
    4237        # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR"
    4238        empty = expression.args.get("empty")
    4239        empty = (
    4240            f"DEFAULT {empty} ON EMPTY"
    4241            if isinstance(empty, exp.Expression)
    4242            else self.sql(expression, "empty")
    4243        )
    4244
    4245        error = expression.args.get("error")
    4246        error = (
    4247            f"DEFAULT {error} ON ERROR"
    4248            if isinstance(error, exp.Expression)
    4249            else self.sql(expression, "error")
    4250        )
    4251
    4252        if error and empty:
    4253            error = (
    4254                f"{empty} {error}"
    4255                if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR
    4256                else f"{error} {empty}"
    4257            )
    4258            empty = ""
    4259
    4260        null = self.sql(expression, "null")
    4261
    4262        return f"{empty}{error}{null}"

def jsonexists_sql(self, expression: sqlglot.expressions.JSONExists) -> str: View Source

    4264    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
    4265        this = self.sql(expression, "this")
    4266        path = self.sql(expression, "path")
    4267
    4268        passing = self.expressions(expression, "passing")
    4269        passing = f" PASSING {passing}" if passing else ""
    4270
    4271        on_condition = self.sql(expression, "on_condition")
    4272        on_condition = f" {on_condition}" if on_condition else ""
    4273
    4274        path = f"{path}{passing}{on_condition}"
    4275
    4276        return self.func("JSON_EXISTS", this, path)

def arrayagg_sql(self, expression: sqlglot.expressions.ArrayAgg) -> str: View Source

    4278    def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
    4279        array_agg = self.function_fallback_sql(expression)
    4280
    4281        if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"):
    4282            parent = expression.parent
    4283            if isinstance(parent, exp.Filter):
    4284                parent_cond = parent.expression.this
    4285                parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_()))
    4286            else:
    4287                array_agg = f"{array_agg} FILTER(WHERE {self.sql(expression, 'this')} IS NOT NULL)"
    4288
    4289        return array_agg