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

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

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

    578    def __init__(
    579        self,
    580        pretty: t.Optional[bool] = None,
    581        identify: str | bool = False,
    582        normalize: bool = False,
    583        pad: int = 2,
    584        indent: int = 2,
    585        normalize_functions: t.Optional[str | bool] = None,
    586        unsupported_level: ErrorLevel = ErrorLevel.WARN,
    587        max_unsupported: int = 3,
    588        leading_comma: bool = False,
    589        max_text_width: int = 80,
    590        comments: bool = True,
    591        dialect: DialectType = None,
    592    ):
    593        import sqlglot
    594        from sqlglot.dialects import Dialect
    595
    596        self.pretty = pretty if pretty is not None else sqlglot.pretty
    597        self.identify = identify
    598        self.normalize = normalize
    599        self.pad = pad
    600        self._indent = indent
    601        self.unsupported_level = unsupported_level
    602        self.max_unsupported = max_unsupported
    603        self.leading_comma = leading_comma
    604        self.max_text_width = max_text_width
    605        self.comments = comments
    606        self.dialect = Dialect.get_or_raise(dialect)
    607
    608        # This is both a Dialect property and a Generator argument, so we prioritize the latter
    609        self.normalize_functions = (
    610            self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
    611        )
    612
    613        self.unsupported_messages: t.List[str] = []
    614        self._escaped_quote_end: str = (
    615            self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END
    616        )
    617        self._escaped_identifier_end: str = (
    618            self.dialect.tokenizer_class.IDENTIFIER_ESCAPES[0] + self.dialect.IDENTIFIER_END
    619        )
    620
    621        self._next_name = name_sequence("_t")

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.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EphemeralColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExcludeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.GlobalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IcebergProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.JSONExtract'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.JSONExtractScalar'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.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.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.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.Timestamp'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.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
EXPLICIT_SET_OP = False
WRAP_DERIVED_VALUES = True
CREATE_FUNCTION_RETURN_AS = True
MATCHED_BY_SOURCE = True
SINGLE_STRING_INTERVAL = False
INTERVAL_ALLOWS_PLURAL_FORM = True
LIMIT_FETCH = 'ALL'
LIMIT_ONLY_LITERALS = False
RENAME_TABLE_WITH_DB = True
GROUPINGS_SEP = ','
INDEX_ON = 'ON'
JOIN_HINTS = True
TABLE_HINTS = True
QUERY_HINTS = True
QUERY_HINT_SEP = ', '
IS_BOOL_ALLOWED = True
DUPLICATE_KEY_UPDATE_WITH_SET = True
LIMIT_IS_TOP = False
RETURNING_END = True
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.JSONPathRoot'>, <class 'sqlglot.expressions.JSONPathRecursive'>, <class 'sqlglot.expressions.JSONPathKey'>, <class 'sqlglot.expressions.JSONPathWildcard'>, <class 'sqlglot.expressions.JSONPathFilter'>, <class 'sqlglot.expressions.JSONPathUnion'>, <class 'sqlglot.expressions.JSONPathSubscript'>, <class 'sqlglot.expressions.JSONPathSelector'>, <class 'sqlglot.expressions.JSONPathSlice'>, <class 'sqlglot.expressions.JSONPathScript'>}
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
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.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.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.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.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.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.CHAR: 'CHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.NCHAR: 'NCHAR'>}
EXPRESSIONS_WITHOUT_NESTED_CTES: Set[Type[sqlglot.expressions.Expression]] = set()
SENTINEL_LINE_BREAK = '__SQLGLOT__LB__'
pretty
identify
normalize
pad
unsupported_level
max_unsupported
leading_comma
max_text_width
comments
dialect
normalize_functions
unsupported_messages: List[str]
def generate( self, expression: sqlglot.expressions.Expression, copy: bool = True) -> str: View Source

    623    def generate(self, expression: exp.Expression, copy: bool = True) -> str:
    624        """
    625        Generates the SQL string corresponding to the given syntax tree.
    626
    627        Args:
    628            expression: The syntax tree.
    629            copy: Whether to copy the expression. The generator performs mutations so
    630                it is safer to copy.
    631
    632        Returns:
    633            The SQL string corresponding to `expression`.
    634        """
    635        if copy:
    636            expression = expression.copy()
    637
    638        expression = self.preprocess(expression)
    639
    640        self.unsupported_messages = []
    641        sql = self.sql(expression).strip()
    642
    643        if self.pretty:
    644            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
    645
    646        if self.unsupported_level == ErrorLevel.IGNORE:
    647            return sql
    648
    649        if self.unsupported_level == ErrorLevel.WARN:
    650            for msg in self.unsupported_messages:
    651                logger.warning(msg)
    652        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
    653            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
    654
    655        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

    657    def preprocess(self, expression: exp.Expression) -> exp.Expression:
    658        """Apply generic preprocessing transformations to a given expression."""
    659        if (
    660            not expression.parent
    661            and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES
    662            and any(node.parent is not expression for node in expression.find_all(exp.With))
    663        ):
    664            from sqlglot.transforms import move_ctes_to_top_level
    665
    666            expression = move_ctes_to_top_level(expression)
    667
    668        if self.ENSURE_BOOLS:
    669            from sqlglot.transforms import ensure_bools
    670
    671            expression = ensure_bools(expression)
    672
    673        return expression

Apply generic preprocessing transformations to a given expression.

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

    675    def unsupported(self, message: str) -> None:
    676        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    677            raise UnsupportedError(message)
    678        self.unsupported_messages.append(message)

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

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

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

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

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

    686    def pad_comment(self, comment: str) -> str:
    687        comment = " " + comment if comment[0].strip() else comment
    688        comment = comment + " " if comment[-1].strip() else comment
    689        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

    691    def maybe_comment(
    692        self,
    693        sql: str,
    694        expression: t.Optional[exp.Expression] = None,
    695        comments: t.Optional[t.List[str]] = None,
    696        separated: bool = False,
    697    ) -> str:
    698        comments = (
    699            ((expression and expression.comments) if comments is None else comments)  # type: ignore
    700            if self.comments
    701            else None
    702        )
    703
    704        if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
    705            return sql
    706
    707        comments_sql = " ".join(
    708            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
    709        )
    710
    711        if not comments_sql:
    712            return sql
    713
    714        comments_sql = self._replace_line_breaks(comments_sql)
    715
    716        if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS):
    717            return (
    718                f"{self.sep()}{comments_sql}{sql}"
    719                if not sql or sql[0].isspace()
    720                else f"{comments_sql}{self.sep()}{sql}"
    721            )
    722
    723        return f"{sql} {comments_sql}"

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

    725    def wrap(self, expression: exp.Expression | str) -> str:
    726        this_sql = (
    727            self.sql(expression)
    728            if isinstance(expression, exp.UNWRAPPED_QUERIES)
    729            else self.sql(expression, "this")
    730        )
    731        if not this_sql:
    732            return "()"
    733
    734        this_sql = self.indent(this_sql, level=1, pad=0)
    735        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"

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

    737    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    738        original = self.identify
    739        self.identify = False
    740        result = func(*args, **kwargs)
    741        self.identify = original
    742        return result

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

    744    def normalize_func(self, name: str) -> str:
    745        if self.normalize_functions == "upper" or self.normalize_functions is True:
    746            return name.upper()
    747        if self.normalize_functions == "lower":
    748            return name.lower()
    749        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

    751    def indent(
    752        self,
    753        sql: str,
    754        level: int = 0,
    755        pad: t.Optional[int] = None,
    756        skip_first: bool = False,
    757        skip_last: bool = False,
    758    ) -> str:
    759        if not self.pretty or not sql:
    760            return sql
    761
    762        pad = self.pad if pad is None else pad
    763        lines = sql.split("\n")
    764
    765        return "\n".join(
    766            (
    767                line
    768                if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
    769                else f"{' ' * (level * self._indent + pad)}{line}"
    770            )
    771            for i, line in enumerate(lines)
    772        )

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

    774    def sql(
    775        self,
    776        expression: t.Optional[str | exp.Expression],
    777        key: t.Optional[str] = None,
    778        comment: bool = True,
    779    ) -> str:
    780        if not expression:
    781            return ""
    782
    783        if isinstance(expression, str):
    784            return expression
    785
    786        if key:
    787            value = expression.args.get(key)
    788            if value:
    789                return self.sql(value)
    790            return ""
    791
    792        transform = self.TRANSFORMS.get(expression.__class__)
    793
    794        if callable(transform):
    795            sql = transform(self, expression)
    796        elif isinstance(expression, exp.Expression):
    797            exp_handler_name = f"{expression.key}_sql"
    798
    799            if hasattr(self, exp_handler_name):
    800                sql = getattr(self, exp_handler_name)(expression)
    801            elif isinstance(expression, exp.Func):
    802                sql = self.function_fallback_sql(expression)
    803            elif isinstance(expression, exp.Property):
    804                sql = self.property_sql(expression)
    805            else:
    806                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
    807        else:
    808            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
    809
    810        return self.maybe_comment(sql, expression) if self.comments and comment else sql

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

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

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

    817    def cache_sql(self, expression: exp.Cache) -> str:
    818        lazy = " LAZY" if expression.args.get("lazy") else ""
    819        table = self.sql(expression, "this")
    820        options = expression.args.get("options")
    821        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
    822        sql = self.sql(expression, "expression")
    823        sql = f" AS{self.sep()}{sql}" if sql else ""
    824        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
    825        return self.prepend_ctes(expression, sql)

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

    827    def characterset_sql(self, expression: exp.CharacterSet) -> str:
    828        if isinstance(expression.parent, exp.Cast):
    829            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
    830        default = "DEFAULT " if expression.args.get("default") else ""
    831        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"

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

    833    def column_parts(self, expression: exp.Column) -> str:
    834        return ".".join(
    835            self.sql(part)
    836            for part in (
    837                expression.args.get("catalog"),
    838                expression.args.get("db"),
    839                expression.args.get("table"),
    840                expression.args.get("this"),
    841            )
    842            if part
    843        )

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

    845    def column_sql(self, expression: exp.Column) -> str:
    846        join_mark = " (+)" if expression.args.get("join_mark") else ""
    847
    848        if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS:
    849            join_mark = ""
    850            self.unsupported("Outer join syntax using the (+) operator is not supported.")
    851
    852        return f"{self.column_parts(expression)}{join_mark}"

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

    854    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    855        this = self.sql(expression, "this")
    856        this = f" {this}" if this else ""
    857        position = self.sql(expression, "position")
    858        return f"{position}{this}"

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

    860    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
    861        column = self.sql(expression, "this")
    862        kind = self.sql(expression, "kind")
    863        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
    864        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
    865        kind = f"{sep}{kind}" if kind else ""
    866        constraints = f" {constraints}" if constraints else ""
    867        position = self.sql(expression, "position")
    868        position = f" {position}" if position else ""
    869
    870        if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:
    871            kind = ""
    872
    873        return f"{exists}{column}{kind}{constraints}{position}"

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

    875    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    876        this = self.sql(expression, "this")
    877        kind_sql = self.sql(expression, "kind").strip()
    878        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

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

    880    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
    881        this = self.sql(expression, "this")
    882        if expression.args.get("not_null"):
    883            persisted = " PERSISTED NOT NULL"
    884        elif expression.args.get("persisted"):
    885            persisted = " PERSISTED"
    886        else:
    887            persisted = ""
    888        return f"AS {this}{persisted}"

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

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

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

    893    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
    894        if isinstance(expression.this, list):
    895            this = self.wrap(self.expressions(expression, key="this", flat=True))
    896        else:
    897            this = self.sql(expression, "this")
    898
    899        return f"COMPRESS {this}"

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

    901    def generatedasidentitycolumnconstraint_sql(
    902        self, expression: exp.GeneratedAsIdentityColumnConstraint
    903    ) -> str:
    904        this = ""
    905        if expression.this is not None:
    906            on_null = " ON NULL" if expression.args.get("on_null") else ""
    907            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
    908
    909        start = expression.args.get("start")
    910        start = f"START WITH {start}" if start else ""
    911        increment = expression.args.get("increment")
    912        increment = f" INCREMENT BY {increment}" if increment else ""
    913        minvalue = expression.args.get("minvalue")
    914        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    915        maxvalue = expression.args.get("maxvalue")
    916        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    917        cycle = expression.args.get("cycle")
    918        cycle_sql = ""
    919
    920        if cycle is not None:
    921            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
    922            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
    923
    924        sequence_opts = ""
    925        if start or increment or cycle_sql:
    926            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
    927            sequence_opts = f" ({sequence_opts.strip()})"
    928
    929        expr = self.sql(expression, "expression")
    930        expr = f"({expr})" if expr else "IDENTITY"
    931
    932        return f"GENERATED{this} AS {expr}{sequence_opts}"

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

    934    def generatedasrowcolumnconstraint_sql(
    935        self, expression: exp.GeneratedAsRowColumnConstraint
    936    ) -> str:
    937        start = "START" if expression.args.get("start") else "END"
    938        hidden = " HIDDEN" if expression.args.get("hidden") else ""
    939        return f"GENERATED ALWAYS AS ROW {start}{hidden}"

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

    941    def periodforsystemtimeconstraint_sql(
    942        self, expression: exp.PeriodForSystemTimeConstraint
    943    ) -> str:
    944        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

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

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

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

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

    952    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    953        desc = expression.args.get("desc")
    954        if desc is not None:
    955            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    956        return "PRIMARY KEY"

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

    958    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    959        this = self.sql(expression, "this")
    960        this = f" {this}" if this else ""
    961        index_type = expression.args.get("index_type")
    962        index_type = f" USING {index_type}" if index_type else ""
    963        on_conflict = self.sql(expression, "on_conflict")
    964        on_conflict = f" {on_conflict}" if on_conflict else ""
    965        nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else ""
    966        return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}"

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

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

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

     971    def create_sql(self, expression: exp.Create) -> str:
     972        kind = self.sql(expression, "kind")
     973        properties = expression.args.get("properties")
     974        properties_locs = self.locate_properties(properties) if properties else defaultdict()
     975
     976        this = self.createable_sql(expression, properties_locs)
     977
     978        properties_sql = ""
     979        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
     980            exp.Properties.Location.POST_WITH
     981        ):
     982            properties_sql = self.sql(
     983                exp.Properties(
     984                    expressions=[
     985                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
     986                        *properties_locs[exp.Properties.Location.POST_WITH],
     987                    ]
     988                )
     989            )
     990
     991            if properties_locs.get(exp.Properties.Location.POST_SCHEMA):
     992                properties_sql = self.sep() + properties_sql
     993            elif not self.pretty:
     994                # Standalone POST_WITH properties need a leading whitespace in non-pretty mode
     995                properties_sql = f" {properties_sql}"
     996
     997        begin = " BEGIN" if expression.args.get("begin") else ""
     998        end = " END" if expression.args.get("end") else ""
     999
    1000        expression_sql = self.sql(expression, "expression")
    1001        if expression_sql:
    1002            expression_sql = f"{begin}{self.sep()}{expression_sql}{end}"
    1003
    1004            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
    1005                postalias_props_sql = ""
    1006                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
    1007                    postalias_props_sql = self.properties(
    1008                        exp.Properties(
    1009                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
    1010                        ),
    1011                        wrapped=False,
    1012                    )
    1013                postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else ""
    1014                expression_sql = f" AS{postalias_props_sql}{expression_sql}"
    1015
    1016        postindex_props_sql = ""
    1017        if properties_locs.get(exp.Properties.Location.POST_INDEX):
    1018            postindex_props_sql = self.properties(
    1019                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
    1020                wrapped=False,
    1021                prefix=" ",
    1022            )
    1023
    1024        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
    1025        indexes = f" {indexes}" if indexes else ""
    1026        index_sql = indexes + postindex_props_sql
    1027
    1028        replace = " OR REPLACE" if expression.args.get("replace") else ""
    1029        unique = " UNIQUE" if expression.args.get("unique") else ""
    1030
    1031        clustered = expression.args.get("clustered")
    1032        if clustered is None:
    1033            clustered_sql = ""
    1034        elif clustered:
    1035            clustered_sql = " CLUSTERED COLUMNSTORE"
    1036        else:
    1037            clustered_sql = " NONCLUSTERED COLUMNSTORE"
    1038
    1039        postcreate_props_sql = ""
    1040        if properties_locs.get(exp.Properties.Location.POST_CREATE):
    1041            postcreate_props_sql = self.properties(
    1042                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
    1043                sep=" ",
    1044                prefix=" ",
    1045                wrapped=False,
    1046            )
    1047
    1048        modifiers = "".join((clustered_sql, replace, unique, postcreate_props_sql))
    1049
    1050        postexpression_props_sql = ""
    1051        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
    1052            postexpression_props_sql = self.properties(
    1053                exp.Properties(
    1054                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
    1055                ),
    1056                sep=" ",
    1057                prefix=" ",
    1058                wrapped=False,
    1059            )
    1060
    1061        concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else ""
    1062        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    1063        no_schema_binding = (
    1064            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
    1065        )
    1066
    1067        clone = self.sql(expression, "clone")
    1068        clone = f" {clone}" if clone else ""
    1069
    1070        expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
    1071        return self.prepend_ctes(expression, expression_sql)

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

    1073    def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str:
    1074        start = self.sql(expression, "start")
    1075        start = f"START WITH {start}" if start else ""
    1076        increment = self.sql(expression, "increment")
    1077        increment = f" INCREMENT BY {increment}" if increment else ""
    1078        minvalue = self.sql(expression, "minvalue")
    1079        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    1080        maxvalue = self.sql(expression, "maxvalue")
    1081        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    1082        owned = self.sql(expression, "owned")
    1083        owned = f" OWNED BY {owned}" if owned else ""
    1084
    1085        cache = expression.args.get("cache")
    1086        if cache is None:
    1087            cache_str = ""
    1088        elif cache is True:
    1089            cache_str = " CACHE"
    1090        else:
    1091            cache_str = f" CACHE {cache}"
    1092
    1093        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1094        options = f" {options}" if options else ""
    1095
    1096        return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()

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

    1098    def clone_sql(self, expression: exp.Clone) -> str:
    1099        this = self.sql(expression, "this")
    1100        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    1101        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
    1102        return f"{shallow}{keyword} {this}"

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

    1104    def describe_sql(self, expression: exp.Describe) -> str:
    1105        style = expression.args.get("style")
    1106        style = f" {style}" if style else ""
    1107        return f"DESCRIBE{style} {self.sql(expression, 'this')}"

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

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

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

    1113    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    1114        with_ = self.sql(expression, "with")
    1115        if with_:
    1116            sql = f"{with_}{self.sep()}{sql}"
    1117        return sql

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

    1119    def with_sql(self, expression: exp.With) -> str:
    1120        sql = self.expressions(expression, flat=True)
    1121        recursive = (
    1122            "RECURSIVE "
    1123            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
    1124            else ""
    1125        )
    1126
    1127        return f"WITH {recursive}{sql}"

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

    1129    def cte_sql(self, expression: exp.CTE) -> str:
    1130        alias = self.sql(expression, "alias")
    1131
    1132        materialized = expression.args.get("materialized")
    1133        if materialized is False:
    1134            materialized = "NOT MATERIALIZED "
    1135        elif materialized:
    1136            materialized = "MATERIALIZED "
    1137
    1138        return f"{alias} AS {materialized or ''}{self.wrap(expression)}"

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

    1140    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    1141        alias = self.sql(expression, "this")
    1142        columns = self.expressions(expression, key="columns", flat=True)
    1143        columns = f"({columns})" if columns else ""
    1144
    1145        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
    1146            columns = ""
    1147            self.unsupported("Named columns are not supported in table alias.")
    1148
    1149        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
    1150            alias = self._next_name()
    1151
    1152        return f"{alias}{columns}"

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

    1154    def bitstring_sql(self, expression: exp.BitString) -> str:
    1155        this = self.sql(expression, "this")
    1156        if self.dialect.BIT_START:
    1157            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    1158        return f"{int(this, 2)}"

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

    1160    def hexstring_sql(self, expression: exp.HexString) -> str:
    1161        this = self.sql(expression, "this")
    1162        if self.dialect.HEX_START:
    1163            return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
    1164        return f"{int(this, 16)}"

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

    1166    def bytestring_sql(self, expression: exp.ByteString) -> str:
    1167        this = self.sql(expression, "this")
    1168        if self.dialect.BYTE_START:
    1169            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    1170        return this

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

    1172    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
    1173        this = self.sql(expression, "this")
    1174        escape = expression.args.get("escape")
    1175
    1176        if self.dialect.UNICODE_START:
    1177            escape_substitute = r"\\\1"
    1178            left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END
    1179        else:
    1180            escape_substitute = r"\\u\1"
    1181            left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END
    1182
    1183        if escape:
    1184            escape_pattern = re.compile(rf"{escape.name}(\d+)")
    1185            escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else ""
    1186        else:
    1187            escape_pattern = ESCAPED_UNICODE_RE
    1188            escape_sql = ""
    1189
    1190        if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE):
    1191            this = escape_pattern.sub(escape_substitute, this)
    1192
    1193        return f"{left_quote}{this}{right_quote}{escape_sql}"

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

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

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

    1199    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    1200        this = self.sql(expression, "this")
    1201        specifier = self.sql(expression, "expression")
    1202        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    1203        return f"{this}{specifier}"

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

    1205    def datatype_sql(self, expression: exp.DataType) -> str:
    1206        type_value = expression.this
    1207
    1208        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
    1209            type_sql = self.sql(expression, "kind")
    1210        else:
    1211            type_sql = (
    1212                self.TYPE_MAPPING.get(type_value, type_value.value)
    1213                if isinstance(type_value, exp.DataType.Type)
    1214                else type_value
    1215            )
    1216
    1217        nested = ""
    1218        interior = self.expressions(expression, flat=True)
    1219        values = ""
    1220
    1221        if interior:
    1222            if expression.args.get("nested"):
    1223                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    1224                if expression.args.get("values") is not None:
    1225                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    1226                    values = self.expressions(expression, key="values", flat=True)
    1227                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    1228            elif type_value == exp.DataType.Type.INTERVAL:
    1229                nested = f" {interior}"
    1230            else:
    1231                nested = f"({interior})"
    1232
    1233        type_sql = f"{type_sql}{nested}{values}"
    1234        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
    1235            exp.DataType.Type.TIMETZ,
    1236            exp.DataType.Type.TIMESTAMPTZ,
    1237        ):
    1238            type_sql = f"{type_sql} WITH TIME ZONE"
    1239
    1240        return type_sql

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

    1242    def directory_sql(self, expression: exp.Directory) -> str:
    1243        local = "LOCAL " if expression.args.get("local") else ""
    1244        row_format = self.sql(expression, "row_format")
    1245        row_format = f" {row_format}" if row_format else ""
    1246        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

    1248    def delete_sql(self, expression: exp.Delete) -> str:
    1249        this = self.sql(expression, "this")
    1250        this = f" FROM {this}" if this else ""
    1251        using = self.sql(expression, "using")
    1252        using = f" USING {using}" if using else ""
    1253        where = self.sql(expression, "where")
    1254        returning = self.sql(expression, "returning")
    1255        limit = self.sql(expression, "limit")
    1256        tables = self.expressions(expression, key="tables")
    1257        tables = f" {tables}" if tables else ""
    1258        if self.RETURNING_END:
    1259            expression_sql = f"{this}{using}{where}{returning}{limit}"
    1260        else:
    1261            expression_sql = f"{returning}{this}{using}{where}{limit}"
    1262        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

    1264    def drop_sql(self, expression: exp.Drop) -> str:
    1265        this = self.sql(expression, "this")
    1266        expressions = self.expressions(expression, flat=True)
    1267        expressions = f" ({expressions})" if expressions else ""
    1268        kind = expression.args["kind"]
    1269        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    1270        on_cluster = self.sql(expression, "cluster")
    1271        on_cluster = f" {on_cluster}" if on_cluster else ""
    1272        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1273        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    1274        cascade = " CASCADE" if expression.args.get("cascade") else ""
    1275        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    1276        purge = " PURGE" if expression.args.get("purge") else ""
    1277        return f"DROP{temporary}{materialized} {kind}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}"

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

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

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

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

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

    1285    def fetch_sql(self, expression: exp.Fetch) -> str:
    1286        direction = expression.args.get("direction")
    1287        direction = f" {direction}" if direction else ""
    1288        count = expression.args.get("count")
    1289        count = f" {count}" if count else ""
    1290        if expression.args.get("percent"):
    1291            count = f"{count} PERCENT"
    1292        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    1293        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"

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

    1295    def filter_sql(self, expression: exp.Filter) -> str:
    1296        if self.AGGREGATE_FILTER_SUPPORTED:
    1297            this = self.sql(expression, "this")
    1298            where = self.sql(expression, "expression").strip()
    1299            return f"{this} FILTER({where})"
    1300
    1301        agg = expression.this
    1302        agg_arg = agg.this
    1303        cond = expression.expression.this
    1304        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1305        return self.sql(agg)

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

    1307    def hint_sql(self, expression: exp.Hint) -> str:
    1308        if not self.QUERY_HINTS:
    1309            self.unsupported("Hints are not supported")
    1310            return ""
    1311
    1312        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

    1314    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
    1315        using = self.sql(expression, "using")
    1316        using = f" USING {using}" if using else ""
    1317        columns = self.expressions(expression, key="columns", flat=True)
    1318        columns = f"({columns})" if columns else ""
    1319        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1320        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1321        where = self.sql(expression, "where")
    1322        include = self.expressions(expression, key="include", flat=True)
    1323        if include:
    1324            include = f" INCLUDE ({include})"
    1325        with_storage = self.expressions(expression, key="with_storage", flat=True)
    1326        with_storage = f" WITH ({with_storage})" if with_storage else ""
    1327        tablespace = self.sql(expression, "tablespace")
    1328        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
    1329        on = self.sql(expression, "on")
    1330        on = f" ON {on}" if on else ""
    1331
    1332        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"

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

    1334    def index_sql(self, expression: exp.Index) -> str:
    1335        unique = "UNIQUE " if expression.args.get("unique") else ""
    1336        primary = "PRIMARY " if expression.args.get("primary") else ""
    1337        amp = "AMP " if expression.args.get("amp") else ""
    1338        name = self.sql(expression, "this")
    1339        name = f"{name} " if name else ""
    1340        table = self.sql(expression, "table")
    1341        table = f"{self.INDEX_ON} {table}" if table else ""
    1342
    1343        index = "INDEX " if not table else ""
    1344
    1345        params = self.sql(expression, "params")
    1346        return f"{unique}{primary}{amp}{index}{name}{table}{params}"

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

    1348    def identifier_sql(self, expression: exp.Identifier) -> str:
    1349        text = expression.name
    1350        lower = text.lower()
    1351        text = lower if self.normalize and not expression.quoted else text
    1352        text = text.replace(self.dialect.IDENTIFIER_END, self._escaped_identifier_end)
    1353        if (
    1354            expression.quoted
    1355            or self.dialect.can_identify(text, self.identify)
    1356            or lower in self.RESERVED_KEYWORDS
    1357            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1358        ):
    1359            text = f"{self.dialect.IDENTIFIER_START}{text}{self.dialect.IDENTIFIER_END}"
    1360        return text

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

    1362    def hex_sql(self, expression: exp.Hex) -> str:
    1363        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1364        if self.dialect.HEX_LOWERCASE:
    1365            text = self.func("LOWER", text)
    1366
    1367        return text

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

    1369    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
    1370        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1371        if not self.dialect.HEX_LOWERCASE:
    1372            text = self.func("LOWER", text)
    1373        return text

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

    1375    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1376        input_format = self.sql(expression, "input_format")
    1377        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1378        output_format = self.sql(expression, "output_format")
    1379        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1380        return self.sep().join((input_format, output_format))

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

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

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

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

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

    1389    def properties_sql(self, expression: exp.Properties) -> str:
    1390        root_properties = []
    1391        with_properties = []
    1392
    1393        for p in expression.expressions:
    1394            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1395            if p_loc == exp.Properties.Location.POST_WITH:
    1396                with_properties.append(p)
    1397            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1398                root_properties.append(p)
    1399
    1400        root_props = self.root_properties(exp.Properties(expressions=root_properties))
    1401        with_props = self.with_properties(exp.Properties(expressions=with_properties))
    1402
    1403        if root_props and with_props and not self.pretty:
    1404            with_props = " " + with_props
    1405
    1406        return root_props + with_props

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

    1408    def root_properties(self, properties: exp.Properties) -> str:
    1409        if properties.expressions:
    1410            return self.expressions(properties, indent=False, sep=" ")
    1411        return ""

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

    1413    def properties(
    1414        self,
    1415        properties: exp.Properties,
    1416        prefix: str = "",
    1417        sep: str = ", ",
    1418        suffix: str = "",
    1419        wrapped: bool = True,
    1420    ) -> str:
    1421        if properties.expressions:
    1422            expressions = self.expressions(properties, sep=sep, indent=False)
    1423            if expressions:
    1424                expressions = self.wrap(expressions) if wrapped else expressions
    1425                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1426        return ""

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

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

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

    1431    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1432        properties_locs = defaultdict(list)
    1433        for p in properties.expressions:
    1434            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1435            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1436                properties_locs[p_loc].append(p)
    1437            else:
    1438                self.unsupported(f"Unsupported property {p.key}")
    1439
    1440        return properties_locs

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

    1442    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1443        if isinstance(expression.this, exp.Dot):
    1444            return self.sql(expression, "this")
    1445        return f"'{expression.name}'" if string_key else expression.name

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

    1447    def property_sql(self, expression: exp.Property) -> str:
    1448        property_cls = expression.__class__
    1449        if property_cls == exp.Property:
    1450            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1451
    1452        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1453        if not property_name:
    1454            self.unsupported(f"Unsupported property {expression.key}")
    1455
    1456        return f"{property_name}={self.sql(expression, 'this')}"

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

    1458    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1459        if self.SUPPORTS_CREATE_TABLE_LIKE:
    1460            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1461            options = f" {options}" if options else ""
    1462
    1463            like = f"LIKE {self.sql(expression, 'this')}{options}"
    1464            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
    1465                like = f"({like})"
    1466
    1467            return like
    1468
    1469        if expression.expressions:
    1470            self.unsupported("Transpilation of LIKE property options is unsupported")
    1471
    1472        select = exp.select("*").from_(expression.this).limit(0)
    1473        return f"AS {self.sql(select)}"

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

    1475    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1476        no = "NO " if expression.args.get("no") else ""
    1477        protection = " PROTECTION" if expression.args.get("protection") else ""
    1478        return f"{no}FALLBACK{protection}"

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

    1480    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1481        no = "NO " if expression.args.get("no") else ""
    1482        local = expression.args.get("local")
    1483        local = f"{local} " if local else ""
    1484        dual = "DUAL " if expression.args.get("dual") else ""
    1485        before = "BEFORE " if expression.args.get("before") else ""
    1486        after = "AFTER " if expression.args.get("after") else ""
    1487        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1489    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1490        freespace = self.sql(expression, "this")
    1491        percent = " PERCENT" if expression.args.get("percent") else ""
    1492        return f"FREESPACE={freespace}{percent}"

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

    1494    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1495        if expression.args.get("default"):
    1496            property = "DEFAULT"
    1497        elif expression.args.get("on"):
    1498            property = "ON"
    1499        else:
    1500            property = "OFF"
    1501        return f"CHECKSUM={property}"

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

    1503    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1504        if expression.args.get("no"):
    1505            return "NO MERGEBLOCKRATIO"
    1506        if expression.args.get("default"):
    1507            return "DEFAULT MERGEBLOCKRATIO"
    1508
    1509        percent = " PERCENT" if expression.args.get("percent") else ""
    1510        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1512    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1513        default = expression.args.get("default")
    1514        minimum = expression.args.get("minimum")
    1515        maximum = expression.args.get("maximum")
    1516        if default or minimum or maximum:
    1517            if default:
    1518                prop = "DEFAULT"
    1519            elif minimum:
    1520                prop = "MINIMUM"
    1521            else:
    1522                prop = "MAXIMUM"
    1523            return f"{prop} DATABLOCKSIZE"
    1524        units = expression.args.get("units")
    1525        units = f" {units}" if units else ""
    1526        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1528    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1529        autotemp = expression.args.get("autotemp")
    1530        always = expression.args.get("always")
    1531        default = expression.args.get("default")
    1532        manual = expression.args.get("manual")
    1533        never = expression.args.get("never")
    1534
    1535        if autotemp is not None:
    1536            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1537        elif always:
    1538            prop = "ALWAYS"
    1539        elif default:
    1540            prop = "DEFAULT"
    1541        elif manual:
    1542            prop = "MANUAL"
    1543        elif never:
    1544            prop = "NEVER"
    1545        return f"BLOCKCOMPRESSION={prop}"

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

    1547    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1548        no = expression.args.get("no")
    1549        no = " NO" if no else ""
    1550        concurrent = expression.args.get("concurrent")
    1551        concurrent = " CONCURRENT" if concurrent else ""
    1552        target = self.sql(expression, "target")
    1553        target = f" {target}" if target else ""
    1554        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"

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

    1556    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1557        if isinstance(expression.this, list):
    1558            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1559        if expression.this:
    1560            modulus = self.sql(expression, "this")
    1561            remainder = self.sql(expression, "expression")
    1562            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1563
    1564        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1565        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1566        return f"FROM ({from_expressions}) TO ({to_expressions})"

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

    1568    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1569        this = self.sql(expression, "this")
    1570
    1571        for_values_or_default = expression.expression
    1572        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1573            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1574        else:
    1575            for_values_or_default = " DEFAULT"
    1576
    1577        return f"PARTITION OF {this}{for_values_or_default}"

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

    1579    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1580        kind = expression.args.get("kind")
    1581        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1582        for_or_in = expression.args.get("for_or_in")
    1583        for_or_in = f" {for_or_in}" if for_or_in else ""
    1584        lock_type = expression.args.get("lock_type")
    1585        override = " OVERRIDE" if expression.args.get("override") else ""
    1586        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"

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

    1588    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1589        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1590        statistics = expression.args.get("statistics")
    1591        statistics_sql = ""
    1592        if statistics is not None:
    1593            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1594        return f"{data_sql}{statistics_sql}"

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

    1596    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1597        this = self.sql(expression, "this")
    1598        this = f"HISTORY_TABLE={this}" if this else ""
    1599        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
    1600        data_consistency = (
    1601            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
    1602        )
    1603        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    1604        retention_period = (
    1605            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
    1606        )
    1607
    1608        if this:
    1609            on_sql = self.func("ON", this, data_consistency, retention_period)
    1610        else:
    1611            on_sql = "ON" if expression.args.get("on") else "OFF"
    1612
    1613        sql = f"SYSTEM_VERSIONING={on_sql}"
    1614
    1615        return f"WITH({sql})" if expression.args.get("with") else sql

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

    1617    def insert_sql(self, expression: exp.Insert) -> str:
    1618        hint = self.sql(expression, "hint")
    1619        overwrite = expression.args.get("overwrite")
    1620
    1621        if isinstance(expression.this, exp.Directory):
    1622            this = " OVERWRITE" if overwrite else " INTO"
    1623        else:
    1624            this = self.INSERT_OVERWRITE if overwrite else " INTO"
    1625
    1626        stored = self.sql(expression, "stored")
    1627        stored = f" {stored}" if stored else ""
    1628        alternative = expression.args.get("alternative")
    1629        alternative = f" OR {alternative}" if alternative else ""
    1630        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1631        is_function = expression.args.get("is_function")
    1632        if is_function:
    1633            this = f"{this} FUNCTION"
    1634        this = f"{this} {self.sql(expression, 'this')}"
    1635
    1636        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1637        where = self.sql(expression, "where")
    1638        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1639        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1640        on_conflict = self.sql(expression, "conflict")
    1641        on_conflict = f" {on_conflict}" if on_conflict else ""
    1642        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1643        returning = self.sql(expression, "returning")
    1644
    1645        if self.RETURNING_END:
    1646            expression_sql = f"{expression_sql}{on_conflict}{returning}"
    1647        else:
    1648            expression_sql = f"{returning}{expression_sql}{on_conflict}"
    1649
    1650        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{where}{expression_sql}"
    1651        return self.prepend_ctes(expression, sql)

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

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

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

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

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

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

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

    1662    def kill_sql(self, expression: exp.Kill) -> str:
    1663        kind = self.sql(expression, "kind")
    1664        kind = f" {kind}" if kind else ""
    1665        this = self.sql(expression, "this")
    1666        this = f" {this}" if this else ""
    1667        return f"KILL{kind}{this}"

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

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

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

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

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

    1675    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1676        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1677
    1678        constraint = self.sql(expression, "constraint")
    1679        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
    1680
    1681        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
    1682        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
    1683        action = self.sql(expression, "action")
    1684
    1685        expressions = self.expressions(expression, flat=True)
    1686        if expressions:
    1687            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1688            expressions = f" {set_keyword}{expressions}"
    1689
    1690        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}"

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

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

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

    1695    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1696        fields = self.sql(expression, "fields")
    1697        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1698        escaped = self.sql(expression, "escaped")
    1699        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1700        items = self.sql(expression, "collection_items")
    1701        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1702        keys = self.sql(expression, "map_keys")
    1703        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1704        lines = self.sql(expression, "lines")
    1705        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1706        null = self.sql(expression, "null")
    1707        null = f" NULL DEFINED AS {null}" if null else ""
    1708        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1713    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1714        this = f"{self.sql(expression, 'this')} INDEX"
    1715        target = self.sql(expression, "target")
    1716        target = f" FOR {target}" if target else ""
    1717        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1719    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1720        this = self.sql(expression, "this")
    1721        kind = self.sql(expression, "kind")
    1722        expr = self.sql(expression, "expression")
    1723        return f"{this} ({kind} => {expr})"

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

    1725    def table_parts(self, expression: exp.Table) -> str:
    1726        return ".".join(
    1727            self.sql(part)
    1728            for part in (
    1729                expression.args.get("catalog"),
    1730                expression.args.get("db"),
    1731                expression.args.get("this"),
    1732            )
    1733            if part is not None
    1734        )

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

    1736    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1737        table = self.table_parts(expression)
    1738        only = "ONLY " if expression.args.get("only") else ""
    1739        partition = self.sql(expression, "partition")
    1740        partition = f" {partition}" if partition else ""
    1741        version = self.sql(expression, "version")
    1742        version = f" {version}" if version else ""
    1743        alias = self.sql(expression, "alias")
    1744        alias = f"{sep}{alias}" if alias else ""
    1745        hints = self.expressions(expression, key="hints", sep=" ")
    1746        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1747        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    1748        joins = self.indent(
    1749            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    1750        )
    1751        laterals = self.expressions(expression, key="laterals", sep="")
    1752
    1753        file_format = self.sql(expression, "format")
    1754        if file_format:
    1755            pattern = self.sql(expression, "pattern")
    1756            pattern = f", PATTERN => {pattern}" if pattern else ""
    1757            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    1758
    1759        ordinality = expression.args.get("ordinality") or ""
    1760        if ordinality:
    1761            ordinality = f" WITH ORDINALITY{alias}"
    1762            alias = ""
    1763
    1764        when = self.sql(expression, "when")
    1765        if when:
    1766            table = f"{table} {when}"
    1767
    1768        changes = self.sql(expression, "changes")
    1769        changes = f" {changes}" if changes else ""
    1770
    1771        rows_from = self.expressions(expression, key="rows_from")
    1772        if rows_from:
    1773            table = f"ROWS FROM {self.wrap(rows_from)}"
    1774
    1775        return f"{only}{table}{changes}{partition}{version}{file_format}{alias}{hints}{pivots}{joins}{laterals}{ordinality}"

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

    1777    def tablesample_sql(
    1778        self,
    1779        expression: exp.TableSample,
    1780        sep: str = " AS ",
    1781        tablesample_keyword: t.Optional[str] = None,
    1782    ) -> str:
    1783        if self.dialect.ALIAS_POST_TABLESAMPLE and expression.this and expression.this.alias:
    1784            table = expression.this.copy()
    1785            table.set("alias", None)
    1786            this = self.sql(table)
    1787            alias = f"{sep}{self.sql(expression.this, 'alias')}"
    1788        else:
    1789            this = self.sql(expression, "this")
    1790            alias = ""
    1791
    1792        method = self.sql(expression, "method")
    1793        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1794        numerator = self.sql(expression, "bucket_numerator")
    1795        denominator = self.sql(expression, "bucket_denominator")
    1796        field = self.sql(expression, "bucket_field")
    1797        field = f" ON {field}" if field else ""
    1798        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1799        seed = self.sql(expression, "seed")
    1800        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
    1801
    1802        size = self.sql(expression, "size")
    1803        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
    1804            size = f"{size} ROWS"
    1805
    1806        percent = self.sql(expression, "percent")
    1807        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
    1808            percent = f"{percent} PERCENT"
    1809
    1810        expr = f"{bucket}{percent}{size}"
    1811        if self.TABLESAMPLE_REQUIRES_PARENS:
    1812            expr = f"({expr})"
    1813
    1814        return (
    1815            f"{this} {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}{alias}"
    1816        )

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

    1818    def pivot_sql(self, expression: exp.Pivot) -> str:
    1819        expressions = self.expressions(expression, flat=True)
    1820
    1821        if expression.this:
    1822            this = self.sql(expression, "this")
    1823            if not expressions:
    1824                return f"UNPIVOT {this}"
    1825
    1826            on = f"{self.seg('ON')} {expressions}"
    1827            using = self.expressions(expression, key="using", flat=True)
    1828            using = f"{self.seg('USING')} {using}" if using else ""
    1829            group = self.sql(expression, "group")
    1830            return f"PIVOT {this}{on}{using}{group}"
    1831
    1832        alias = self.sql(expression, "alias")
    1833        alias = f" AS {alias}" if alias else ""
    1834        direction = self.seg("UNPIVOT" if expression.unpivot else "PIVOT")
    1835        field = self.sql(expression, "field")
    1836        include_nulls = expression.args.get("include_nulls")
    1837        if include_nulls is not None:
    1838            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    1839        else:
    1840            nulls = ""
    1841        return f"{direction}{nulls}({expressions} FOR {field}){alias}"

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

    1843    def version_sql(self, expression: exp.Version) -> str:
    1844        this = f"FOR {expression.name}"
    1845        kind = expression.text("kind")
    1846        expr = self.sql(expression, "expression")
    1847        return f"{this} {kind} {expr}"

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

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

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

    1852    def update_sql(self, expression: exp.Update) -> str:
    1853        this = self.sql(expression, "this")
    1854        set_sql = self.expressions(expression, flat=True)
    1855        from_sql = self.sql(expression, "from")
    1856        where_sql = self.sql(expression, "where")
    1857        returning = self.sql(expression, "returning")
    1858        order = self.sql(expression, "order")
    1859        limit = self.sql(expression, "limit")
    1860        if self.RETURNING_END:
    1861            expression_sql = f"{from_sql}{where_sql}{returning}"
    1862        else:
    1863            expression_sql = f"{returning}{from_sql}{where_sql}"
    1864        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    1865        return self.prepend_ctes(expression, sql)

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

    1867    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
    1868        values_as_table = values_as_table and self.VALUES_AS_TABLE
    1869
    1870        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    1871        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
    1872            args = self.expressions(expression)
    1873            alias = self.sql(expression, "alias")
    1874            values = f"VALUES{self.seg('')}{args}"
    1875            values = (
    1876                f"({values})"
    1877                if self.WRAP_DERIVED_VALUES and (alias or isinstance(expression.parent, exp.From))
    1878                else values
    1879            )
    1880            return f"{values} AS {alias}" if alias else values
    1881
    1882        # Converts `VALUES...` expression into a series of select unions.
    1883        alias_node = expression.args.get("alias")
    1884        column_names = alias_node and alias_node.columns
    1885
    1886        selects: t.List[exp.Query] = []
    1887
    1888        for i, tup in enumerate(expression.expressions):
    1889            row = tup.expressions
    1890
    1891            if i == 0 and column_names:
    1892                row = [
    1893                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    1894                ]
    1895
    1896            selects.append(exp.Select(expressions=row))
    1897
    1898        if self.pretty:
    1899            # This may result in poor performance for large-cardinality `VALUES` tables, due to
    1900            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
    1901            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
    1902            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
    1903            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
    1904
    1905        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
    1906        unions = " UNION ALL ".join(self.sql(select) for select in selects)
    1907        return f"({unions}){alias}"

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

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

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

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

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

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

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

    1920    def group_sql(self, expression: exp.Group) -> str:
    1921        group_by_all = expression.args.get("all")
    1922        if group_by_all is True:
    1923            modifier = " ALL"
    1924        elif group_by_all is False:
    1925            modifier = " DISTINCT"
    1926        else:
    1927            modifier = ""
    1928
    1929        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
    1930
    1931        grouping_sets = self.expressions(expression, key="grouping_sets", indent=False)
    1932        grouping_sets = (
    1933            f"{self.seg('GROUPING SETS')} {self.wrap(grouping_sets)}" if grouping_sets else ""
    1934        )
    1935
    1936        cube = expression.args.get("cube", [])
    1937        if seq_get(cube, 0) is True:
    1938            return f"{group_by}{self.seg('WITH CUBE')}"
    1939        else:
    1940            cube_sql = self.expressions(expression, key="cube", indent=False)
    1941            cube_sql = f"{self.seg('CUBE')} {self.wrap(cube_sql)}" if cube_sql else ""
    1942
    1943        rollup = expression.args.get("rollup", [])
    1944        if seq_get(rollup, 0) is True:
    1945            return f"{group_by}{self.seg('WITH ROLLUP')}"
    1946        else:
    1947            rollup_sql = self.expressions(expression, key="rollup", indent=False)
    1948            rollup_sql = f"{self.seg('ROLLUP')} {self.wrap(rollup_sql)}" if rollup_sql else ""
    1949
    1950        groupings = csv(
    1951            grouping_sets,
    1952            cube_sql,
    1953            rollup_sql,
    1954            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    1955            sep=self.GROUPINGS_SEP,
    1956        )
    1957
    1958        if expression.args.get("expressions") and groupings:
    1959            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    1960
    1961        return f"{group_by}{groupings}"

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

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

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

    1967    def connect_sql(self, expression: exp.Connect) -> str:
    1968        start = self.sql(expression, "start")
    1969        start = self.seg(f"START WITH {start}") if start else ""
    1970        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
    1971        connect = self.sql(expression, "connect")
    1972        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
    1973        return start + connect

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

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

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

    1978    def join_sql(self, expression: exp.Join) -> str:
    1979        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    1980            side = None
    1981        else:
    1982            side = expression.side
    1983
    1984        op_sql = " ".join(
    1985            op
    1986            for op in (
    1987                expression.method,
    1988                "GLOBAL" if expression.args.get("global") else None,
    1989                side,
    1990                expression.kind,
    1991                expression.hint if self.JOIN_HINTS else None,
    1992            )
    1993            if op
    1994        )
    1995        match_cond = self.sql(expression, "match_condition")
    1996        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
    1997        on_sql = self.sql(expression, "on")
    1998        using = expression.args.get("using")
    1999
    2000        if not on_sql and using:
    2001            on_sql = csv(*(self.sql(column) for column in using))
    2002
    2003        this = expression.this
    2004        this_sql = self.sql(this)
    2005
    2006        if on_sql:
    2007            on_sql = self.indent(on_sql, skip_first=True)
    2008            space = self.seg(" " * self.pad) if self.pretty else " "
    2009            if using:
    2010                on_sql = f"{space}USING ({on_sql})"
    2011            else:
    2012                on_sql = f"{space}ON {on_sql}"
    2013        elif not op_sql:
    2014            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
    2015                return f" {this_sql}"
    2016
    2017            return f", {this_sql}"
    2018
    2019        if op_sql != "STRAIGHT_JOIN":
    2020            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    2021
    2022        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

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

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

    2029    def lateral_op(self, expression: exp.Lateral) -> str:
    2030        cross_apply = expression.args.get("cross_apply")
    2031
    2032        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    2033        if cross_apply is True:
    2034            op = "INNER JOIN "
    2035        elif cross_apply is False:
    2036            op = "LEFT JOIN "
    2037        else:
    2038            op = ""
    2039
    2040        return f"{op}LATERAL"

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

    2042    def lateral_sql(self, expression: exp.Lateral) -> str:
    2043        this = self.sql(expression, "this")
    2044
    2045        if expression.args.get("view"):
    2046            alias = expression.args["alias"]
    2047            columns = self.expressions(alias, key="columns", flat=True)
    2048            table = f" {alias.name}" if alias.name else ""
    2049            columns = f" AS {columns}" if columns else ""
    2050            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    2051            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    2052
    2053        alias = self.sql(expression, "alias")
    2054        alias = f" AS {alias}" if alias else ""
    2055        return f"{self.lateral_op(expression)} {this}{alias}"

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

    2057    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    2058        this = self.sql(expression, "this")
    2059
    2060        args = [
    2061            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    2062            for e in (expression.args.get(k) for k in ("offset", "expression"))
    2063            if e
    2064        ]
    2065
    2066        args_sql = ", ".join(self.sql(e) for e in args)
    2067        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
    2068        expressions = self.expressions(expression, flat=True)
    2069        expressions = f" BY {expressions}" if expressions else ""
    2070
    2071        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}"

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

    2073    def offset_sql(self, expression: exp.Offset) -> str:
    2074        this = self.sql(expression, "this")
    2075        value = expression.expression
    2076        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    2077        expressions = self.expressions(expression, flat=True)
    2078        expressions = f" BY {expressions}" if expressions else ""
    2079        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"

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

    2081    def setitem_sql(self, expression: exp.SetItem) -> str:
    2082        kind = self.sql(expression, "kind")
    2083        kind = f"{kind} " if kind else ""
    2084        this = self.sql(expression, "this")
    2085        expressions = self.expressions(expression)
    2086        collate = self.sql(expression, "collate")
    2087        collate = f" COLLATE {collate}" if collate else ""
    2088        global_ = "GLOBAL " if expression.args.get("global") else ""
    2089        return f"{global_}{kind}{this}{expressions}{collate}"

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

    2091    def set_sql(self, expression: exp.Set) -> str:
    2092        expressions = (
    2093            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    2094        )
    2095        tag = " TAG" if expression.args.get("tag") else ""
    2096        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"

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

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

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

    2101    def lock_sql(self, expression: exp.Lock) -> str:
    2102        if not self.LOCKING_READS_SUPPORTED:
    2103            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    2104            return ""
    2105
    2106        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    2107        expressions = self.expressions(expression, flat=True)
    2108        expressions = f" OF {expressions}" if expressions else ""
    2109        wait = expression.args.get("wait")
    2110
    2111        if wait is not None:
    2112            if isinstance(wait, exp.Literal):
    2113                wait = f" WAIT {self.sql(wait)}"
    2114            else:
    2115                wait = " NOWAIT" if wait else " SKIP LOCKED"
    2116
    2117        return f"{lock_type}{expressions}{wait or ''}"

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

    2119    def literal_sql(self, expression: exp.Literal) -> str:
    2120        text = expression.this or ""
    2121        if expression.is_string:
    2122            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    2123        return text

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

    2125    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
    2126        if self.dialect.ESCAPED_SEQUENCES:
    2127            to_escaped = self.dialect.ESCAPED_SEQUENCES
    2128            text = "".join(
    2129                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
    2130            )
    2131
    2132        return self._replace_line_breaks(text).replace(
    2133            self.dialect.QUOTE_END, self._escaped_quote_end
    2134        )

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

    2136    def loaddata_sql(self, expression: exp.LoadData) -> str:
    2137        local = " LOCAL" if expression.args.get("local") else ""
    2138        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    2139        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    2140        this = f" INTO TABLE {self.sql(expression, 'this')}"
    2141        partition = self.sql(expression, "partition")
    2142        partition = f" {partition}" if partition else ""
    2143        input_format = self.sql(expression, "input_format")
    2144        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    2145        serde = self.sql(expression, "serde")
    2146        serde = f" SERDE {serde}" if serde else ""
    2147        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    2149    def null_sql(self, *_) -> str:
    2150        return "NULL"

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

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

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

    2155    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2156        this = self.sql(expression, "this")
    2157        this = f"{this} " if this else this
    2158        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2159        order = self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat)  # type: ignore
    2160        interpolated_values = [
    2161            f"{self.sql(named_expression, 'alias')} AS {self.sql(named_expression, 'this')}"
    2162            for named_expression in expression.args.get("interpolate") or []
    2163        ]
    2164        interpolate = (
    2165            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    2166        )
    2167        return f"{order}{interpolate}"

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

    2169    def withfill_sql(self, expression: exp.WithFill) -> str:
    2170        from_sql = self.sql(expression, "from")
    2171        from_sql = f" FROM {from_sql}" if from_sql else ""
    2172        to_sql = self.sql(expression, "to")
    2173        to_sql = f" TO {to_sql}" if to_sql else ""
    2174        step_sql = self.sql(expression, "step")
    2175        step_sql = f" STEP {step_sql}" if step_sql else ""
    2176        return f"WITH FILL{from_sql}{to_sql}{step_sql}"

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

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

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

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

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

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

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

    2187    def ordered_sql(self, expression: exp.Ordered) -> str:
    2188        desc = expression.args.get("desc")
    2189        asc = not desc
    2190
    2191        nulls_first = expression.args.get("nulls_first")
    2192        nulls_last = not nulls_first
    2193        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
    2194        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
    2195        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
    2196
    2197        this = self.sql(expression, "this")
    2198
    2199        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
    2200        nulls_sort_change = ""
    2201        if nulls_first and (
    2202            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    2203        ):
    2204            nulls_sort_change = " NULLS FIRST"
    2205        elif (
    2206            nulls_last
    2207            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    2208            and not nulls_are_last
    2209        ):
    2210            nulls_sort_change = " NULLS LAST"
    2211
    2212        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
    2213        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    2214            window = expression.find_ancestor(exp.Window, exp.Select)
    2215            if isinstance(window, exp.Window) and window.args.get("spec"):
    2216                self.unsupported(
    2217                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
    2218                )
    2219                nulls_sort_change = ""
    2220            elif self.NULL_ORDERING_SUPPORTED is None:
    2221                if expression.this.is_int:
    2222                    self.unsupported(
    2223                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
    2224                    )
    2225                elif not isinstance(expression.this, exp.Rand):
    2226                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
    2227                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
    2228                nulls_sort_change = ""
    2229
    2230        with_fill = self.sql(expression, "with_fill")
    2231        with_fill = f" {with_fill}" if with_fill else ""
    2232
    2233        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"

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

    2235    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
    2236        window_frame = self.sql(expression, "window_frame")
    2237        window_frame = f"{window_frame} " if window_frame else ""
    2238
    2239        this = self.sql(expression, "this")
    2240
    2241        return f"{window_frame}{this}"

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

    2243    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    2244        partition = self.partition_by_sql(expression)
    2245        order = self.sql(expression, "order")
    2246        measures = self.expressions(expression, key="measures")
    2247        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    2248        rows = self.sql(expression, "rows")
    2249        rows = self.seg(rows) if rows else ""
    2250        after = self.sql(expression, "after")
    2251        after = self.seg(after) if after else ""
    2252        pattern = self.sql(expression, "pattern")
    2253        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    2254        definition_sqls = [
    2255            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    2256            for definition in expression.args.get("define", [])
    2257        ]
    2258        definitions = self.expressions(sqls=definition_sqls)
    2259        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    2260        body = "".join(
    2261            (
    2262                partition,
    2263                order,
    2264                measures,
    2265                rows,
    2266                after,
    2267                pattern,
    2268                define,
    2269            )
    2270        )
    2271        alias = self.sql(expression, "alias")
    2272        alias = f" {alias}" if alias else ""
    2273        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    2275    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    2276        limit = expression.args.get("limit")
    2277
    2278        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    2279            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    2280        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    2281            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    2282
    2283        return csv(
    2284            *sqls,
    2285            *[self.sql(join) for join in expression.args.get("joins") or []],
    2286            self.sql(expression, "connect"),
    2287            self.sql(expression, "match"),
    2288            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2289            self.sql(expression, "prewhere"),
    2290            self.sql(expression, "where"),
    2291            self.sql(expression, "group"),
    2292            self.sql(expression, "having"),
    2293            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
    2294            self.sql(expression, "order"),
    2295            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
    2296            *self.after_limit_modifiers(expression),
    2297            self.options_modifier(expression),
    2298            sep="",
    2299        )

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

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

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

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

    2308    def offset_limit_modifiers(
    2309        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2310    ) -> t.List[str]:
    2311        return [
    2312            self.sql(expression, "offset") if fetch else self.sql(limit),
    2313            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2314        ]

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

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

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

    2321    def select_sql(self, expression: exp.Select) -> str:
    2322        into = expression.args.get("into")
    2323        if not self.SUPPORTS_SELECT_INTO and into:
    2324            into.pop()
    2325
    2326        hint = self.sql(expression, "hint")
    2327        distinct = self.sql(expression, "distinct")
    2328        distinct = f" {distinct}" if distinct else ""
    2329        kind = self.sql(expression, "kind")
    2330
    2331        limit = expression.args.get("limit")
    2332        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
    2333            top = self.limit_sql(limit, top=True)
    2334            limit.pop()
    2335        else:
    2336            top = ""
    2337
    2338        expressions = self.expressions(expression)
    2339
    2340        if kind:
    2341            if kind in self.SELECT_KINDS:
    2342                kind = f" AS {kind}"
    2343            else:
    2344                if kind == "STRUCT":
    2345                    expressions = self.expressions(
    2346                        sqls=[
    2347                            self.sql(
    2348                                exp.Struct(
    2349                                    expressions=[
    2350                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
    2351                                        if isinstance(e, exp.Alias)
    2352                                        else e
    2353                                        for e in expression.expressions
    2354                                    ]
    2355                                )
    2356                            )
    2357                        ]
    2358                    )
    2359                kind = ""
    2360
    2361        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
    2362        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
    2363        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
    2364        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    2365        sql = self.query_modifiers(
    2366            expression,
    2367            f"SELECT{top_distinct}{kind}{expressions}",
    2368            self.sql(expression, "into", comment=False),
    2369            self.sql(expression, "from", comment=False),
    2370        )
    2371
    2372        sql = self.prepend_ctes(expression, sql)
    2373
    2374        if not self.SUPPORTS_SELECT_INTO and into:
    2375            if into.args.get("temporary"):
    2376                table_kind = " TEMPORARY"
    2377            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
    2378                table_kind = " UNLOGGED"
    2379            else:
    2380                table_kind = ""
    2381            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
    2382
    2383        return sql

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

    2385    def schema_sql(self, expression: exp.Schema) -> str:
    2386        this = self.sql(expression, "this")
    2387        sql = self.schema_columns_sql(expression)
    2388        return f"{this} {sql}" if this and sql else this or sql

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

    2390    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2391        if expression.expressions:
    2392            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2393        return ""

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

    2395    def star_sql(self, expression: exp.Star) -> str:
    2396        except_ = self.expressions(expression, key="except", flat=True)
    2397        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
    2398        replace = self.expressions(expression, key="replace", flat=True)
    2399        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
    2400        rename = self.expressions(expression, key="rename", flat=True)
    2401        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
    2402        return f"*{except_}{replace}{rename}"

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

    2404    def parameter_sql(self, expression: exp.Parameter) -> str:
    2405        this = self.sql(expression, "this")
    2406        return f"{self.PARAMETER_TOKEN}{this}"

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

    2408    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2409        this = self.sql(expression, "this")
    2410        kind = expression.text("kind")
    2411        if kind:
    2412            kind = f"{kind}."
    2413        return f"@@{kind}{this}"

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

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

    2418    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2419        alias = self.sql(expression, "alias")
    2420        alias = f"{sep}{alias}" if alias else ""
    2421        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2422        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2423        return self.prepend_ctes(expression, sql)

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

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

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

    2429    def set_operations(self, expression: exp.SetOperation) -> str:
    2430        if not self.SET_OP_MODIFIERS:
    2431            limit = expression.args.get("limit")
    2432            order = expression.args.get("order")
    2433
    2434            if limit or order:
    2435                select = exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
    2436
    2437                if limit:
    2438                    select = select.limit(limit.pop(), copy=False)
    2439                if order:
    2440                    select = select.order_by(order.pop(), copy=False)
    2441                return self.sql(select)
    2442
    2443        sqls: t.List[str] = []
    2444        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    2445
    2446        while stack:
    2447            node = stack.pop()
    2448
    2449            if isinstance(node, exp.SetOperation):
    2450                stack.append(node.expression)
    2451                stack.append(
    2452                    self.maybe_comment(
    2453                        getattr(self, f"{node.key}_op")(node),
    2454                        comments=node.comments,
    2455                        separated=True,
    2456                    )
    2457                )
    2458                stack.append(node.this)
    2459            else:
    2460                sqls.append(self.sql(node))
    2461
    2462        this = self.sep().join(sqls)
    2463        this = self.query_modifiers(expression, this)
    2464        return self.prepend_ctes(expression, this)

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

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

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

    2469    def union_op(self, expression: exp.SetOperation) -> str:
    2470        kind = " DISTINCT" if self.EXPLICIT_SET_OP else ""
    2471        kind = kind if expression.args.get("distinct") else " ALL"
    2472        by_name = " BY NAME" if expression.args.get("by_name") else ""
    2473        return f"UNION{kind}{by_name}"

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

    2475    def unnest_sql(self, expression: exp.Unnest) -> str:
    2476        args = self.expressions(expression, flat=True)
    2477
    2478        alias = expression.args.get("alias")
    2479        offset = expression.args.get("offset")
    2480
    2481        if self.UNNEST_WITH_ORDINALITY:
    2482            if alias and isinstance(offset, exp.Expression):
    2483                alias.append("columns", offset)
    2484
    2485        if alias and self.dialect.UNNEST_COLUMN_ONLY:
    2486            columns = alias.columns
    2487            alias = self.sql(columns[0]) if columns else ""
    2488        else:
    2489            alias = self.sql(alias)
    2490
    2491        alias = f" AS {alias}" if alias else alias
    2492        if self.UNNEST_WITH_ORDINALITY:
    2493            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2494        else:
    2495            if isinstance(offset, exp.Expression):
    2496                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2497            elif offset:
    2498                suffix = f"{alias} WITH OFFSET"
    2499            else:
    2500                suffix = alias
    2501
    2502        return f"UNNEST({args}){suffix}"

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

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

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

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

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

    2511    def window_sql(self, expression: exp.Window) -> str:
    2512        this = self.sql(expression, "this")
    2513        partition = self.partition_by_sql(expression)
    2514        order = expression.args.get("order")
    2515        order = self.order_sql(order, flat=True) if order else ""
    2516        spec = self.sql(expression, "spec")
    2517        alias = self.sql(expression, "alias")
    2518        over = self.sql(expression, "over") or "OVER"
    2519
    2520        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2521
    2522        first = expression.args.get("first")
    2523        if first is None:
    2524            first = ""
    2525        else:
    2526            first = "FIRST" if first else "LAST"
    2527
    2528        if not partition and not order and not spec and alias:
    2529            return f"{this} {alias}"
    2530
    2531        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    2532        return f"{this} ({args})"

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

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

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

    2538    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2539        kind = self.sql(expression, "kind")
    2540        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2541        end = (
    2542            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2543            or "CURRENT ROW"
    2544        )
    2545        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    2552    def between_sql(self, expression: exp.Between) -> str:
    2553        this = self.sql(expression, "this")
    2554        low = self.sql(expression, "low")
    2555        high = self.sql(expression, "high")
    2556        return f"{this} BETWEEN {low} AND {high}"

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

    2558    def bracket_offset_expressions(self, expression: exp.Bracket) -> t.List[exp.Expression]:
    2559        return apply_index_offset(
    2560            expression.this,
    2561            expression.expressions,
    2562            self.dialect.INDEX_OFFSET - expression.args.get("offset", 0),
    2563        )

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

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

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

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

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

    2573    def any_sql(self, expression: exp.Any) -> str:
    2574        this = self.sql(expression, "this")
    2575        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
    2576            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2577                this = self.wrap(this)
    2578            return f"ANY{this}"
    2579        return f"ANY {this}"

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

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

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

    2584    def case_sql(self, expression: exp.Case) -> str:
    2585        this = self.sql(expression, "this")
    2586        statements = [f"CASE {this}" if this else "CASE"]
    2587
    2588        for e in expression.args["ifs"]:
    2589            statements.append(f"WHEN {self.sql(e, 'this')}")
    2590            statements.append(f"THEN {self.sql(e, 'true')}")
    2591
    2592        default = self.sql(expression, "default")
    2593
    2594        if default:
    2595            statements.append(f"ELSE {default}")
    2596
    2597        statements.append("END")
    2598
    2599        if self.pretty and self.too_wide(statements):
    2600            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2601
    2602        return " ".join(statements)

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

    2604    def constraint_sql(self, expression: exp.Constraint) -> str:
    2605        this = self.sql(expression, "this")
    2606        expressions = self.expressions(expression, flat=True)
    2607        return f"CONSTRAINT {this} {expressions}"

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

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

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

    2614    def extract_sql(self, expression: exp.Extract) -> str:
    2615        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2616        expression_sql = self.sql(expression, "expression")
    2617        return f"EXTRACT({this} FROM {expression_sql})"

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

    2619    def trim_sql(self, expression: exp.Trim) -> str:
    2620        trim_type = self.sql(expression, "position")
    2621
    2622        if trim_type == "LEADING":
    2623            return self.func("LTRIM", expression.this)
    2624        elif trim_type == "TRAILING":
    2625            return self.func("RTRIM", expression.this)
    2626        else:
    2627            return self.func("TRIM", expression.this, expression.expression)

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

    2629    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2630        args = expression.expressions
    2631        if isinstance(expression, exp.ConcatWs):
    2632            args = args[1:]  # Skip the delimiter
    2633
    2634        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2635            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
    2636
    2637        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2638            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2639
    2640        return args

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

    2642    def concat_sql(self, expression: exp.Concat) -> str:
    2643        expressions = self.convert_concat_args(expression)
    2644
    2645        # Some dialects don't allow a single-argument CONCAT call
    2646        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2647            return self.sql(expressions[0])
    2648
    2649        return self.func("CONCAT", *expressions)

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

    2651    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2652        return self.func(
    2653            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2654        )

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

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

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

    2660    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2661        expressions = self.expressions(expression, flat=True)
    2662        reference = self.sql(expression, "reference")
    2663        reference = f" {reference}" if reference else ""
    2664        delete = self.sql(expression, "delete")
    2665        delete = f" ON DELETE {delete}" if delete else ""
    2666        update = self.sql(expression, "update")
    2667        update = f" ON UPDATE {update}" if update else ""
    2668        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"

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

    2670    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2671        expressions = self.expressions(expression, flat=True)
    2672        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2673        options = f" {options}" if options else ""
    2674        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

    2687    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
    2688        path = self.expressions(expression, sep="", flat=True).lstrip(".")
    2689        if self.QUOTE_JSON_PATH:
    2690            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
    2691
    2692        return path

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

    2694    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
    2695        if isinstance(expression, exp.JSONPathPart):
    2696            transform = self.TRANSFORMS.get(expression.__class__)
    2697            if not callable(transform):
    2698                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
    2699                return ""
    2700
    2701            return transform(self, expression)
    2702
    2703        if isinstance(expression, int):
    2704            return str(expression)
    2705
    2706        if self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
    2707            escaped = expression.replace("'", "\\'")
    2708            escaped = f"\\'{expression}\\'"
    2709        else:
    2710            escaped = expression.replace('"', '\\"')
    2711            escaped = f'"{escaped}"'
    2712
    2713        return escaped

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

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

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

    2718    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    2719        null_handling = expression.args.get("null_handling")
    2720        null_handling = f" {null_handling}" if null_handling else ""
    2721
    2722        unique_keys = expression.args.get("unique_keys")
    2723        if unique_keys is not None:
    2724            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2725        else:
    2726            unique_keys = ""
    2727
    2728        return_type = self.sql(expression, "return_type")
    2729        return_type = f" RETURNING {return_type}" if return_type else ""
    2730        encoding = self.sql(expression, "encoding")
    2731        encoding = f" ENCODING {encoding}" if encoding else ""
    2732
    2733        return self.func(
    2734            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    2735            *expression.expressions,
    2736            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2737        )

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

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

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

    2742    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2743        null_handling = expression.args.get("null_handling")
    2744        null_handling = f" {null_handling}" if null_handling else ""
    2745        return_type = self.sql(expression, "return_type")
    2746        return_type = f" RETURNING {return_type}" if return_type else ""
    2747        strict = " STRICT" if expression.args.get("strict") else ""
    2748        return self.func(
    2749            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2750        )

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

    2752    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2753        this = self.sql(expression, "this")
    2754        order = self.sql(expression, "order")
    2755        null_handling = expression.args.get("null_handling")
    2756        null_handling = f" {null_handling}" if null_handling else ""
    2757        return_type = self.sql(expression, "return_type")
    2758        return_type = f" RETURNING {return_type}" if return_type else ""
    2759        strict = " STRICT" if expression.args.get("strict") else ""
    2760        return self.func(
    2761            "JSON_ARRAYAGG",
    2762            this,
    2763            suffix=f"{order}{null_handling}{return_type}{strict})",
    2764        )

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

    2766    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2767        path = self.sql(expression, "path")
    2768        path = f" PATH {path}" if path else ""
    2769        nested_schema = self.sql(expression, "nested_schema")
    2770
    2771        if nested_schema:
    2772            return f"NESTED{path} {nested_schema}"
    2773
    2774        this = self.sql(expression, "this")
    2775        kind = self.sql(expression, "kind")
    2776        kind = f" {kind}" if kind else ""
    2777        return f"{this}{kind}{path}"

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

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

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

    2782    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    2783        this = self.sql(expression, "this")
    2784        path = self.sql(expression, "path")
    2785        path = f", {path}" if path else ""
    2786        error_handling = expression.args.get("error_handling")
    2787        error_handling = f" {error_handling}" if error_handling else ""
    2788        empty_handling = expression.args.get("empty_handling")
    2789        empty_handling = f" {empty_handling}" if empty_handling else ""
    2790        schema = self.sql(expression, "schema")
    2791        return self.func(
    2792            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    2793        )

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

    2795    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    2796        this = self.sql(expression, "this")
    2797        kind = self.sql(expression, "kind")
    2798        path = self.sql(expression, "path")
    2799        path = f" {path}" if path else ""
    2800        as_json = " AS JSON" if expression.args.get("as_json") else ""
    2801        return f"{this} {kind}{path}{as_json}"

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

    2803    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    2804        this = self.sql(expression, "this")
    2805        path = self.sql(expression, "path")
    2806        path = f", {path}" if path else ""
    2807        expressions = self.expressions(expression)
    2808        with_ = (
    2809            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2810            if expressions
    2811            else ""
    2812        )
    2813        return f"OPENJSON({this}{path}){with_}"

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

    2815    def in_sql(self, expression: exp.In) -> str:
    2816        query = expression.args.get("query")
    2817        unnest = expression.args.get("unnest")
    2818        field = expression.args.get("field")
    2819        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    2820
    2821        if query:
    2822            in_sql = self.sql(query)
    2823        elif unnest:
    2824            in_sql = self.in_unnest_op(unnest)
    2825        elif field:
    2826            in_sql = self.sql(field)
    2827        else:
    2828            in_sql = f"({self.expressions(expression, flat=True)})"
    2829
    2830        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    2835    def interval_sql(self, expression: exp.Interval) -> str:
    2836        unit = self.sql(expression, "unit")
    2837        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    2838            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    2839        unit = f" {unit}" if unit else ""
    2840
    2841        if self.SINGLE_STRING_INTERVAL:
    2842            this = expression.this.name if expression.this else ""
    2843            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    2844
    2845        this = self.sql(expression, "this")
    2846        if this:
    2847            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    2848            this = f" {this}" if unwrapped else f" ({this})"
    2849
    2850        return f"INTERVAL{this}{unit}"

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

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

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

    2855    def reference_sql(self, expression: exp.Reference) -> str:
    2856        this = self.sql(expression, "this")
    2857        expressions = self.expressions(expression, flat=True)
    2858        expressions = f"({expressions})" if expressions else ""
    2859        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2860        options = f" {options}" if options else ""
    2861        return f"REFERENCES {this}{expressions}{options}"

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

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

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

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

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

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

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

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

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

    2879    def alias_sql(self, expression: exp.Alias) -> str:
    2880        alias = self.sql(expression, "alias")
    2881        alias = f" AS {alias}" if alias else ""
    2882        return f"{self.sql(expression, 'this')}{alias}"

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

    2884    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    2885        alias = expression.args["alias"]
    2886        identifier_alias = isinstance(alias, exp.Identifier)
    2887
    2888        if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2889            alias.replace(exp.Literal.string(alias.output_name))
    2890        elif not identifier_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2891            alias.replace(exp.to_identifier(alias.output_name))
    2892
    2893        return self.alias_sql(expression)

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

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

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

    2898    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    2899        this = self.sql(expression, "this")
    2900        index = self.sql(expression, "expression")
    2901        return f"{this} AT {index}"

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

    2903    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    2904        this = self.sql(expression, "this")
    2905        zone = self.sql(expression, "zone")
    2906        return f"{this} AT TIME ZONE {zone}"

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

    2908    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    2909        this = self.sql(expression, "this")
    2910        zone = self.sql(expression, "zone")
    2911        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"

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

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

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

    2916    def and_sql(
    2917        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
    2918    ) -> str:
    2919        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

    2921    def or_sql(
    2922        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
    2923    ) -> str:
    2924        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

    2926    def xor_sql(
    2927        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
    2928    ) -> str:
    2929        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

    2931    def connector_sql(
    2932        self,
    2933        expression: exp.Connector,
    2934        op: str,
    2935        stack: t.Optional[t.List[str | exp.Expression]] = None,
    2936    ) -> str:
    2937        if stack is not None:
    2938            if expression.expressions:
    2939                stack.append(self.expressions(expression, sep=f" {op} "))
    2940            else:
    2941                stack.append(expression.right)
    2942                if expression.comments and self.comments:
    2943                    for comment in expression.comments:
    2944                        if comment:
    2945                            op += f" /*{self.pad_comment(comment)}*/"
    2946                stack.extend((op, expression.left))
    2947            return op
    2948
    2949        stack = [expression]
    2950        sqls: t.List[str] = []
    2951        ops = set()
    2952
    2953        while stack:
    2954            node = stack.pop()
    2955            if isinstance(node, exp.Connector):
    2956                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
    2957            else:
    2958                sql = self.sql(node)
    2959                if sqls and sqls[-1] in ops:
    2960                    sqls[-1] += f" {sql}"
    2961                else:
    2962                    sqls.append(sql)
    2963
    2964        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
    2965        return sep.join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

    2985    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    2986        format_sql = self.sql(expression, "format")
    2987        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    2988        to_sql = self.sql(expression, "to")
    2989        to_sql = f" {to_sql}" if to_sql else ""
    2990        action = self.sql(expression, "action")
    2991        action = f" {action}" if action else ""
    2992        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

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

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

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

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

    3001    def collate_sql(self, expression: exp.Collate) -> str:
    3002        if self.COLLATE_IS_FUNC:
    3003            return self.function_fallback_sql(expression)
    3004        return self.binary(expression, "COLLATE")

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

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

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

    3009    def comment_sql(self, expression: exp.Comment) -> str:
    3010        this = self.sql(expression, "this")
    3011        kind = expression.args["kind"]
    3012        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    3013        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    3014        expression_sql = self.sql(expression, "expression")
    3015        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"

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

    3017    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    3018        this = self.sql(expression, "this")
    3019        delete = " DELETE" if expression.args.get("delete") else ""
    3020        recompress = self.sql(expression, "recompress")
    3021        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    3022        to_disk = self.sql(expression, "to_disk")
    3023        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    3024        to_volume = self.sql(expression, "to_volume")
    3025        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    3026        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    3028    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    3029        where = self.sql(expression, "where")
    3030        group = self.sql(expression, "group")
    3031        aggregates = self.expressions(expression, key="aggregates")
    3032        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    3033
    3034        if not (where or group or aggregates) and len(expression.expressions) == 1:
    3035            return f"TTL {self.expressions(expression, flat=True)}"
    3036
    3037        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    3042    def commit_sql(self, expression: exp.Commit) -> str:
    3043        chain = expression.args.get("chain")
    3044        if chain is not None:
    3045            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    3046
    3047        return f"COMMIT{chain or ''}"

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

    3049    def rollback_sql(self, expression: exp.Rollback) -> str:
    3050        savepoint = expression.args.get("savepoint")
    3051        savepoint = f" TO {savepoint}" if savepoint else ""
    3052        return f"ROLLBACK{savepoint}"

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

    3054    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    3055        this = self.sql(expression, "this")
    3056
    3057        dtype = self.sql(expression, "dtype")
    3058        if dtype:
    3059            collate = self.sql(expression, "collate")
    3060            collate = f" COLLATE {collate}" if collate else ""
    3061            using = self.sql(expression, "using")
    3062            using = f" USING {using}" if using else ""
    3063            return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}"
    3064
    3065        default = self.sql(expression, "default")
    3066        if default:
    3067            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    3068
    3069        comment = self.sql(expression, "comment")
    3070        if comment:
    3071            return f"ALTER COLUMN {this} COMMENT {comment}"
    3072
    3073        allow_null = expression.args.get("allow_null")
    3074        drop = expression.args.get("drop")
    3075
    3076        if not drop and not allow_null:
    3077            self.unsupported("Unsupported ALTER COLUMN syntax")
    3078
    3079        if allow_null is not None:
    3080            keyword = "DROP" if drop else "SET"
    3081            return f"ALTER COLUMN {this} {keyword} NOT NULL"
    3082
    3083        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    3085    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
    3086        this = self.sql(expression, "this")
    3087        if not isinstance(expression.this, exp.Var):
    3088            this = f"KEY DISTKEY {this}"
    3089        return f"ALTER DISTSTYLE {this}"

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

    3091    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
    3092        compound = " COMPOUND" if expression.args.get("compound") else ""
    3093        this = self.sql(expression, "this")
    3094        expressions = self.expressions(expression, flat=True)
    3095        expressions = f"({expressions})" if expressions else ""
    3096        return f"ALTER{compound} SORTKEY {this or expressions}"

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

    3098    def renametable_sql(self, expression: exp.RenameTable) -> str:
    3099        if not self.RENAME_TABLE_WITH_DB:
    3100            # Remove db from tables
    3101            expression = expression.transform(
    3102                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    3103            ).assert_is(exp.RenameTable)
    3104        this = self.sql(expression, "this")
    3105        return f"RENAME TO {this}"

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

    3107    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    3108        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3109        old_column = self.sql(expression, "this")
    3110        new_column = self.sql(expression, "to")
    3111        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"

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

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

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

    3117    def altertable_sql(self, expression: exp.AlterTable) -> str:
    3118        actions = expression.args["actions"]
    3119
    3120        if isinstance(actions[0], exp.ColumnDef):
    3121            actions = self.add_column_sql(expression)
    3122        elif isinstance(actions[0], exp.Schema):
    3123            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    3124        elif isinstance(actions[0], exp.Delete):
    3125            actions = self.expressions(expression, key="actions", flat=True)
    3126        else:
    3127            actions = self.expressions(expression, key="actions", flat=True)
    3128
    3129        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3130        on_cluster = self.sql(expression, "cluster")
    3131        on_cluster = f" {on_cluster}" if on_cluster else ""
    3132        only = " ONLY" if expression.args.get("only") else ""
    3133        options = self.expressions(expression, key="options")
    3134        options = f", {options}" if options else ""
    3135        return f"ALTER TABLE{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{options}"

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

    3137    def add_column_sql(self, expression: exp.AlterTable) -> str:
    3138        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    3139            return self.expressions(
    3140                expression,
    3141                key="actions",
    3142                prefix="ADD COLUMN ",
    3143                skip_first=True,
    3144            )
    3145        return f"ADD {self.expressions(expression, key='actions', flat=True)}"

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

    3147    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    3148        expressions = self.expressions(expression)
    3149        exists = " IF EXISTS " if expression.args.get("exists") else " "
    3150        return f"DROP{exists}{expressions}"

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

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

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

    3155    def distinct_sql(self, expression: exp.Distinct) -> str:
    3156        this = self.expressions(expression, flat=True)
    3157
    3158        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    3159            case = exp.case()
    3160            for arg in expression.expressions:
    3161                case = case.when(arg.is_(exp.null()), exp.null())
    3162            this = self.sql(case.else_(f"({this})"))
    3163
    3164        this = f" {this}" if this else ""
    3165
    3166        on = self.sql(expression, "on")
    3167        on = f" ON {on}" if on else ""
    3168        return f"DISTINCT{this}{on}"

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

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

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

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

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

    3176    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    3177        this_sql = self.sql(expression, "this")
    3178        expression_sql = self.sql(expression, "expression")
    3179        kind = "MAX" if expression.args.get("max") else "MIN"
    3180        return f"{this_sql} HAVING {kind} {expression_sql}"

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

    3182    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    3183        return self.sql(
    3184            exp.Cast(
    3185                this=exp.Div(this=expression.this, expression=expression.expression),
    3186                to=exp.DataType(this=exp.DataType.Type.INT),
    3187            )
    3188        )

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

    3190    def dpipe_sql(self, expression: exp.DPipe) -> str:
    3191        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    3192            return self.func(
    3193                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
    3194            )
    3195        return self.binary(expression, "||")

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

    3197    def div_sql(self, expression: exp.Div) -> str:
    3198        l, r = expression.left, expression.right
    3199
    3200        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    3201            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    3202
    3203        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    3204            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
    3205                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    3206
    3207        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    3208            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    3209                return self.sql(
    3210                    exp.cast(
    3211                        l / r,
    3212                        to=exp.DataType.Type.BIGINT,
    3213                    )
    3214                )
    3215
    3216        return self.binary(expression, "/")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3251    def is_sql(self, expression: exp.Is) -> str:
    3252        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3253            return self.sql(
    3254                expression.this if expression.expression.this else exp.not_(expression.this)
    3255            )
    3256        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3297    def try_sql(self, expression: exp.Try) -> str:
    3298        if not self.TRY_SUPPORTED:
    3299            self.unsupported("Unsupported TRY function")
    3300            return self.sql(expression, "this")
    3301
    3302        return self.func("TRY", expression.this)

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

    3304    def log_sql(self, expression: exp.Log) -> str:
    3305        this = expression.this
    3306        expr = expression.expression
    3307
    3308        if self.dialect.LOG_BASE_FIRST is False:
    3309            this, expr = expr, this
    3310        elif self.dialect.LOG_BASE_FIRST is None and expr:
    3311            if this.name in ("2", "10"):
    3312                return self.func(f"LOG{this.name}", expr)
    3313
    3314            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
    3315
    3316        return self.func("LOG", this, expr)

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

    3318    def use_sql(self, expression: exp.Use) -> str:
    3319        kind = self.sql(expression, "kind")
    3320        kind = f" {kind}" if kind else ""
    3321        this = self.sql(expression, "this")
    3322        this = f" {this}" if this else ""
    3323        return f"USE{kind}{this}"

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

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

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

    3329    def function_fallback_sql(self, expression: exp.Func) -> str:
    3330        args = []
    3331
    3332        for key in expression.arg_types:
    3333            arg_value = expression.args.get(key)
    3334
    3335            if isinstance(arg_value, list):
    3336                for value in arg_value:
    3337                    args.append(value)
    3338            elif arg_value is not None:
    3339                args.append(arg_value)
    3340
    3341        if self.normalize_functions:
    3342            name = expression.sql_name()
    3343        else:
    3344            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3345
    3346        return self.func(name, *args)

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

    3348    def func(
    3349        self,
    3350        name: str,
    3351        *args: t.Optional[exp.Expression | str],
    3352        prefix: str = "(",
    3353        suffix: str = ")",
    3354    ) -> str:
    3355        return f"{self.normalize_func(name)}{prefix}{self.format_args(*args)}{suffix}"

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

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

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

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

    3366    def format_time(
    3367        self,
    3368        expression: exp.Expression,
    3369        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
    3370        inverse_time_trie: t.Optional[t.Dict] = None,
    3371    ) -> t.Optional[str]:
    3372        return format_time(
    3373            self.sql(expression, "format"),
    3374            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
    3375            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
    3376        )

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

    3378    def expressions(
    3379        self,
    3380        expression: t.Optional[exp.Expression] = None,
    3381        key: t.Optional[str] = None,
    3382        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    3383        flat: bool = False,
    3384        indent: bool = True,
    3385        skip_first: bool = False,
    3386        skip_last: bool = False,
    3387        sep: str = ", ",
    3388        prefix: str = "",
    3389        dynamic: bool = False,
    3390        new_line: bool = False,
    3391    ) -> str:
    3392        expressions = expression.args.get(key or "expressions") if expression else sqls
    3393
    3394        if not expressions:
    3395            return ""
    3396
    3397        if flat:
    3398            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    3399
    3400        num_sqls = len(expressions)
    3401
    3402        # These are calculated once in case we have the leading_comma / pretty option set, correspondingly
    3403        if self.pretty and not self.leading_comma:
    3404            stripped_sep = sep.strip()
    3405
    3406        result_sqls = []
    3407        for i, e in enumerate(expressions):
    3408            sql = self.sql(e, comment=False)
    3409            if not sql:
    3410                continue
    3411
    3412            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    3413
    3414            if self.pretty:
    3415                if self.leading_comma:
    3416                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
    3417                else:
    3418                    result_sqls.append(
    3419                        f"{prefix}{sql}{stripped_sep if i + 1 < num_sqls else ''}{comments}"
    3420                    )
    3421            else:
    3422                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    3423
    3424        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
    3425            if new_line:
    3426                result_sqls.insert(0, "")
    3427                result_sqls.append("")
    3428            result_sql = "\n".join(result_sqls)
    3429        else:
    3430            result_sql = "".join(result_sqls)
    3431        return (
    3432            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
    3433            if indent
    3434            else result_sql
    3435        )

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

    3437    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3438        flat = flat or isinstance(expression.parent, exp.Properties)
    3439        expressions_sql = self.expressions(expression, flat=flat)
    3440        if flat:
    3441            return f"{op} {expressions_sql}"
    3442        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    3444    def naked_property(self, expression: exp.Property) -> str:
    3445        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3446        if not property_name:
    3447            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3448        return f"{property_name} {self.sql(expression, 'this')}"

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

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

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

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

    3456    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3457        this = self.sql(expression, "this")
    3458        expressions = self.no_identify(self.expressions, expression)
    3459        expressions = (
    3460            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3461        )
    3462        return f"{this}{expressions}"

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

    3464    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3465        this = self.sql(expression, "this")
    3466        expressions = self.expressions(expression, flat=True)
    3467        return f"{this}({expressions})"

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

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

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

    3472    def when_sql(self, expression: exp.When) -> str:
    3473        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3474        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3475        condition = self.sql(expression, "condition")
    3476        condition = f" AND {condition}" if condition else ""
    3477
    3478        then_expression = expression.args.get("then")
    3479        if isinstance(then_expression, exp.Insert):
    3480            this = self.sql(then_expression, "this")
    3481            this = f"INSERT {this}" if this else "INSERT"
    3482            then = self.sql(then_expression, "expression")
    3483            then = f"{this} VALUES {then}" if then else this
    3484        elif isinstance(then_expression, exp.Update):
    3485            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3486                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3487            else:
    3488                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    3489        else:
    3490            then = self.sql(then_expression)
    3491        return f"WHEN {matched}{source}{condition} THEN {then}"

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

    3493    def merge_sql(self, expression: exp.Merge) -> str:
    3494        table = expression.this
    3495        table_alias = ""
    3496
    3497        hints = table.args.get("hints")
    3498        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3499            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3500            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3501
    3502        this = self.sql(table)
    3503        using = f"USING {self.sql(expression, 'using')}"
    3504        on = f"ON {self.sql(expression, 'on')}"
    3505        expressions = self.expressions(expression, sep=" ", indent=False)
    3506        sep = self.sep()
    3507
    3508        return self.prepend_ctes(
    3509            expression, f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{expressions}"
    3510        )

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

    3512    def tochar_sql(self, expression: exp.ToChar) -> str:
    3513        if expression.args.get("format"):
    3514            self.unsupported("Format argument unsupported for TO_CHAR/TO_VARCHAR function")
    3515
    3516        return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT))

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

    3518    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3519        if not self.SUPPORTS_TO_NUMBER:
    3520            self.unsupported("Unsupported TO_NUMBER function")
    3521            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3522
    3523        fmt = expression.args.get("format")
    3524        if not fmt:
    3525            self.unsupported("Conversion format is required for TO_NUMBER")
    3526            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3527
    3528        return self.func("TO_NUMBER", expression.this, fmt)

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

    3530    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3531        this = self.sql(expression, "this")
    3532        kind = self.sql(expression, "kind")
    3533        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3534        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3535        return f"{this}({kind}{args})"

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

    3537    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3538        this = self.sql(expression, "this")
    3539        max = self.sql(expression, "max")
    3540        min = self.sql(expression, "min")
    3541        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

    3549    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3550        expressions = self.expressions(expression, key="expressions", flat=True)
    3551        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3552        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3553        buckets = self.sql(expression, "buckets")
    3554        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    3556    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3557        this = self.sql(expression, "this")
    3558        having = self.sql(expression, "having")
    3559
    3560        if having:
    3561            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3562
    3563        return self.func("ANY_VALUE", this)

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

    3565    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3566        transform = self.func("TRANSFORM", *expression.expressions)
    3567        row_format_before = self.sql(expression, "row_format_before")
    3568        row_format_before = f" {row_format_before}" if row_format_before else ""
    3569        record_writer = self.sql(expression, "record_writer")
    3570        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3571        using = f" USING {self.sql(expression, 'command_script')}"
    3572        schema = self.sql(expression, "schema")
    3573        schema = f" AS {schema}" if schema else ""
    3574        row_format_after = self.sql(expression, "row_format_after")
    3575        row_format_after = f" {row_format_after}" if row_format_after else ""
    3576        record_reader = self.sql(expression, "record_reader")
    3577        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3578        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

    3580    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3581        key_block_size = self.sql(expression, "key_block_size")
    3582        if key_block_size:
    3583            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3584
    3585        using = self.sql(expression, "using")
    3586        if using:
    3587            return f"USING {using}"
    3588
    3589        parser = self.sql(expression, "parser")
    3590        if parser:
    3591            return f"WITH PARSER {parser}"
    3592
    3593        comment = self.sql(expression, "comment")
    3594        if comment:
    3595            return f"COMMENT {comment}"
    3596
    3597        visible = expression.args.get("visible")
    3598        if visible is not None:
    3599            return "VISIBLE" if visible else "INVISIBLE"
    3600
    3601        engine_attr = self.sql(expression, "engine_attr")
    3602        if engine_attr:
    3603            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3604
    3605        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3606        if secondary_engine_attr:
    3607            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3608
    3609        self.unsupported("Unsupported index constraint option.")
    3610        return ""

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

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

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

    3616    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3617        kind = self.sql(expression, "kind")
    3618        kind = f"{kind} INDEX" if kind else "INDEX"
    3619        this = self.sql(expression, "this")
    3620        this = f" {this}" if this else ""
    3621        index_type = self.sql(expression, "index_type")
    3622        index_type = f" USING {index_type}" if index_type else ""
    3623        expressions = self.expressions(expression, flat=True)
    3624        expressions = f" ({expressions})" if expressions else ""
    3625        options = self.expressions(expression, key="options", sep=" ")
    3626        options = f" {options}" if options else ""
    3627        return f"{kind}{this}{index_type}{expressions}{options}"

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

    3629    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3630        if self.NVL2_SUPPORTED:
    3631            return self.function_fallback_sql(expression)
    3632
    3633        case = exp.Case().when(
    3634            expression.this.is_(exp.null()).not_(copy=False),
    3635            expression.args["true"],
    3636            copy=False,
    3637        )
    3638        else_cond = expression.args.get("false")
    3639        if else_cond:
    3640            case.else_(else_cond, copy=False)
    3641
    3642        return self.sql(case)

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

    3644    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3645        this = self.sql(expression, "this")
    3646        expr = self.sql(expression, "expression")
    3647        iterator = self.sql(expression, "iterator")
    3648        condition = self.sql(expression, "condition")
    3649        condition = f" IF {condition}" if condition else ""
    3650        return f"{this} FOR {expr} IN {iterator}{condition}"

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

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

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

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

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

    3658    def predict_sql(self, expression: exp.Predict) -> str:
    3659        model = self.sql(expression, "this")
    3660        model = f"MODEL {model}"
    3661        table = self.sql(expression, "expression")
    3662        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    3663        parameters = self.sql(expression, "params_struct")
    3664        return self.func("PREDICT", model, table, parameters or None)

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

    3666    def forin_sql(self, expression: exp.ForIn) -> str:
    3667        this = self.sql(expression, "this")
    3668        expression_sql = self.sql(expression, "expression")
    3669        return f"FOR {this} DO {expression_sql}"

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

    3671    def refresh_sql(self, expression: exp.Refresh) -> str:
    3672        this = self.sql(expression, "this")
    3673        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    3674        return f"REFRESH {table}{this}"

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

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

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

    3679    def toarray_sql(self, expression: exp.ToArray) -> str:
    3680        arg = expression.this
    3681        if not arg.type:
    3682            from sqlglot.optimizer.annotate_types import annotate_types
    3683
    3684            arg = annotate_types(arg)
    3685
    3686        if arg.is_type(exp.DataType.Type.ARRAY):
    3687            return self.sql(arg)
    3688
    3689        cond_for_null = arg.is_(exp.null())
    3690        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

    3692    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    3693        this = expression.this
    3694        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    3695            return self.sql(this)
    3696
    3697        return self.sql(exp.cast(this, exp.DataType.Type.TIME))

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

    3699    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
    3700        this = expression.this
    3701        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
    3702            return self.sql(this)
    3703
    3704        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP))

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

    3706    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    3707        this = expression.this
    3708        time_format = self.format_time(expression)
    3709
    3710        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    3711            return self.sql(
    3712                exp.cast(
    3713                    exp.StrToTime(this=this, format=expression.args["format"]),
    3714                    exp.DataType.Type.DATE,
    3715                )
    3716            )
    3717
    3718        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    3719            return self.sql(this)
    3720
    3721        return self.sql(exp.cast(this, exp.DataType.Type.DATE))

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

    3723    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    3724        return self.sql(
    3725            exp.func(
    3726                "DATEDIFF",
    3727                expression.this,
    3728                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
    3729                "day",
    3730            )
    3731        )

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

    3733    def lastday_sql(self, expression: exp.LastDay) -> str:
    3734        if self.LAST_DAY_SUPPORTS_DATE_PART:
    3735            return self.function_fallback_sql(expression)
    3736
    3737        unit = expression.text("unit")
    3738        if unit and unit != "MONTH":
    3739            self.unsupported("Date parts are not supported in LAST_DAY.")
    3740
    3741        return self.func("LAST_DAY", expression.this)

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

    3743    def dateadd_sql(self, expression: exp.DateAdd) -> str:
    3744        from sqlglot.dialects.dialect import unit_to_str
    3745
    3746        return self.func(
    3747            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
    3748        )

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

    3750    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    3751        if self.CAN_IMPLEMENT_ARRAY_ANY:
    3752            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    3753            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    3754            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    3755            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    3756
    3757        from sqlglot.dialects import Dialect
    3758
    3759        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    3760        if self.dialect.__class__ != Dialect:
    3761            self.unsupported("ARRAY_ANY is unsupported")
    3762
    3763        return self.function_fallback_sql(expression)

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

    3765    def generateseries_sql(self, expression: exp.GenerateSeries) -> str:
    3766        expression.set("is_end_exclusive", None)
    3767        return self.function_fallback_sql(expression)

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

    3769    def struct_sql(self, expression: exp.Struct) -> str:
    3770        expression.set(
    3771            "expressions",
    3772            [
    3773                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    3774                if isinstance(e, exp.PropertyEQ)
    3775                else e
    3776                for e in expression.expressions
    3777            ],
    3778        )
    3779
    3780        return self.function_fallback_sql(expression)

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

    3782    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    3783        low = self.sql(expression, "this")
    3784        high = self.sql(expression, "expression")
    3785
    3786        return f"{low} TO {high}"

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

    3788    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    3789        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    3790        tables = f" {self.expressions(expression)}"
    3791
    3792        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3793
    3794        on_cluster = self.sql(expression, "cluster")
    3795        on_cluster = f" {on_cluster}" if on_cluster else ""
    3796
    3797        identity = self.sql(expression, "identity")
    3798        identity = f" {identity} IDENTITY" if identity else ""
    3799
    3800        option = self.sql(expression, "option")
    3801        option = f" {option}" if option else ""
    3802
    3803        partition = self.sql(expression, "partition")
    3804        partition = f" {partition}" if partition else ""
    3805
    3806        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"

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

    3810    def convert_sql(self, expression: exp.Convert) -> str:
    3811        to = expression.this
    3812        value = expression.expression
    3813        style = expression.args.get("style")
    3814        safe = expression.args.get("safe")
    3815        strict = expression.args.get("strict")
    3816
    3817        if not to or not value:
    3818            return ""
    3819
    3820        # Retrieve length of datatype and override to default if not specified
    3821        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3822            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    3823
    3824        transformed: t.Optional[exp.Expression] = None
    3825        cast = exp.Cast if strict else exp.TryCast
    3826
    3827        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
    3828        if isinstance(style, exp.Literal) and style.is_int:
    3829            from sqlglot.dialects.tsql import TSQL
    3830
    3831            style_value = style.name
    3832            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
    3833            if not converted_style:
    3834                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
    3835
    3836            fmt = exp.Literal.string(converted_style)
    3837
    3838            if to.this == exp.DataType.Type.DATE:
    3839                transformed = exp.StrToDate(this=value, format=fmt)
    3840            elif to.this == exp.DataType.Type.DATETIME:
    3841                transformed = exp.StrToTime(this=value, format=fmt)
    3842            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3843                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
    3844            elif to.this == exp.DataType.Type.TEXT:
    3845                transformed = exp.TimeToStr(this=value, format=fmt)
    3846
    3847        if not transformed:
    3848            transformed = cast(this=value, to=to, safe=safe)
    3849
    3850        return self.sql(transformed)

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

    3906    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
    3907        option = self.sql(expression, "this")
    3908
    3909        if expression.expressions:
    3910            upper = option.upper()
    3911
    3912            # Snowflake FILE_FORMAT options are separated by whitespace
    3913            sep = " " if upper == "FILE_FORMAT" else ", "
    3914
    3915            # Databricks copy/format options do not set their list of values with EQ
    3916            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
    3917            values = self.expressions(expression, flat=True, sep=sep)
    3918            return f"{option}{op}({values})"
    3919
    3920        value = self.sql(expression, "expression")
    3921
    3922        if not value:
    3923            return option
    3924
    3925        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
    3926
    3927        return f"{option}{op}{value}"

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

    3929    def credentials_sql(self, expression: exp.Credentials) -> str:
    3930        cred_expr = expression.args.get("credentials")
    3931        if isinstance(cred_expr, exp.Literal):
    3932            # Redshift case: CREDENTIALS <string>
    3933            credentials = self.sql(expression, "credentials")
    3934            credentials = f"CREDENTIALS {credentials}" if credentials else ""
    3935        else:
    3936            # Snowflake case: CREDENTIALS = (...)
    3937            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
    3938            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
    3939
    3940        storage = self.sql(expression, "storage")
    3941        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
    3942
    3943        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
    3944        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
    3945
    3946        iam_role = self.sql(expression, "iam_role")
    3947        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
    3948
    3949        region = self.sql(expression, "region")
    3950        region = f" REGION {region}" if region else ""
    3951
    3952        return f"{credentials}{storage}{encryption}{iam_role}{region}"

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

    3954    def copy_sql(self, expression: exp.Copy) -> str:
    3955        this = self.sql(expression, "this")
    3956        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
    3957
    3958        credentials = self.sql(expression, "credentials")
    3959        credentials = self.seg(credentials) if credentials else ""
    3960        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
    3961        files = self.expressions(expression, key="files", flat=True)
    3962
    3963        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
    3964        params = self.expressions(
    3965            expression,
    3966            key="params",
    3967            sep=sep,
    3968            new_line=True,
    3969            skip_last=True,
    3970            skip_first=True,
    3971            indent=self.COPY_PARAMS_ARE_WRAPPED,
    3972        )
    3973
    3974        if params:
    3975            if self.COPY_PARAMS_ARE_WRAPPED:
    3976                params = f" WITH ({params})"
    3977            elif not self.pretty:
    3978                params = f" {params}"
    3979
    3980        return f"COPY{this}{kind} {files}{credentials}{params}"

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

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

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

    3985    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
    3986        on_sql = "ON" if expression.args.get("on") else "OFF"
    3987        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
    3988        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
    3989        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    3990        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
    3991
    3992        if filter_col or retention_period:
    3993            on_sql = self.func("ON", filter_col, retention_period)
    3994
    3995        return f"DATA_DELETION={on_sql}"

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

    3997    def maskingpolicycolumnconstraint_sql(
    3998        self, expression: exp.MaskingPolicyColumnConstraint
    3999    ) -> str:
    4000        this = self.sql(expression, "this")
    4001        expressions = self.expressions(expression, flat=True)
    4002        expressions = f" USING ({expressions})" if expressions else ""
    4003        return f"MASKING POLICY {this}{expressions}"

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

    4005    def gapfill_sql(self, expression: exp.GapFill) -> str:
    4006        this = self.sql(expression, "this")
    4007        this = f"TABLE {this}"
    4008        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

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

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

    4013    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
    4014        this = self.sql(expression, "this")
    4015        expr = expression.expression
    4016
    4017        if isinstance(expr, exp.Func):
    4018            # T-SQL's CLR functions are case sensitive
    4019            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
    4020        else:
    4021            expr = self.sql(expression, "expression")
    4022
    4023        return self.scope_resolution(expr, this)

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

    4025    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
    4026        if self.PARSE_JSON_NAME is None:
    4027            return self.sql(expression.this)
    4028
    4029        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)

def length_sql(self, expression: sqlglot.expressions.Length) -> str: View Source

    4031    def length_sql(self, expression: exp.Length) -> str:
    4032        return self.func("LENGTH", expression.this)

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

    4034    def rand_sql(self, expression: exp.Rand) -> str:
    4035        lower = self.sql(expression, "lower")
    4036        upper = self.sql(expression, "upper")
    4037
    4038        if lower and upper:
    4039            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
    4040        return self.func("RAND", expression.this)

def strtodate_sql(self, expression: sqlglot.expressions.StrToDate) -> str: View Source

    4042    def strtodate_sql(self, expression: exp.StrToDate) -> str:
    4043        return self.func("STR_TO_DATE", expression.this, expression.args.get("format"))

def strtotime_sql(self, expression: sqlglot.expressions.StrToTime) -> str: View Source

    4045    def strtotime_sql(self, expression: exp.StrToTime) -> str:
    4046        return self.func(
    4047            "STR_TO_TIME",
    4048            expression.this,
    4049            expression.args.get("format"),
    4050            expression.args.get("zone"),
    4051        )

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

    4053    def changes_sql(self, expression: exp.Changes) -> str:
    4054        information = self.sql(expression, "information")
    4055        information = f"INFORMATION => {information}"
    4056        at_before = self.sql(expression, "at_before")
    4057        at_before = f"{self.seg('')}{at_before}" if at_before else ""
    4058        end = self.sql(expression, "end")
    4059        end = f"{self.seg('')}{end}" if end else ""
    4060
    4061        return f"CHANGES ({information}){at_before}{end}"

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

    4063    def pad_sql(self, expression: exp.Pad) -> str:
    4064        prefix = "L" if expression.args.get("is_left") else "R"
    4065
    4066        fill_pattern = self.sql(expression, "fill_pattern") or None
    4067        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
    4068            fill_pattern = "' '"
    4069
    4070        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)