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        return f"UNIQUE{this}{index_type}{on_conflict}"
     965
     966    def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
     967        return self.sql(expression, "this")
     968
     969    def create_sql(self, expression: exp.Create) -> str:
     970        kind = self.sql(expression, "kind")
     971        properties = expression.args.get("properties")
     972        properties_locs = self.locate_properties(properties) if properties else defaultdict()
     973
     974        this = self.createable_sql(expression, properties_locs)
     975
     976        properties_sql = ""
     977        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
     978            exp.Properties.Location.POST_WITH
     979        ):
     980            properties_sql = self.sql(
     981                exp.Properties(
     982                    expressions=[
     983                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
     984                        *properties_locs[exp.Properties.Location.POST_WITH],
     985                    ]
     986                )
     987            )
     988
     989            if properties_locs.get(exp.Properties.Location.POST_SCHEMA):
     990                properties_sql = self.sep() + properties_sql
     991            elif not self.pretty:
     992                # Standalone POST_WITH properties need a leading whitespace in non-pretty mode
     993                properties_sql = f" {properties_sql}"
     994
     995        begin = " BEGIN" if expression.args.get("begin") else ""
     996        end = " END" if expression.args.get("end") else ""
     997
     998        expression_sql = self.sql(expression, "expression")
     999        if expression_sql:
    1000            expression_sql = f"{begin}{self.sep()}{expression_sql}{end}"
    1001
    1002            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
    1003                postalias_props_sql = ""
    1004                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
    1005                    postalias_props_sql = self.properties(
    1006                        exp.Properties(
    1007                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
    1008                        ),
    1009                        wrapped=False,
    1010                    )
    1011                postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else ""
    1012                expression_sql = f" AS{postalias_props_sql}{expression_sql}"
    1013
    1014        postindex_props_sql = ""
    1015        if properties_locs.get(exp.Properties.Location.POST_INDEX):
    1016            postindex_props_sql = self.properties(
    1017                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
    1018                wrapped=False,
    1019                prefix=" ",
    1020            )
    1021
    1022        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
    1023        indexes = f" {indexes}" if indexes else ""
    1024        index_sql = indexes + postindex_props_sql
    1025
    1026        replace = " OR REPLACE" if expression.args.get("replace") else ""
    1027        unique = " UNIQUE" if expression.args.get("unique") else ""
    1028
    1029        postcreate_props_sql = ""
    1030        if properties_locs.get(exp.Properties.Location.POST_CREATE):
    1031            postcreate_props_sql = self.properties(
    1032                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
    1033                sep=" ",
    1034                prefix=" ",
    1035                wrapped=False,
    1036            )
    1037
    1038        modifiers = "".join((replace, unique, postcreate_props_sql))
    1039
    1040        postexpression_props_sql = ""
    1041        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
    1042            postexpression_props_sql = self.properties(
    1043                exp.Properties(
    1044                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
    1045                ),
    1046                sep=" ",
    1047                prefix=" ",
    1048                wrapped=False,
    1049            )
    1050
    1051        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    1052        no_schema_binding = (
    1053            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
    1054        )
    1055
    1056        clone = self.sql(expression, "clone")
    1057        clone = f" {clone}" if clone else ""
    1058
    1059        expression_sql = f"CREATE{modifiers} {kind}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
    1060        return self.prepend_ctes(expression, expression_sql)
    1061
    1062    def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str:
    1063        start = self.sql(expression, "start")
    1064        start = f"START WITH {start}" if start else ""
    1065        increment = self.sql(expression, "increment")
    1066        increment = f" INCREMENT BY {increment}" if increment else ""
    1067        minvalue = self.sql(expression, "minvalue")
    1068        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    1069        maxvalue = self.sql(expression, "maxvalue")
    1070        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    1071        owned = self.sql(expression, "owned")
    1072        owned = f" OWNED BY {owned}" if owned else ""
    1073
    1074        cache = expression.args.get("cache")
    1075        if cache is None:
    1076            cache_str = ""
    1077        elif cache is True:
    1078            cache_str = " CACHE"
    1079        else:
    1080            cache_str = f" CACHE {cache}"
    1081
    1082        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1083        options = f" {options}" if options else ""
    1084
    1085        return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()
    1086
    1087    def clone_sql(self, expression: exp.Clone) -> str:
    1088        this = self.sql(expression, "this")
    1089        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    1090        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
    1091        return f"{shallow}{keyword} {this}"
    1092
    1093    def describe_sql(self, expression: exp.Describe) -> str:
    1094        style = expression.args.get("style")
    1095        style = f" {style}" if style else ""
    1096        return f"DESCRIBE{style} {self.sql(expression, 'this')}"
    1097
    1098    def heredoc_sql(self, expression: exp.Heredoc) -> str:
    1099        tag = self.sql(expression, "tag")
    1100        return f"${tag}${self.sql(expression, 'this')}${tag}$"
    1101
    1102    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    1103        with_ = self.sql(expression, "with")
    1104        if with_:
    1105            sql = f"{with_}{self.sep()}{sql}"
    1106        return sql
    1107
    1108    def with_sql(self, expression: exp.With) -> str:
    1109        sql = self.expressions(expression, flat=True)
    1110        recursive = (
    1111            "RECURSIVE "
    1112            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
    1113            else ""
    1114        )
    1115
    1116        return f"WITH {recursive}{sql}"
    1117
    1118    def cte_sql(self, expression: exp.CTE) -> str:
    1119        alias = self.sql(expression, "alias")
    1120
    1121        materialized = expression.args.get("materialized")
    1122        if materialized is False:
    1123            materialized = "NOT MATERIALIZED "
    1124        elif materialized:
    1125            materialized = "MATERIALIZED "
    1126
    1127        return f"{alias} AS {materialized or ''}{self.wrap(expression)}"
    1128
    1129    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    1130        alias = self.sql(expression, "this")
    1131        columns = self.expressions(expression, key="columns", flat=True)
    1132        columns = f"({columns})" if columns else ""
    1133
    1134        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
    1135            columns = ""
    1136            self.unsupported("Named columns are not supported in table alias.")
    1137
    1138        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
    1139            alias = self._next_name()
    1140
    1141        return f"{alias}{columns}"
    1142
    1143    def bitstring_sql(self, expression: exp.BitString) -> str:
    1144        this = self.sql(expression, "this")
    1145        if self.dialect.BIT_START:
    1146            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    1147        return f"{int(this, 2)}"
    1148
    1149    def hexstring_sql(self, expression: exp.HexString) -> str:
    1150        this = self.sql(expression, "this")
    1151        if self.dialect.HEX_START:
    1152            return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
    1153        return f"{int(this, 16)}"
    1154
    1155    def bytestring_sql(self, expression: exp.ByteString) -> str:
    1156        this = self.sql(expression, "this")
    1157        if self.dialect.BYTE_START:
    1158            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    1159        return this
    1160
    1161    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
    1162        this = self.sql(expression, "this")
    1163        escape = expression.args.get("escape")
    1164
    1165        if self.dialect.UNICODE_START:
    1166            escape_substitute = r"\\\1"
    1167            left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END
    1168        else:
    1169            escape_substitute = r"\\u\1"
    1170            left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END
    1171
    1172        if escape:
    1173            escape_pattern = re.compile(rf"{escape.name}(\d+)")
    1174            escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else ""
    1175        else:
    1176            escape_pattern = ESCAPED_UNICODE_RE
    1177            escape_sql = ""
    1178
    1179        if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE):
    1180            this = escape_pattern.sub(escape_substitute, this)
    1181
    1182        return f"{left_quote}{this}{right_quote}{escape_sql}"
    1183
    1184    def rawstring_sql(self, expression: exp.RawString) -> str:
    1185        string = self.escape_str(expression.this.replace("\\", "\\\\"), escape_backslash=False)
    1186        return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}"
    1187
    1188    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    1189        this = self.sql(expression, "this")
    1190        specifier = self.sql(expression, "expression")
    1191        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    1192        return f"{this}{specifier}"
    1193
    1194    def datatype_sql(self, expression: exp.DataType) -> str:
    1195        type_value = expression.this
    1196
    1197        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
    1198            type_sql = self.sql(expression, "kind")
    1199        else:
    1200            type_sql = (
    1201                self.TYPE_MAPPING.get(type_value, type_value.value)
    1202                if isinstance(type_value, exp.DataType.Type)
    1203                else type_value
    1204            )
    1205
    1206        nested = ""
    1207        interior = self.expressions(expression, flat=True)
    1208        values = ""
    1209
    1210        if interior:
    1211            if expression.args.get("nested"):
    1212                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    1213                if expression.args.get("values") is not None:
    1214                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    1215                    values = self.expressions(expression, key="values", flat=True)
    1216                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    1217            elif type_value == exp.DataType.Type.INTERVAL:
    1218                nested = f" {interior}"
    1219            else:
    1220                nested = f"({interior})"
    1221
    1222        type_sql = f"{type_sql}{nested}{values}"
    1223        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
    1224            exp.DataType.Type.TIMETZ,
    1225            exp.DataType.Type.TIMESTAMPTZ,
    1226        ):
    1227            type_sql = f"{type_sql} WITH TIME ZONE"
    1228
    1229        return type_sql
    1230
    1231    def directory_sql(self, expression: exp.Directory) -> str:
    1232        local = "LOCAL " if expression.args.get("local") else ""
    1233        row_format = self.sql(expression, "row_format")
    1234        row_format = f" {row_format}" if row_format else ""
    1235        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"
    1236
    1237    def delete_sql(self, expression: exp.Delete) -> str:
    1238        this = self.sql(expression, "this")
    1239        this = f" FROM {this}" if this else ""
    1240        using = self.sql(expression, "using")
    1241        using = f" USING {using}" if using else ""
    1242        where = self.sql(expression, "where")
    1243        returning = self.sql(expression, "returning")
    1244        limit = self.sql(expression, "limit")
    1245        tables = self.expressions(expression, key="tables")
    1246        tables = f" {tables}" if tables else ""
    1247        if self.RETURNING_END:
    1248            expression_sql = f"{this}{using}{where}{returning}{limit}"
    1249        else:
    1250            expression_sql = f"{returning}{this}{using}{where}{limit}"
    1251        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")
    1252
    1253    def drop_sql(self, expression: exp.Drop) -> str:
    1254        this = self.sql(expression, "this")
    1255        expressions = self.expressions(expression, flat=True)
    1256        expressions = f" ({expressions})" if expressions else ""
    1257        kind = expression.args["kind"]
    1258        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    1259        on_cluster = self.sql(expression, "cluster")
    1260        on_cluster = f" {on_cluster}" if on_cluster else ""
    1261        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1262        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    1263        cascade = " CASCADE" if expression.args.get("cascade") else ""
    1264        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    1265        purge = " PURGE" if expression.args.get("purge") else ""
    1266        return f"DROP{temporary}{materialized} {kind}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}"
    1267
    1268    def except_sql(self, expression: exp.Except) -> str:
    1269        return self.set_operations(expression)
    1270
    1271    def except_op(self, expression: exp.Except) -> str:
    1272        return f"EXCEPT{'' if expression.args.get('distinct') else ' ALL'}"
    1273
    1274    def fetch_sql(self, expression: exp.Fetch) -> str:
    1275        direction = expression.args.get("direction")
    1276        direction = f" {direction}" if direction else ""
    1277        count = expression.args.get("count")
    1278        count = f" {count}" if count else ""
    1279        if expression.args.get("percent"):
    1280            count = f"{count} PERCENT"
    1281        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    1282        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"
    1283
    1284    def filter_sql(self, expression: exp.Filter) -> str:
    1285        if self.AGGREGATE_FILTER_SUPPORTED:
    1286            this = self.sql(expression, "this")
    1287            where = self.sql(expression, "expression").strip()
    1288            return f"{this} FILTER({where})"
    1289
    1290        agg = expression.this
    1291        agg_arg = agg.this
    1292        cond = expression.expression.this
    1293        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1294        return self.sql(agg)
    1295
    1296    def hint_sql(self, expression: exp.Hint) -> str:
    1297        if not self.QUERY_HINTS:
    1298            self.unsupported("Hints are not supported")
    1299            return ""
    1300
    1301        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"
    1302
    1303    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
    1304        using = self.sql(expression, "using")
    1305        using = f" USING {using}" if using else ""
    1306        columns = self.expressions(expression, key="columns", flat=True)
    1307        columns = f"({columns})" if columns else ""
    1308        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1309        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1310        where = self.sql(expression, "where")
    1311        include = self.expressions(expression, key="include", flat=True)
    1312        if include:
    1313            include = f" INCLUDE ({include})"
    1314        with_storage = self.expressions(expression, key="with_storage", flat=True)
    1315        with_storage = f" WITH ({with_storage})" if with_storage else ""
    1316        tablespace = self.sql(expression, "tablespace")
    1317        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
    1318        on = self.sql(expression, "on")
    1319        on = f" ON {on}" if on else ""
    1320
    1321        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"
    1322
    1323    def index_sql(self, expression: exp.Index) -> str:
    1324        unique = "UNIQUE " if expression.args.get("unique") else ""
    1325        primary = "PRIMARY " if expression.args.get("primary") else ""
    1326        amp = "AMP " if expression.args.get("amp") else ""
    1327        name = self.sql(expression, "this")
    1328        name = f"{name} " if name else ""
    1329        table = self.sql(expression, "table")
    1330        table = f"{self.INDEX_ON} {table}" if table else ""
    1331
    1332        index = "INDEX " if not table else ""
    1333
    1334        params = self.sql(expression, "params")
    1335        return f"{unique}{primary}{amp}{index}{name}{table}{params}"
    1336
    1337    def identifier_sql(self, expression: exp.Identifier) -> str:
    1338        text = expression.name
    1339        lower = text.lower()
    1340        text = lower if self.normalize and not expression.quoted else text
    1341        text = text.replace(self.dialect.IDENTIFIER_END, self._escaped_identifier_end)
    1342        if (
    1343            expression.quoted
    1344            or self.dialect.can_identify(text, self.identify)
    1345            or lower in self.RESERVED_KEYWORDS
    1346            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1347        ):
    1348            text = f"{self.dialect.IDENTIFIER_START}{text}{self.dialect.IDENTIFIER_END}"
    1349        return text
    1350
    1351    def hex_sql(self, expression: exp.Hex) -> str:
    1352        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1353        if self.dialect.HEX_LOWERCASE:
    1354            text = self.func("LOWER", text)
    1355
    1356        return text
    1357
    1358    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
    1359        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1360        if not self.dialect.HEX_LOWERCASE:
    1361            text = self.func("LOWER", text)
    1362        return text
    1363
    1364    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1365        input_format = self.sql(expression, "input_format")
    1366        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1367        output_format = self.sql(expression, "output_format")
    1368        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1369        return self.sep().join((input_format, output_format))
    1370
    1371    def national_sql(self, expression: exp.National, prefix: str = "N") -> str:
    1372        string = self.sql(exp.Literal.string(expression.name))
    1373        return f"{prefix}{string}"
    1374
    1375    def partition_sql(self, expression: exp.Partition) -> str:
    1376        return f"PARTITION({self.expressions(expression, flat=True)})"
    1377
    1378    def properties_sql(self, expression: exp.Properties) -> str:
    1379        root_properties = []
    1380        with_properties = []
    1381
    1382        for p in expression.expressions:
    1383            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1384            if p_loc == exp.Properties.Location.POST_WITH:
    1385                with_properties.append(p)
    1386            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1387                root_properties.append(p)
    1388
    1389        root_props = self.root_properties(exp.Properties(expressions=root_properties))
    1390        with_props = self.with_properties(exp.Properties(expressions=with_properties))
    1391
    1392        if root_props and with_props and not self.pretty:
    1393            with_props = " " + with_props
    1394
    1395        return root_props + with_props
    1396
    1397    def root_properties(self, properties: exp.Properties) -> str:
    1398        if properties.expressions:
    1399            return self.expressions(properties, indent=False, sep=" ")
    1400        return ""
    1401
    1402    def properties(
    1403        self,
    1404        properties: exp.Properties,
    1405        prefix: str = "",
    1406        sep: str = ", ",
    1407        suffix: str = "",
    1408        wrapped: bool = True,
    1409    ) -> str:
    1410        if properties.expressions:
    1411            expressions = self.expressions(properties, sep=sep, indent=False)
    1412            if expressions:
    1413                expressions = self.wrap(expressions) if wrapped else expressions
    1414                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1415        return ""
    1416
    1417    def with_properties(self, properties: exp.Properties) -> str:
    1418        return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep=""))
    1419
    1420    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1421        properties_locs = defaultdict(list)
    1422        for p in properties.expressions:
    1423            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1424            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1425                properties_locs[p_loc].append(p)
    1426            else:
    1427                self.unsupported(f"Unsupported property {p.key}")
    1428
    1429        return properties_locs
    1430
    1431    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1432        if isinstance(expression.this, exp.Dot):
    1433            return self.sql(expression, "this")
    1434        return f"'{expression.name}'" if string_key else expression.name
    1435
    1436    def property_sql(self, expression: exp.Property) -> str:
    1437        property_cls = expression.__class__
    1438        if property_cls == exp.Property:
    1439            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1440
    1441        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1442        if not property_name:
    1443            self.unsupported(f"Unsupported property {expression.key}")
    1444
    1445        return f"{property_name}={self.sql(expression, 'this')}"
    1446
    1447    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1448        if self.SUPPORTS_CREATE_TABLE_LIKE:
    1449            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1450            options = f" {options}" if options else ""
    1451
    1452            like = f"LIKE {self.sql(expression, 'this')}{options}"
    1453            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
    1454                like = f"({like})"
    1455
    1456            return like
    1457
    1458        if expression.expressions:
    1459            self.unsupported("Transpilation of LIKE property options is unsupported")
    1460
    1461        select = exp.select("*").from_(expression.this).limit(0)
    1462        return f"AS {self.sql(select)}"
    1463
    1464    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1465        no = "NO " if expression.args.get("no") else ""
    1466        protection = " PROTECTION" if expression.args.get("protection") else ""
    1467        return f"{no}FALLBACK{protection}"
    1468
    1469    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1470        no = "NO " if expression.args.get("no") else ""
    1471        local = expression.args.get("local")
    1472        local = f"{local} " if local else ""
    1473        dual = "DUAL " if expression.args.get("dual") else ""
    1474        before = "BEFORE " if expression.args.get("before") else ""
    1475        after = "AFTER " if expression.args.get("after") else ""
    1476        return f"{no}{local}{dual}{before}{after}JOURNAL"
    1477
    1478    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1479        freespace = self.sql(expression, "this")
    1480        percent = " PERCENT" if expression.args.get("percent") else ""
    1481        return f"FREESPACE={freespace}{percent}"
    1482
    1483    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1484        if expression.args.get("default"):
    1485            property = "DEFAULT"
    1486        elif expression.args.get("on"):
    1487            property = "ON"
    1488        else:
    1489            property = "OFF"
    1490        return f"CHECKSUM={property}"
    1491
    1492    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1493        if expression.args.get("no"):
    1494            return "NO MERGEBLOCKRATIO"
    1495        if expression.args.get("default"):
    1496            return "DEFAULT MERGEBLOCKRATIO"
    1497
    1498        percent = " PERCENT" if expression.args.get("percent") else ""
    1499        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
    1500
    1501    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1502        default = expression.args.get("default")
    1503        minimum = expression.args.get("minimum")
    1504        maximum = expression.args.get("maximum")
    1505        if default or minimum or maximum:
    1506            if default:
    1507                prop = "DEFAULT"
    1508            elif minimum:
    1509                prop = "MINIMUM"
    1510            else:
    1511                prop = "MAXIMUM"
    1512            return f"{prop} DATABLOCKSIZE"
    1513        units = expression.args.get("units")
    1514        units = f" {units}" if units else ""
    1515        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
    1516
    1517    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1518        autotemp = expression.args.get("autotemp")
    1519        always = expression.args.get("always")
    1520        default = expression.args.get("default")
    1521        manual = expression.args.get("manual")
    1522        never = expression.args.get("never")
    1523
    1524        if autotemp is not None:
    1525            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1526        elif always:
    1527            prop = "ALWAYS"
    1528        elif default:
    1529            prop = "DEFAULT"
    1530        elif manual:
    1531            prop = "MANUAL"
    1532        elif never:
    1533            prop = "NEVER"
    1534        return f"BLOCKCOMPRESSION={prop}"
    1535
    1536    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1537        no = expression.args.get("no")
    1538        no = " NO" if no else ""
    1539        concurrent = expression.args.get("concurrent")
    1540        concurrent = " CONCURRENT" if concurrent else ""
    1541        target = self.sql(expression, "target")
    1542        target = f" {target}" if target else ""
    1543        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"
    1544
    1545    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1546        if isinstance(expression.this, list):
    1547            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1548        if expression.this:
    1549            modulus = self.sql(expression, "this")
    1550            remainder = self.sql(expression, "expression")
    1551            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1552
    1553        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1554        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1555        return f"FROM ({from_expressions}) TO ({to_expressions})"
    1556
    1557    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1558        this = self.sql(expression, "this")
    1559
    1560        for_values_or_default = expression.expression
    1561        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1562            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1563        else:
    1564            for_values_or_default = " DEFAULT"
    1565
    1566        return f"PARTITION OF {this}{for_values_or_default}"
    1567
    1568    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1569        kind = expression.args.get("kind")
    1570        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1571        for_or_in = expression.args.get("for_or_in")
    1572        for_or_in = f" {for_or_in}" if for_or_in else ""
    1573        lock_type = expression.args.get("lock_type")
    1574        override = " OVERRIDE" if expression.args.get("override") else ""
    1575        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"
    1576
    1577    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1578        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1579        statistics = expression.args.get("statistics")
    1580        statistics_sql = ""
    1581        if statistics is not None:
    1582            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1583        return f"{data_sql}{statistics_sql}"
    1584
    1585    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1586        this = self.sql(expression, "this")
    1587        this = f"HISTORY_TABLE={this}" if this else ""
    1588        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
    1589        data_consistency = (
    1590            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
    1591        )
    1592        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    1593        retention_period = (
    1594            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
    1595        )
    1596
    1597        if this:
    1598            on_sql = self.func("ON", this, data_consistency, retention_period)
    1599        else:
    1600            on_sql = "ON" if expression.args.get("on") else "OFF"
    1601
    1602        sql = f"SYSTEM_VERSIONING={on_sql}"
    1603
    1604        return f"WITH({sql})" if expression.args.get("with") else sql
    1605
    1606    def insert_sql(self, expression: exp.Insert) -> str:
    1607        hint = self.sql(expression, "hint")
    1608        overwrite = expression.args.get("overwrite")
    1609
    1610        if isinstance(expression.this, exp.Directory):
    1611            this = " OVERWRITE" if overwrite else " INTO"
    1612        else:
    1613            this = self.INSERT_OVERWRITE if overwrite else " INTO"
    1614
    1615        stored = self.sql(expression, "stored")
    1616        stored = f" {stored}" if stored else ""
    1617        alternative = expression.args.get("alternative")
    1618        alternative = f" OR {alternative}" if alternative else ""
    1619        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1620        is_function = expression.args.get("is_function")
    1621        if is_function:
    1622            this = f"{this} FUNCTION"
    1623        this = f"{this} {self.sql(expression, 'this')}"
    1624
    1625        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1626        where = self.sql(expression, "where")
    1627        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1628        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1629        on_conflict = self.sql(expression, "conflict")
    1630        on_conflict = f" {on_conflict}" if on_conflict else ""
    1631        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1632        returning = self.sql(expression, "returning")
    1633
    1634        if self.RETURNING_END:
    1635            expression_sql = f"{expression_sql}{on_conflict}{returning}"
    1636        else:
    1637            expression_sql = f"{returning}{expression_sql}{on_conflict}"
    1638
    1639        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{where}{expression_sql}"
    1640        return self.prepend_ctes(expression, sql)
    1641
    1642    def intersect_sql(self, expression: exp.Intersect) -> str:
    1643        return self.set_operations(expression)
    1644
    1645    def intersect_op(self, expression: exp.Intersect) -> str:
    1646        return f"INTERSECT{'' if expression.args.get('distinct') else ' ALL'}"
    1647
    1648    def introducer_sql(self, expression: exp.Introducer) -> str:
    1649        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
    1650
    1651    def kill_sql(self, expression: exp.Kill) -> str:
    1652        kind = self.sql(expression, "kind")
    1653        kind = f" {kind}" if kind else ""
    1654        this = self.sql(expression, "this")
    1655        this = f" {this}" if this else ""
    1656        return f"KILL{kind}{this}"
    1657
    1658    def pseudotype_sql(self, expression: exp.PseudoType) -> str:
    1659        return expression.name
    1660
    1661    def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str:
    1662        return expression.name
    1663
    1664    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1665        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1666
    1667        constraint = self.sql(expression, "constraint")
    1668        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
    1669
    1670        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
    1671        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
    1672        action = self.sql(expression, "action")
    1673
    1674        expressions = self.expressions(expression, flat=True)
    1675        if expressions:
    1676            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1677            expressions = f" {set_keyword}{expressions}"
    1678
    1679        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}"
    1680
    1681    def returning_sql(self, expression: exp.Returning) -> str:
    1682        return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}"
    1683
    1684    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1685        fields = self.sql(expression, "fields")
    1686        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1687        escaped = self.sql(expression, "escaped")
    1688        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1689        items = self.sql(expression, "collection_items")
    1690        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1691        keys = self.sql(expression, "map_keys")
    1692        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1693        lines = self.sql(expression, "lines")
    1694        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1695        null = self.sql(expression, "null")
    1696        null = f" NULL DEFINED AS {null}" if null else ""
    1697        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
    1698
    1699    def withtablehint_sql(self, expression: exp.WithTableHint) -> str:
    1700        return f"WITH ({self.expressions(expression, flat=True)})"
    1701
    1702    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1703        this = f"{self.sql(expression, 'this')} INDEX"
    1704        target = self.sql(expression, "target")
    1705        target = f" FOR {target}" if target else ""
    1706        return f"{this}{target} ({self.expressions(expression, flat=True)})"
    1707
    1708    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1709        this = self.sql(expression, "this")
    1710        kind = self.sql(expression, "kind")
    1711        expr = self.sql(expression, "expression")
    1712        return f"{this} ({kind} => {expr})"
    1713
    1714    def table_parts(self, expression: exp.Table) -> str:
    1715        return ".".join(
    1716            self.sql(part)
    1717            for part in (
    1718                expression.args.get("catalog"),
    1719                expression.args.get("db"),
    1720                expression.args.get("this"),
    1721            )
    1722            if part is not None
    1723        )
    1724
    1725    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1726        table = self.table_parts(expression)
    1727        only = "ONLY " if expression.args.get("only") else ""
    1728        partition = self.sql(expression, "partition")
    1729        partition = f" {partition}" if partition else ""
    1730        version = self.sql(expression, "version")
    1731        version = f" {version}" if version else ""
    1732        alias = self.sql(expression, "alias")
    1733        alias = f"{sep}{alias}" if alias else ""
    1734        hints = self.expressions(expression, key="hints", sep=" ")
    1735        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1736        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1737        pivots = f" {pivots}" if pivots else ""
    1738        joins = self.indent(
    1739            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    1740        )
    1741        laterals = self.expressions(expression, key="laterals", sep="")
    1742
    1743        file_format = self.sql(expression, "format")
    1744        if file_format:
    1745            pattern = self.sql(expression, "pattern")
    1746            pattern = f", PATTERN => {pattern}" if pattern else ""
    1747            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    1748
    1749        ordinality = expression.args.get("ordinality") or ""
    1750        if ordinality:
    1751            ordinality = f" WITH ORDINALITY{alias}"
    1752            alias = ""
    1753
    1754        when = self.sql(expression, "when")
    1755        if when:
    1756            table = f"{table} {when}"
    1757
    1758        changes = self.sql(expression, "changes")
    1759        changes = f" {changes}" if changes else ""
    1760
    1761        rows_from = self.expressions(expression, key="rows_from")
    1762        if rows_from:
    1763            table = f"ROWS FROM {self.wrap(rows_from)}"
    1764
    1765        return f"{only}{table}{changes}{partition}{version}{file_format}{alias}{hints}{pivots}{joins}{laterals}{ordinality}"
    1766
    1767    def tablesample_sql(
    1768        self,
    1769        expression: exp.TableSample,
    1770        sep: str = " AS ",
    1771        tablesample_keyword: t.Optional[str] = None,
    1772    ) -> str:
    1773        if self.dialect.ALIAS_POST_TABLESAMPLE and expression.this and expression.this.alias:
    1774            table = expression.this.copy()
    1775            table.set("alias", None)
    1776            this = self.sql(table)
    1777            alias = f"{sep}{self.sql(expression.this, 'alias')}"
    1778        else:
    1779            this = self.sql(expression, "this")
    1780            alias = ""
    1781
    1782        method = self.sql(expression, "method")
    1783        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1784        numerator = self.sql(expression, "bucket_numerator")
    1785        denominator = self.sql(expression, "bucket_denominator")
    1786        field = self.sql(expression, "bucket_field")
    1787        field = f" ON {field}" if field else ""
    1788        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1789        seed = self.sql(expression, "seed")
    1790        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
    1791
    1792        size = self.sql(expression, "size")
    1793        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
    1794            size = f"{size} ROWS"
    1795
    1796        percent = self.sql(expression, "percent")
    1797        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
    1798            percent = f"{percent} PERCENT"
    1799
    1800        expr = f"{bucket}{percent}{size}"
    1801        if self.TABLESAMPLE_REQUIRES_PARENS:
    1802            expr = f"({expr})"
    1803
    1804        return (
    1805            f"{this} {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}{alias}"
    1806        )
    1807
    1808    def pivot_sql(self, expression: exp.Pivot) -> str:
    1809        expressions = self.expressions(expression, flat=True)
    1810
    1811        if expression.this:
    1812            this = self.sql(expression, "this")
    1813            if not expressions:
    1814                return f"UNPIVOT {this}"
    1815
    1816            on = f"{self.seg('ON')} {expressions}"
    1817            using = self.expressions(expression, key="using", flat=True)
    1818            using = f"{self.seg('USING')} {using}" if using else ""
    1819            group = self.sql(expression, "group")
    1820            return f"PIVOT {this}{on}{using}{group}"
    1821
    1822        alias = self.sql(expression, "alias")
    1823        alias = f" AS {alias}" if alias else ""
    1824        direction = "UNPIVOT" if expression.unpivot else "PIVOT"
    1825        field = self.sql(expression, "field")
    1826        include_nulls = expression.args.get("include_nulls")
    1827        if include_nulls is not None:
    1828            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    1829        else:
    1830            nulls = ""
    1831        return f"{direction}{nulls}({expressions} FOR {field}){alias}"
    1832
    1833    def version_sql(self, expression: exp.Version) -> str:
    1834        this = f"FOR {expression.name}"
    1835        kind = expression.text("kind")
    1836        expr = self.sql(expression, "expression")
    1837        return f"{this} {kind} {expr}"
    1838
    1839    def tuple_sql(self, expression: exp.Tuple) -> str:
    1840        return f"({self.expressions(expression, flat=True)})"
    1841
    1842    def update_sql(self, expression: exp.Update) -> str:
    1843        this = self.sql(expression, "this")
    1844        set_sql = self.expressions(expression, flat=True)
    1845        from_sql = self.sql(expression, "from")
    1846        where_sql = self.sql(expression, "where")
    1847        returning = self.sql(expression, "returning")
    1848        order = self.sql(expression, "order")
    1849        limit = self.sql(expression, "limit")
    1850        if self.RETURNING_END:
    1851            expression_sql = f"{from_sql}{where_sql}{returning}"
    1852        else:
    1853            expression_sql = f"{returning}{from_sql}{where_sql}"
    1854        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    1855        return self.prepend_ctes(expression, sql)
    1856
    1857    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
    1858        values_as_table = values_as_table and self.VALUES_AS_TABLE
    1859
    1860        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    1861        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
    1862            args = self.expressions(expression)
    1863            alias = self.sql(expression, "alias")
    1864            values = f"VALUES{self.seg('')}{args}"
    1865            values = (
    1866                f"({values})"
    1867                if self.WRAP_DERIVED_VALUES and (alias or isinstance(expression.parent, exp.From))
    1868                else values
    1869            )
    1870            return f"{values} AS {alias}" if alias else values
    1871
    1872        # Converts `VALUES...` expression into a series of select unions.
    1873        alias_node = expression.args.get("alias")
    1874        column_names = alias_node and alias_node.columns
    1875
    1876        selects: t.List[exp.Query] = []
    1877
    1878        for i, tup in enumerate(expression.expressions):
    1879            row = tup.expressions
    1880
    1881            if i == 0 and column_names:
    1882                row = [
    1883                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    1884                ]
    1885
    1886            selects.append(exp.Select(expressions=row))
    1887
    1888        if self.pretty:
    1889            # This may result in poor performance for large-cardinality `VALUES` tables, due to
    1890            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
    1891            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
    1892            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
    1893            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
    1894
    1895        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
    1896        unions = " UNION ALL ".join(self.sql(select) for select in selects)
    1897        return f"({unions}){alias}"
    1898
    1899    def var_sql(self, expression: exp.Var) -> str:
    1900        return self.sql(expression, "this")
    1901
    1902    def into_sql(self, expression: exp.Into) -> str:
    1903        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1904        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
    1905        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
    1906
    1907    def from_sql(self, expression: exp.From) -> str:
    1908        return f"{self.seg('FROM')} {self.sql(expression, 'this')}"
    1909
    1910    def group_sql(self, expression: exp.Group) -> str:
    1911        group_by_all = expression.args.get("all")
    1912        if group_by_all is True:
    1913            modifier = " ALL"
    1914        elif group_by_all is False:
    1915            modifier = " DISTINCT"
    1916        else:
    1917            modifier = ""
    1918
    1919        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
    1920
    1921        grouping_sets = self.expressions(expression, key="grouping_sets", indent=False)
    1922        grouping_sets = (
    1923            f"{self.seg('GROUPING SETS')} {self.wrap(grouping_sets)}" if grouping_sets else ""
    1924        )
    1925
    1926        cube = expression.args.get("cube", [])
    1927        if seq_get(cube, 0) is True:
    1928            return f"{group_by}{self.seg('WITH CUBE')}"
    1929        else:
    1930            cube_sql = self.expressions(expression, key="cube", indent=False)
    1931            cube_sql = f"{self.seg('CUBE')} {self.wrap(cube_sql)}" if cube_sql else ""
    1932
    1933        rollup = expression.args.get("rollup", [])
    1934        if seq_get(rollup, 0) is True:
    1935            return f"{group_by}{self.seg('WITH ROLLUP')}"
    1936        else:
    1937            rollup_sql = self.expressions(expression, key="rollup", indent=False)
    1938            rollup_sql = f"{self.seg('ROLLUP')} {self.wrap(rollup_sql)}" if rollup_sql else ""
    1939
    1940        groupings = csv(
    1941            grouping_sets,
    1942            cube_sql,
    1943            rollup_sql,
    1944            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    1945            sep=self.GROUPINGS_SEP,
    1946        )
    1947
    1948        if expression.args.get("expressions") and groupings:
    1949            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    1950
    1951        return f"{group_by}{groupings}"
    1952
    1953    def having_sql(self, expression: exp.Having) -> str:
    1954        this = self.indent(self.sql(expression, "this"))
    1955        return f"{self.seg('HAVING')}{self.sep()}{this}"
    1956
    1957    def connect_sql(self, expression: exp.Connect) -> str:
    1958        start = self.sql(expression, "start")
    1959        start = self.seg(f"START WITH {start}") if start else ""
    1960        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
    1961        connect = self.sql(expression, "connect")
    1962        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
    1963        return start + connect
    1964
    1965    def prior_sql(self, expression: exp.Prior) -> str:
    1966        return f"PRIOR {self.sql(expression, 'this')}"
    1967
    1968    def join_sql(self, expression: exp.Join) -> str:
    1969        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    1970            side = None
    1971        else:
    1972            side = expression.side
    1973
    1974        op_sql = " ".join(
    1975            op
    1976            for op in (
    1977                expression.method,
    1978                "GLOBAL" if expression.args.get("global") else None,
    1979                side,
    1980                expression.kind,
    1981                expression.hint if self.JOIN_HINTS else None,
    1982            )
    1983            if op
    1984        )
    1985        match_cond = self.sql(expression, "match_condition")
    1986        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
    1987        on_sql = self.sql(expression, "on")
    1988        using = expression.args.get("using")
    1989
    1990        if not on_sql and using:
    1991            on_sql = csv(*(self.sql(column) for column in using))
    1992
    1993        this = expression.this
    1994        this_sql = self.sql(this)
    1995
    1996        if on_sql:
    1997            on_sql = self.indent(on_sql, skip_first=True)
    1998            space = self.seg(" " * self.pad) if self.pretty else " "
    1999            if using:
    2000                on_sql = f"{space}USING ({on_sql})"
    2001            else:
    2002                on_sql = f"{space}ON {on_sql}"
    2003        elif not op_sql:
    2004            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
    2005                return f" {this_sql}"
    2006
    2007            return f", {this_sql}"
    2008
    2009        if op_sql != "STRAIGHT_JOIN":
    2010            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    2011
    2012        return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}"
    2013
    2014    def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str:
    2015        args = self.expressions(expression, flat=True)
    2016        args = f"({args})" if len(args.split(",")) > 1 else args
    2017        return f"{args} {arrow_sep} {self.sql(expression, 'this')}"
    2018
    2019    def lateral_op(self, expression: exp.Lateral) -> str:
    2020        cross_apply = expression.args.get("cross_apply")
    2021
    2022        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    2023        if cross_apply is True:
    2024            op = "INNER JOIN "
    2025        elif cross_apply is False:
    2026            op = "LEFT JOIN "
    2027        else:
    2028            op = ""
    2029
    2030        return f"{op}LATERAL"
    2031
    2032    def lateral_sql(self, expression: exp.Lateral) -> str:
    2033        this = self.sql(expression, "this")
    2034
    2035        if expression.args.get("view"):
    2036            alias = expression.args["alias"]
    2037            columns = self.expressions(alias, key="columns", flat=True)
    2038            table = f" {alias.name}" if alias.name else ""
    2039            columns = f" AS {columns}" if columns else ""
    2040            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    2041            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    2042
    2043        alias = self.sql(expression, "alias")
    2044        alias = f" AS {alias}" if alias else ""
    2045        return f"{self.lateral_op(expression)} {this}{alias}"
    2046
    2047    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    2048        this = self.sql(expression, "this")
    2049
    2050        args = [
    2051            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    2052            for e in (expression.args.get(k) for k in ("offset", "expression"))
    2053            if e
    2054        ]
    2055
    2056        args_sql = ", ".join(self.sql(e) for e in args)
    2057        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
    2058        expressions = self.expressions(expression, flat=True)
    2059        expressions = f" BY {expressions}" if expressions else ""
    2060
    2061        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}"
    2062
    2063    def offset_sql(self, expression: exp.Offset) -> str:
    2064        this = self.sql(expression, "this")
    2065        value = expression.expression
    2066        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    2067        expressions = self.expressions(expression, flat=True)
    2068        expressions = f" BY {expressions}" if expressions else ""
    2069        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"
    2070
    2071    def setitem_sql(self, expression: exp.SetItem) -> str:
    2072        kind = self.sql(expression, "kind")
    2073        kind = f"{kind} " if kind else ""
    2074        this = self.sql(expression, "this")
    2075        expressions = self.expressions(expression)
    2076        collate = self.sql(expression, "collate")
    2077        collate = f" COLLATE {collate}" if collate else ""
    2078        global_ = "GLOBAL " if expression.args.get("global") else ""
    2079        return f"{global_}{kind}{this}{expressions}{collate}"
    2080
    2081    def set_sql(self, expression: exp.Set) -> str:
    2082        expressions = (
    2083            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    2084        )
    2085        tag = " TAG" if expression.args.get("tag") else ""
    2086        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"
    2087
    2088    def pragma_sql(self, expression: exp.Pragma) -> str:
    2089        return f"PRAGMA {self.sql(expression, 'this')}"
    2090
    2091    def lock_sql(self, expression: exp.Lock) -> str:
    2092        if not self.LOCKING_READS_SUPPORTED:
    2093            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    2094            return ""
    2095
    2096        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    2097        expressions = self.expressions(expression, flat=True)
    2098        expressions = f" OF {expressions}" if expressions else ""
    2099        wait = expression.args.get("wait")
    2100
    2101        if wait is not None:
    2102            if isinstance(wait, exp.Literal):
    2103                wait = f" WAIT {self.sql(wait)}"
    2104            else:
    2105                wait = " NOWAIT" if wait else " SKIP LOCKED"
    2106
    2107        return f"{lock_type}{expressions}{wait or ''}"
    2108
    2109    def literal_sql(self, expression: exp.Literal) -> str:
    2110        text = expression.this or ""
    2111        if expression.is_string:
    2112            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    2113        return text
    2114
    2115    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
    2116        if self.dialect.ESCAPED_SEQUENCES:
    2117            to_escaped = self.dialect.ESCAPED_SEQUENCES
    2118            text = "".join(
    2119                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
    2120            )
    2121
    2122        return self._replace_line_breaks(text).replace(
    2123            self.dialect.QUOTE_END, self._escaped_quote_end
    2124        )
    2125
    2126    def loaddata_sql(self, expression: exp.LoadData) -> str:
    2127        local = " LOCAL" if expression.args.get("local") else ""
    2128        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    2129        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    2130        this = f" INTO TABLE {self.sql(expression, 'this')}"
    2131        partition = self.sql(expression, "partition")
    2132        partition = f" {partition}" if partition else ""
    2133        input_format = self.sql(expression, "input_format")
    2134        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    2135        serde = self.sql(expression, "serde")
    2136        serde = f" SERDE {serde}" if serde else ""
    2137        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
    2138
    2139    def null_sql(self, *_) -> str:
    2140        return "NULL"
    2141
    2142    def boolean_sql(self, expression: exp.Boolean) -> str:
    2143        return "TRUE" if expression.this else "FALSE"
    2144
    2145    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2146        this = self.sql(expression, "this")
    2147        this = f"{this} " if this else this
    2148        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2149        order = self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat)  # type: ignore
    2150        interpolated_values = [
    2151            f"{self.sql(named_expression, 'alias')} AS {self.sql(named_expression, 'this')}"
    2152            for named_expression in expression.args.get("interpolate") or []
    2153        ]
    2154        interpolate = (
    2155            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    2156        )
    2157        return f"{order}{interpolate}"
    2158
    2159    def withfill_sql(self, expression: exp.WithFill) -> str:
    2160        from_sql = self.sql(expression, "from")
    2161        from_sql = f" FROM {from_sql}" if from_sql else ""
    2162        to_sql = self.sql(expression, "to")
    2163        to_sql = f" TO {to_sql}" if to_sql else ""
    2164        step_sql = self.sql(expression, "step")
    2165        step_sql = f" STEP {step_sql}" if step_sql else ""
    2166        return f"WITH FILL{from_sql}{to_sql}{step_sql}"
    2167
    2168    def cluster_sql(self, expression: exp.Cluster) -> str:
    2169        return self.op_expressions("CLUSTER BY", expression)
    2170
    2171    def distribute_sql(self, expression: exp.Distribute) -> str:
    2172        return self.op_expressions("DISTRIBUTE BY", expression)
    2173
    2174    def sort_sql(self, expression: exp.Sort) -> str:
    2175        return self.op_expressions("SORT BY", expression)
    2176
    2177    def ordered_sql(self, expression: exp.Ordered) -> str:
    2178        desc = expression.args.get("desc")
    2179        asc = not desc
    2180
    2181        nulls_first = expression.args.get("nulls_first")
    2182        nulls_last = not nulls_first
    2183        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
    2184        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
    2185        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
    2186
    2187        this = self.sql(expression, "this")
    2188
    2189        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
    2190        nulls_sort_change = ""
    2191        if nulls_first and (
    2192            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    2193        ):
    2194            nulls_sort_change = " NULLS FIRST"
    2195        elif (
    2196            nulls_last
    2197            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    2198            and not nulls_are_last
    2199        ):
    2200            nulls_sort_change = " NULLS LAST"
    2201
    2202        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
    2203        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    2204            window = expression.find_ancestor(exp.Window, exp.Select)
    2205            if isinstance(window, exp.Window) and window.args.get("spec"):
    2206                self.unsupported(
    2207                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
    2208                )
    2209                nulls_sort_change = ""
    2210            elif self.NULL_ORDERING_SUPPORTED is None:
    2211                if expression.this.is_int:
    2212                    self.unsupported(
    2213                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
    2214                    )
    2215                elif not isinstance(expression.this, exp.Rand):
    2216                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
    2217                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
    2218                nulls_sort_change = ""
    2219
    2220        with_fill = self.sql(expression, "with_fill")
    2221        with_fill = f" {with_fill}" if with_fill else ""
    2222
    2223        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"
    2224
    2225    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
    2226        window_frame = self.sql(expression, "window_frame")
    2227        window_frame = f"{window_frame} " if window_frame else ""
    2228
    2229        this = self.sql(expression, "this")
    2230
    2231        return f"{window_frame}{this}"
    2232
    2233    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    2234        partition = self.partition_by_sql(expression)
    2235        order = self.sql(expression, "order")
    2236        measures = self.expressions(expression, key="measures")
    2237        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    2238        rows = self.sql(expression, "rows")
    2239        rows = self.seg(rows) if rows else ""
    2240        after = self.sql(expression, "after")
    2241        after = self.seg(after) if after else ""
    2242        pattern = self.sql(expression, "pattern")
    2243        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    2244        definition_sqls = [
    2245            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    2246            for definition in expression.args.get("define", [])
    2247        ]
    2248        definitions = self.expressions(sqls=definition_sqls)
    2249        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    2250        body = "".join(
    2251            (
    2252                partition,
    2253                order,
    2254                measures,
    2255                rows,
    2256                after,
    2257                pattern,
    2258                define,
    2259            )
    2260        )
    2261        alias = self.sql(expression, "alias")
    2262        alias = f" {alias}" if alias else ""
    2263        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
    2264
    2265    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    2266        limit = expression.args.get("limit")
    2267
    2268        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    2269            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    2270        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    2271            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    2272
    2273        return csv(
    2274            *sqls,
    2275            *[self.sql(join) for join in expression.args.get("joins") or []],
    2276            self.sql(expression, "connect"),
    2277            self.sql(expression, "match"),
    2278            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2279            self.sql(expression, "prewhere"),
    2280            self.sql(expression, "where"),
    2281            self.sql(expression, "group"),
    2282            self.sql(expression, "having"),
    2283            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
    2284            self.sql(expression, "order"),
    2285            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
    2286            *self.after_limit_modifiers(expression),
    2287            self.options_modifier(expression),
    2288            sep="",
    2289        )
    2290
    2291    def options_modifier(self, expression: exp.Expression) -> str:
    2292        options = self.expressions(expression, key="options")
    2293        return f" {options}" if options else ""
    2294
    2295    def queryoption_sql(self, expression: exp.QueryOption) -> str:
    2296        return ""
    2297
    2298    def offset_limit_modifiers(
    2299        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2300    ) -> t.List[str]:
    2301        return [
    2302            self.sql(expression, "offset") if fetch else self.sql(limit),
    2303            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2304        ]
    2305
    2306    def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
    2307        locks = self.expressions(expression, key="locks", sep=" ")
    2308        locks = f" {locks}" if locks else ""
    2309        return [locks, self.sql(expression, "sample")]
    2310
    2311    def select_sql(self, expression: exp.Select) -> str:
    2312        into = expression.args.get("into")
    2313        if not self.SUPPORTS_SELECT_INTO and into:
    2314            into.pop()
    2315
    2316        hint = self.sql(expression, "hint")
    2317        distinct = self.sql(expression, "distinct")
    2318        distinct = f" {distinct}" if distinct else ""
    2319        kind = self.sql(expression, "kind")
    2320
    2321        limit = expression.args.get("limit")
    2322        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
    2323            top = self.limit_sql(limit, top=True)
    2324            limit.pop()
    2325        else:
    2326            top = ""
    2327
    2328        expressions = self.expressions(expression)
    2329
    2330        if kind:
    2331            if kind in self.SELECT_KINDS:
    2332                kind = f" AS {kind}"
    2333            else:
    2334                if kind == "STRUCT":
    2335                    expressions = self.expressions(
    2336                        sqls=[
    2337                            self.sql(
    2338                                exp.Struct(
    2339                                    expressions=[
    2340                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
    2341                                        if isinstance(e, exp.Alias)
    2342                                        else e
    2343                                        for e in expression.expressions
    2344                                    ]
    2345                                )
    2346                            )
    2347                        ]
    2348                    )
    2349                kind = ""
    2350
    2351        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
    2352        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
    2353        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
    2354        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    2355        sql = self.query_modifiers(
    2356            expression,
    2357            f"SELECT{top_distinct}{kind}{expressions}",
    2358            self.sql(expression, "into", comment=False),
    2359            self.sql(expression, "from", comment=False),
    2360        )
    2361
    2362        sql = self.prepend_ctes(expression, sql)
    2363
    2364        if not self.SUPPORTS_SELECT_INTO and into:
    2365            if into.args.get("temporary"):
    2366                table_kind = " TEMPORARY"
    2367            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
    2368                table_kind = " UNLOGGED"
    2369            else:
    2370                table_kind = ""
    2371            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
    2372
    2373        return sql
    2374
    2375    def schema_sql(self, expression: exp.Schema) -> str:
    2376        this = self.sql(expression, "this")
    2377        sql = self.schema_columns_sql(expression)
    2378        return f"{this} {sql}" if this and sql else this or sql
    2379
    2380    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2381        if expression.expressions:
    2382            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2383        return ""
    2384
    2385    def star_sql(self, expression: exp.Star) -> str:
    2386        except_ = self.expressions(expression, key="except", flat=True)
    2387        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
    2388        replace = self.expressions(expression, key="replace", flat=True)
    2389        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
    2390        rename = self.expressions(expression, key="rename", flat=True)
    2391        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
    2392        return f"*{except_}{replace}{rename}"
    2393
    2394    def parameter_sql(self, expression: exp.Parameter) -> str:
    2395        this = self.sql(expression, "this")
    2396        return f"{self.PARAMETER_TOKEN}{this}"
    2397
    2398    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2399        this = self.sql(expression, "this")
    2400        kind = expression.text("kind")
    2401        if kind:
    2402            kind = f"{kind}."
    2403        return f"@@{kind}{this}"
    2404
    2405    def placeholder_sql(self, expression: exp.Placeholder) -> str:
    2406        return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?"
    2407
    2408    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2409        alias = self.sql(expression, "alias")
    2410        alias = f"{sep}{alias}" if alias else ""
    2411
    2412        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    2413        pivots = f" {pivots}" if pivots else ""
    2414
    2415        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2416        return self.prepend_ctes(expression, sql)
    2417
    2418    def qualify_sql(self, expression: exp.Qualify) -> str:
    2419        this = self.indent(self.sql(expression, "this"))
    2420        return f"{self.seg('QUALIFY')}{self.sep()}{this}"
    2421
    2422    def set_operations(self, expression: exp.SetOperation) -> str:
    2423        if not self.SET_OP_MODIFIERS:
    2424            limit = expression.args.get("limit")
    2425            order = expression.args.get("order")
    2426
    2427            if limit or order:
    2428                select = exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
    2429
    2430                if limit:
    2431                    select = select.limit(limit.pop(), copy=False)
    2432                if order:
    2433                    select = select.order_by(order.pop(), copy=False)
    2434                return self.sql(select)
    2435
    2436        sqls: t.List[str] = []
    2437        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    2438
    2439        while stack:
    2440            node = stack.pop()
    2441
    2442            if isinstance(node, exp.SetOperation):
    2443                stack.append(node.expression)
    2444                stack.append(
    2445                    self.maybe_comment(
    2446                        getattr(self, f"{node.key}_op")(node),
    2447                        comments=node.comments,
    2448                        separated=True,
    2449                    )
    2450                )
    2451                stack.append(node.this)
    2452            else:
    2453                sqls.append(self.sql(node))
    2454
    2455        this = self.sep().join(sqls)
    2456        this = self.query_modifiers(expression, this)
    2457        return self.prepend_ctes(expression, this)
    2458
    2459    def union_sql(self, expression: exp.Union) -> str:
    2460        return self.set_operations(expression)
    2461
    2462    def union_op(self, expression: exp.SetOperation) -> str:
    2463        kind = " DISTINCT" if self.EXPLICIT_SET_OP else ""
    2464        kind = kind if expression.args.get("distinct") else " ALL"
    2465        by_name = " BY NAME" if expression.args.get("by_name") else ""
    2466        return f"UNION{kind}{by_name}"
    2467
    2468    def unnest_sql(self, expression: exp.Unnest) -> str:
    2469        args = self.expressions(expression, flat=True)
    2470
    2471        alias = expression.args.get("alias")
    2472        offset = expression.args.get("offset")
    2473
    2474        if self.UNNEST_WITH_ORDINALITY:
    2475            if alias and isinstance(offset, exp.Expression):
    2476                alias.append("columns", offset)
    2477
    2478        if alias and self.dialect.UNNEST_COLUMN_ONLY:
    2479            columns = alias.columns
    2480            alias = self.sql(columns[0]) if columns else ""
    2481        else:
    2482            alias = self.sql(alias)
    2483
    2484        alias = f" AS {alias}" if alias else alias
    2485        if self.UNNEST_WITH_ORDINALITY:
    2486            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2487        else:
    2488            if isinstance(offset, exp.Expression):
    2489                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2490            elif offset:
    2491                suffix = f"{alias} WITH OFFSET"
    2492            else:
    2493                suffix = alias
    2494
    2495        return f"UNNEST({args}){suffix}"
    2496
    2497    def prewhere_sql(self, expression: exp.PreWhere) -> str:
    2498        return ""
    2499
    2500    def where_sql(self, expression: exp.Where) -> str:
    2501        this = self.indent(self.sql(expression, "this"))
    2502        return f"{self.seg('WHERE')}{self.sep()}{this}"
    2503
    2504    def window_sql(self, expression: exp.Window) -> str:
    2505        this = self.sql(expression, "this")
    2506        partition = self.partition_by_sql(expression)
    2507        order = expression.args.get("order")
    2508        order = self.order_sql(order, flat=True) if order else ""
    2509        spec = self.sql(expression, "spec")
    2510        alias = self.sql(expression, "alias")
    2511        over = self.sql(expression, "over") or "OVER"
    2512
    2513        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2514
    2515        first = expression.args.get("first")
    2516        if first is None:
    2517            first = ""
    2518        else:
    2519            first = "FIRST" if first else "LAST"
    2520
    2521        if not partition and not order and not spec and alias:
    2522            return f"{this} {alias}"
    2523
    2524        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    2525        return f"{this} ({args})"
    2526
    2527    def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str:
    2528        partition = self.expressions(expression, key="partition_by", flat=True)
    2529        return f"PARTITION BY {partition}" if partition else ""
    2530
    2531    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2532        kind = self.sql(expression, "kind")
    2533        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2534        end = (
    2535            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2536            or "CURRENT ROW"
    2537        )
    2538        return f"{kind} BETWEEN {start} AND {end}"
    2539
    2540    def withingroup_sql(self, expression: exp.WithinGroup) -> str:
    2541        this = self.sql(expression, "this")
    2542        expression_sql = self.sql(expression, "expression")[1:]  # order has a leading space
    2543        return f"{this} WITHIN GROUP ({expression_sql})"
    2544
    2545    def between_sql(self, expression: exp.Between) -> str:
    2546        this = self.sql(expression, "this")
    2547        low = self.sql(expression, "low")
    2548        high = self.sql(expression, "high")
    2549        return f"{this} BETWEEN {low} AND {high}"
    2550
    2551    def bracket_offset_expressions(self, expression: exp.Bracket) -> t.List[exp.Expression]:
    2552        return apply_index_offset(
    2553            expression.this,
    2554            expression.expressions,
    2555            self.dialect.INDEX_OFFSET - expression.args.get("offset", 0),
    2556        )
    2557
    2558    def bracket_sql(self, expression: exp.Bracket) -> str:
    2559        expressions = self.bracket_offset_expressions(expression)
    2560        expressions_sql = ", ".join(self.sql(e) for e in expressions)
    2561        return f"{self.sql(expression, 'this')}[{expressions_sql}]"
    2562
    2563    def all_sql(self, expression: exp.All) -> str:
    2564        return f"ALL {self.wrap(expression)}"
    2565
    2566    def any_sql(self, expression: exp.Any) -> str:
    2567        this = self.sql(expression, "this")
    2568        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
    2569            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2570                this = self.wrap(this)
    2571            return f"ANY{this}"
    2572        return f"ANY {this}"
    2573
    2574    def exists_sql(self, expression: exp.Exists) -> str:
    2575        return f"EXISTS{self.wrap(expression)}"
    2576
    2577    def case_sql(self, expression: exp.Case) -> str:
    2578        this = self.sql(expression, "this")
    2579        statements = [f"CASE {this}" if this else "CASE"]
    2580
    2581        for e in expression.args["ifs"]:
    2582            statements.append(f"WHEN {self.sql(e, 'this')}")
    2583            statements.append(f"THEN {self.sql(e, 'true')}")
    2584
    2585        default = self.sql(expression, "default")
    2586
    2587        if default:
    2588            statements.append(f"ELSE {default}")
    2589
    2590        statements.append("END")
    2591
    2592        if self.pretty and self.too_wide(statements):
    2593            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2594
    2595        return " ".join(statements)
    2596
    2597    def constraint_sql(self, expression: exp.Constraint) -> str:
    2598        this = self.sql(expression, "this")
    2599        expressions = self.expressions(expression, flat=True)
    2600        return f"CONSTRAINT {this} {expressions}"
    2601
    2602    def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str:
    2603        order = expression.args.get("order")
    2604        order = f" OVER ({self.order_sql(order, flat=True)})" if order else ""
    2605        return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}"
    2606
    2607    def extract_sql(self, expression: exp.Extract) -> str:
    2608        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2609        expression_sql = self.sql(expression, "expression")
    2610        return f"EXTRACT({this} FROM {expression_sql})"
    2611
    2612    def trim_sql(self, expression: exp.Trim) -> str:
    2613        trim_type = self.sql(expression, "position")
    2614
    2615        if trim_type == "LEADING":
    2616            return self.func("LTRIM", expression.this)
    2617        elif trim_type == "TRAILING":
    2618            return self.func("RTRIM", expression.this)
    2619        else:
    2620            return self.func("TRIM", expression.this, expression.expression)
    2621
    2622    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2623        args = expression.expressions
    2624        if isinstance(expression, exp.ConcatWs):
    2625            args = args[1:]  # Skip the delimiter
    2626
    2627        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2628            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
    2629
    2630        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2631            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2632
    2633        return args
    2634
    2635    def concat_sql(self, expression: exp.Concat) -> str:
    2636        expressions = self.convert_concat_args(expression)
    2637
    2638        # Some dialects don't allow a single-argument CONCAT call
    2639        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2640            return self.sql(expressions[0])
    2641
    2642        return self.func("CONCAT", *expressions)
    2643
    2644    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2645        return self.func(
    2646            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2647        )
    2648
    2649    def check_sql(self, expression: exp.Check) -> str:
    2650        this = self.sql(expression, key="this")
    2651        return f"CHECK ({this})"
    2652
    2653    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2654        expressions = self.expressions(expression, flat=True)
    2655        reference = self.sql(expression, "reference")
    2656        reference = f" {reference}" if reference else ""
    2657        delete = self.sql(expression, "delete")
    2658        delete = f" ON DELETE {delete}" if delete else ""
    2659        update = self.sql(expression, "update")
    2660        update = f" ON UPDATE {update}" if update else ""
    2661        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"
    2662
    2663    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2664        expressions = self.expressions(expression, flat=True)
    2665        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2666        options = f" {options}" if options else ""
    2667        return f"PRIMARY KEY ({expressions}){options}"
    2668
    2669    def if_sql(self, expression: exp.If) -> str:
    2670        return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false")))
    2671
    2672    def matchagainst_sql(self, expression: exp.MatchAgainst) -> str:
    2673        modifier = expression.args.get("modifier")
    2674        modifier = f" {modifier}" if modifier else ""
    2675        return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})"
    2676
    2677    def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str:
    2678        return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}"
    2679
    2680    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
    2681        path = self.expressions(expression, sep="", flat=True).lstrip(".")
    2682        if self.QUOTE_JSON_PATH:
    2683            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
    2684
    2685        return path
    2686
    2687    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
    2688        if isinstance(expression, exp.JSONPathPart):
    2689            transform = self.TRANSFORMS.get(expression.__class__)
    2690            if not callable(transform):
    2691                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
    2692                return ""
    2693
    2694            return transform(self, expression)
    2695
    2696        if isinstance(expression, int):
    2697            return str(expression)
    2698
    2699        if self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
    2700            escaped = expression.replace("'", "\\'")
    2701            escaped = f"\\'{expression}\\'"
    2702        else:
    2703            escaped = expression.replace('"', '\\"')
    2704            escaped = f'"{escaped}"'
    2705
    2706        return escaped
    2707
    2708    def formatjson_sql(self, expression: exp.FormatJson) -> str:
    2709        return f"{self.sql(expression, 'this')} FORMAT JSON"
    2710
    2711    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    2712        null_handling = expression.args.get("null_handling")
    2713        null_handling = f" {null_handling}" if null_handling else ""
    2714
    2715        unique_keys = expression.args.get("unique_keys")
    2716        if unique_keys is not None:
    2717            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2718        else:
    2719            unique_keys = ""
    2720
    2721        return_type = self.sql(expression, "return_type")
    2722        return_type = f" RETURNING {return_type}" if return_type else ""
    2723        encoding = self.sql(expression, "encoding")
    2724        encoding = f" ENCODING {encoding}" if encoding else ""
    2725
    2726        return self.func(
    2727            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    2728            *expression.expressions,
    2729            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2730        )
    2731
    2732    def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str:
    2733        return self.jsonobject_sql(expression)
    2734
    2735    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2736        null_handling = expression.args.get("null_handling")
    2737        null_handling = f" {null_handling}" if null_handling else ""
    2738        return_type = self.sql(expression, "return_type")
    2739        return_type = f" RETURNING {return_type}" if return_type else ""
    2740        strict = " STRICT" if expression.args.get("strict") else ""
    2741        return self.func(
    2742            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2743        )
    2744
    2745    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2746        this = self.sql(expression, "this")
    2747        order = self.sql(expression, "order")
    2748        null_handling = expression.args.get("null_handling")
    2749        null_handling = f" {null_handling}" if null_handling else ""
    2750        return_type = self.sql(expression, "return_type")
    2751        return_type = f" RETURNING {return_type}" if return_type else ""
    2752        strict = " STRICT" if expression.args.get("strict") else ""
    2753        return self.func(
    2754            "JSON_ARRAYAGG",
    2755            this,
    2756            suffix=f"{order}{null_handling}{return_type}{strict})",
    2757        )
    2758
    2759    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2760        path = self.sql(expression, "path")
    2761        path = f" PATH {path}" if path else ""
    2762        nested_schema = self.sql(expression, "nested_schema")
    2763
    2764        if nested_schema:
    2765            return f"NESTED{path} {nested_schema}"
    2766
    2767        this = self.sql(expression, "this")
    2768        kind = self.sql(expression, "kind")
    2769        kind = f" {kind}" if kind else ""
    2770        return f"{this}{kind}{path}"
    2771
    2772    def jsonschema_sql(self, expression: exp.JSONSchema) -> str:
    2773        return self.func("COLUMNS", *expression.expressions)
    2774
    2775    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    2776        this = self.sql(expression, "this")
    2777        path = self.sql(expression, "path")
    2778        path = f", {path}" if path else ""
    2779        error_handling = expression.args.get("error_handling")
    2780        error_handling = f" {error_handling}" if error_handling else ""
    2781        empty_handling = expression.args.get("empty_handling")
    2782        empty_handling = f" {empty_handling}" if empty_handling else ""
    2783        schema = self.sql(expression, "schema")
    2784        return self.func(
    2785            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    2786        )
    2787
    2788    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    2789        this = self.sql(expression, "this")
    2790        kind = self.sql(expression, "kind")
    2791        path = self.sql(expression, "path")
    2792        path = f" {path}" if path else ""
    2793        as_json = " AS JSON" if expression.args.get("as_json") else ""
    2794        return f"{this} {kind}{path}{as_json}"
    2795
    2796    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    2797        this = self.sql(expression, "this")
    2798        path = self.sql(expression, "path")
    2799        path = f", {path}" if path else ""
    2800        expressions = self.expressions(expression)
    2801        with_ = (
    2802            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2803            if expressions
    2804            else ""
    2805        )
    2806        return f"OPENJSON({this}{path}){with_}"
    2807
    2808    def in_sql(self, expression: exp.In) -> str:
    2809        query = expression.args.get("query")
    2810        unnest = expression.args.get("unnest")
    2811        field = expression.args.get("field")
    2812        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    2813
    2814        if query:
    2815            in_sql = self.sql(query)
    2816        elif unnest:
    2817            in_sql = self.in_unnest_op(unnest)
    2818        elif field:
    2819            in_sql = self.sql(field)
    2820        else:
    2821            in_sql = f"({self.expressions(expression, flat=True)})"
    2822
    2823        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
    2824
    2825    def in_unnest_op(self, unnest: exp.Unnest) -> str:
    2826        return f"(SELECT {self.sql(unnest)})"
    2827
    2828    def interval_sql(self, expression: exp.Interval) -> str:
    2829        unit = self.sql(expression, "unit")
    2830        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    2831            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    2832        unit = f" {unit}" if unit else ""
    2833
    2834        if self.SINGLE_STRING_INTERVAL:
    2835            this = expression.this.name if expression.this else ""
    2836            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    2837
    2838        this = self.sql(expression, "this")
    2839        if this:
    2840            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    2841            this = f" {this}" if unwrapped else f" ({this})"
    2842
    2843        return f"INTERVAL{this}{unit}"
    2844
    2845    def return_sql(self, expression: exp.Return) -> str:
    2846        return f"RETURN {self.sql(expression, 'this')}"
    2847
    2848    def reference_sql(self, expression: exp.Reference) -> str:
    2849        this = self.sql(expression, "this")
    2850        expressions = self.expressions(expression, flat=True)
    2851        expressions = f"({expressions})" if expressions else ""
    2852        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2853        options = f" {options}" if options else ""
    2854        return f"REFERENCES {this}{expressions}{options}"
    2855
    2856    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    2857        return self.func(self.sql(expression, "this"), *expression.expressions)
    2858
    2859    def paren_sql(self, expression: exp.Paren) -> str:
    2860        sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
    2861        return f"({sql}{self.seg(')', sep='')}"
    2862
    2863    def neg_sql(self, expression: exp.Neg) -> str:
    2864        # This makes sure we don't convert "- - 5" to "--5", which is a comment
    2865        this_sql = self.sql(expression, "this")
    2866        sep = " " if this_sql[0] == "-" else ""
    2867        return f"-{sep}{this_sql}"
    2868
    2869    def not_sql(self, expression: exp.Not) -> str:
    2870        return f"NOT {self.sql(expression, 'this')}"
    2871
    2872    def alias_sql(self, expression: exp.Alias) -> str:
    2873        alias = self.sql(expression, "alias")
    2874        alias = f" AS {alias}" if alias else ""
    2875        return f"{self.sql(expression, 'this')}{alias}"
    2876
    2877    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    2878        alias = expression.args["alias"]
    2879        identifier_alias = isinstance(alias, exp.Identifier)
    2880
    2881        if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2882            alias.replace(exp.Literal.string(alias.output_name))
    2883        elif not identifier_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2884            alias.replace(exp.to_identifier(alias.output_name))
    2885
    2886        return self.alias_sql(expression)
    2887
    2888    def aliases_sql(self, expression: exp.Aliases) -> str:
    2889        return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})"
    2890
    2891    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    2892        this = self.sql(expression, "this")
    2893        index = self.sql(expression, "expression")
    2894        return f"{this} AT {index}"
    2895
    2896    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    2897        this = self.sql(expression, "this")
    2898        zone = self.sql(expression, "zone")
    2899        return f"{this} AT TIME ZONE {zone}"
    2900
    2901    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    2902        this = self.sql(expression, "this")
    2903        zone = self.sql(expression, "zone")
    2904        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"
    2905
    2906    def add_sql(self, expression: exp.Add) -> str:
    2907        return self.binary(expression, "+")
    2908
    2909    def and_sql(
    2910        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
    2911    ) -> str:
    2912        return self.connector_sql(expression, "AND", stack)
    2913
    2914    def or_sql(
    2915        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
    2916    ) -> str:
    2917        return self.connector_sql(expression, "OR", stack)
    2918
    2919    def xor_sql(
    2920        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
    2921    ) -> str:
    2922        return self.connector_sql(expression, "XOR", stack)
    2923
    2924    def connector_sql(
    2925        self,
    2926        expression: exp.Connector,
    2927        op: str,
    2928        stack: t.Optional[t.List[str | exp.Expression]] = None,
    2929    ) -> str:
    2930        if stack is not None:
    2931            if expression.expressions:
    2932                stack.append(self.expressions(expression, sep=f" {op} "))
    2933            else:
    2934                stack.append(expression.right)
    2935                if expression.comments and self.comments:
    2936                    for comment in expression.comments:
    2937                        if comment:
    2938                            op += f" /*{self.pad_comment(comment)}*/"
    2939                stack.extend((op, expression.left))
    2940            return op
    2941
    2942        stack = [expression]
    2943        sqls: t.List[str] = []
    2944        ops = set()
    2945
    2946        while stack:
    2947            node = stack.pop()
    2948            if isinstance(node, exp.Connector):
    2949                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
    2950            else:
    2951                sql = self.sql(node)
    2952                if sqls and sqls[-1] in ops:
    2953                    sqls[-1] += f" {sql}"
    2954                else:
    2955                    sqls.append(sql)
    2956
    2957        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
    2958        return sep.join(sqls)
    2959
    2960    def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str:
    2961        return self.binary(expression, "&")
    2962
    2963    def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str:
    2964        return self.binary(expression, "<<")
    2965
    2966    def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str:
    2967        return f"~{self.sql(expression, 'this')}"
    2968
    2969    def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str:
    2970        return self.binary(expression, "|")
    2971
    2972    def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str:
    2973        return self.binary(expression, ">>")
    2974
    2975    def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str:
    2976        return self.binary(expression, "^")
    2977
    2978    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    2979        format_sql = self.sql(expression, "format")
    2980        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    2981        to_sql = self.sql(expression, "to")
    2982        to_sql = f" {to_sql}" if to_sql else ""
    2983        action = self.sql(expression, "action")
    2984        action = f" {action}" if action else ""
    2985        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{format_sql}{action})"
    2986
    2987    def currentdate_sql(self, expression: exp.CurrentDate) -> str:
    2988        zone = self.sql(expression, "this")
    2989        return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE"
    2990
    2991    def currenttimestamp_sql(self, expression: exp.CurrentTimestamp) -> str:
    2992        return self.func("CURRENT_TIMESTAMP", expression.this)
    2993
    2994    def collate_sql(self, expression: exp.Collate) -> str:
    2995        if self.COLLATE_IS_FUNC:
    2996            return self.function_fallback_sql(expression)
    2997        return self.binary(expression, "COLLATE")
    2998
    2999    def command_sql(self, expression: exp.Command) -> str:
    3000        return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}"
    3001
    3002    def comment_sql(self, expression: exp.Comment) -> str:
    3003        this = self.sql(expression, "this")
    3004        kind = expression.args["kind"]
    3005        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    3006        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    3007        expression_sql = self.sql(expression, "expression")
    3008        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"
    3009
    3010    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    3011        this = self.sql(expression, "this")
    3012        delete = " DELETE" if expression.args.get("delete") else ""
    3013        recompress = self.sql(expression, "recompress")
    3014        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    3015        to_disk = self.sql(expression, "to_disk")
    3016        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    3017        to_volume = self.sql(expression, "to_volume")
    3018        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    3019        return f"{this}{delete}{recompress}{to_disk}{to_volume}"
    3020
    3021    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    3022        where = self.sql(expression, "where")
    3023        group = self.sql(expression, "group")
    3024        aggregates = self.expressions(expression, key="aggregates")
    3025        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    3026
    3027        if not (where or group or aggregates) and len(expression.expressions) == 1:
    3028            return f"TTL {self.expressions(expression, flat=True)}"
    3029
    3030        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
    3031
    3032    def transaction_sql(self, expression: exp.Transaction) -> str:
    3033        return "BEGIN"
    3034
    3035    def commit_sql(self, expression: exp.Commit) -> str:
    3036        chain = expression.args.get("chain")
    3037        if chain is not None:
    3038            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    3039
    3040        return f"COMMIT{chain or ''}"
    3041
    3042    def rollback_sql(self, expression: exp.Rollback) -> str:
    3043        savepoint = expression.args.get("savepoint")
    3044        savepoint = f" TO {savepoint}" if savepoint else ""
    3045        return f"ROLLBACK{savepoint}"
    3046
    3047    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    3048        this = self.sql(expression, "this")
    3049
    3050        dtype = self.sql(expression, "dtype")
    3051        if dtype:
    3052            collate = self.sql(expression, "collate")
    3053            collate = f" COLLATE {collate}" if collate else ""
    3054            using = self.sql(expression, "using")
    3055            using = f" USING {using}" if using else ""
    3056            return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}"
    3057
    3058        default = self.sql(expression, "default")
    3059        if default:
    3060            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    3061
    3062        comment = self.sql(expression, "comment")
    3063        if comment:
    3064            return f"ALTER COLUMN {this} COMMENT {comment}"
    3065
    3066        allow_null = expression.args.get("allow_null")
    3067        drop = expression.args.get("drop")
    3068
    3069        if not drop and not allow_null:
    3070            self.unsupported("Unsupported ALTER COLUMN syntax")
    3071
    3072        if allow_null is not None:
    3073            keyword = "DROP" if drop else "SET"
    3074            return f"ALTER COLUMN {this} {keyword} NOT NULL"
    3075
    3076        return f"ALTER COLUMN {this} DROP DEFAULT"
    3077
    3078    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
    3079        this = self.sql(expression, "this")
    3080        if not isinstance(expression.this, exp.Var):
    3081            this = f"KEY DISTKEY {this}"
    3082        return f"ALTER DISTSTYLE {this}"
    3083
    3084    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
    3085        compound = " COMPOUND" if expression.args.get("compound") else ""
    3086        this = self.sql(expression, "this")
    3087        expressions = self.expressions(expression, flat=True)
    3088        expressions = f"({expressions})" if expressions else ""
    3089        return f"ALTER{compound} SORTKEY {this or expressions}"
    3090
    3091    def renametable_sql(self, expression: exp.RenameTable) -> str:
    3092        if not self.RENAME_TABLE_WITH_DB:
    3093            # Remove db from tables
    3094            expression = expression.transform(
    3095                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    3096            ).assert_is(exp.RenameTable)
    3097        this = self.sql(expression, "this")
    3098        return f"RENAME TO {this}"
    3099
    3100    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    3101        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3102        old_column = self.sql(expression, "this")
    3103        new_column = self.sql(expression, "to")
    3104        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"
    3105
    3106    def alterset_sql(self, expression: exp.AlterSet) -> str:
    3107        exprs = self.expressions(expression, flat=True)
    3108        return f"SET {exprs}"
    3109
    3110    def altertable_sql(self, expression: exp.AlterTable) -> str:
    3111        actions = expression.args["actions"]
    3112
    3113        if isinstance(actions[0], exp.ColumnDef):
    3114            actions = self.add_column_sql(expression)
    3115        elif isinstance(actions[0], exp.Schema):
    3116            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    3117        elif isinstance(actions[0], exp.Delete):
    3118            actions = self.expressions(expression, key="actions", flat=True)
    3119        else:
    3120            actions = self.expressions(expression, key="actions", flat=True)
    3121
    3122        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3123        on_cluster = self.sql(expression, "cluster")
    3124        on_cluster = f" {on_cluster}" if on_cluster else ""
    3125        only = " ONLY" if expression.args.get("only") else ""
    3126        options = self.expressions(expression, key="options")
    3127        options = f", {options}" if options else ""
    3128        return f"ALTER TABLE{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{options}"
    3129
    3130    def add_column_sql(self, expression: exp.AlterTable) -> str:
    3131        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    3132            return self.expressions(
    3133                expression,
    3134                key="actions",
    3135                prefix="ADD COLUMN ",
    3136            )
    3137        return f"ADD {self.expressions(expression, key='actions', flat=True)}"
    3138
    3139    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    3140        expressions = self.expressions(expression)
    3141        exists = " IF EXISTS " if expression.args.get("exists") else " "
    3142        return f"DROP{exists}{expressions}"
    3143
    3144    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
    3145        return f"ADD {self.expressions(expression)}"
    3146
    3147    def distinct_sql(self, expression: exp.Distinct) -> str:
    3148        this = self.expressions(expression, flat=True)
    3149
    3150        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    3151            case = exp.case()
    3152            for arg in expression.expressions:
    3153                case = case.when(arg.is_(exp.null()), exp.null())
    3154            this = self.sql(case.else_(f"({this})"))
    3155
    3156        this = f" {this}" if this else ""
    3157
    3158        on = self.sql(expression, "on")
    3159        on = f" ON {on}" if on else ""
    3160        return f"DISTINCT{this}{on}"
    3161
    3162    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
    3163        return self._embed_ignore_nulls(expression, "IGNORE NULLS")
    3164
    3165    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
    3166        return self._embed_ignore_nulls(expression, "RESPECT NULLS")
    3167
    3168    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    3169        this_sql = self.sql(expression, "this")
    3170        expression_sql = self.sql(expression, "expression")
    3171        kind = "MAX" if expression.args.get("max") else "MIN"
    3172        return f"{this_sql} HAVING {kind} {expression_sql}"
    3173
    3174    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    3175        return self.sql(
    3176            exp.Cast(
    3177                this=exp.Div(this=expression.this, expression=expression.expression),
    3178                to=exp.DataType(this=exp.DataType.Type.INT),
    3179            )
    3180        )
    3181
    3182    def dpipe_sql(self, expression: exp.DPipe) -> str:
    3183        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    3184            return self.func(
    3185                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
    3186            )
    3187        return self.binary(expression, "||")
    3188
    3189    def div_sql(self, expression: exp.Div) -> str:
    3190        l, r = expression.left, expression.right
    3191
    3192        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    3193            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    3194
    3195        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    3196            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
    3197                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    3198
    3199        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    3200            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    3201                return self.sql(
    3202                    exp.cast(
    3203                        l / r,
    3204                        to=exp.DataType.Type.BIGINT,
    3205                    )
    3206                )
    3207
    3208        return self.binary(expression, "/")
    3209
    3210    def overlaps_sql(self, expression: exp.Overlaps) -> str:
    3211        return self.binary(expression, "OVERLAPS")
    3212
    3213    def distance_sql(self, expression: exp.Distance) -> str:
    3214        return self.binary(expression, "<->")
    3215
    3216    def dot_sql(self, expression: exp.Dot) -> str:
    3217        return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}"
    3218
    3219    def eq_sql(self, expression: exp.EQ) -> str:
    3220        return self.binary(expression, "=")
    3221
    3222    def propertyeq_sql(self, expression: exp.PropertyEQ) -> str:
    3223        return self.binary(expression, ":=")
    3224
    3225    def escape_sql(self, expression: exp.Escape) -> str:
    3226        return self.binary(expression, "ESCAPE")
    3227
    3228    def glob_sql(self, expression: exp.Glob) -> str:
    3229        return self.binary(expression, "GLOB")
    3230
    3231    def gt_sql(self, expression: exp.GT) -> str:
    3232        return self.binary(expression, ">")
    3233
    3234    def gte_sql(self, expression: exp.GTE) -> str:
    3235        return self.binary(expression, ">=")
    3236
    3237    def ilike_sql(self, expression: exp.ILike) -> str:
    3238        return self.binary(expression, "ILIKE")
    3239
    3240    def ilikeany_sql(self, expression: exp.ILikeAny) -> str:
    3241        return self.binary(expression, "ILIKE ANY")
    3242
    3243    def is_sql(self, expression: exp.Is) -> str:
    3244        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3245            return self.sql(
    3246                expression.this if expression.expression.this else exp.not_(expression.this)
    3247            )
    3248        return self.binary(expression, "IS")
    3249
    3250    def like_sql(self, expression: exp.Like) -> str:
    3251        return self.binary(expression, "LIKE")
    3252
    3253    def likeany_sql(self, expression: exp.LikeAny) -> str:
    3254        return self.binary(expression, "LIKE ANY")
    3255
    3256    def similarto_sql(self, expression: exp.SimilarTo) -> str:
    3257        return self.binary(expression, "SIMILAR TO")
    3258
    3259    def lt_sql(self, expression: exp.LT) -> str:
    3260        return self.binary(expression, "<")
    3261
    3262    def lte_sql(self, expression: exp.LTE) -> str:
    3263        return self.binary(expression, "<=")
    3264
    3265    def mod_sql(self, expression: exp.Mod) -> str:
    3266        return self.binary(expression, "%")
    3267
    3268    def mul_sql(self, expression: exp.Mul) -> str:
    3269        return self.binary(expression, "*")
    3270
    3271    def neq_sql(self, expression: exp.NEQ) -> str:
    3272        return self.binary(expression, "<>")
    3273
    3274    def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str:
    3275        return self.binary(expression, "IS NOT DISTINCT FROM")
    3276
    3277    def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str:
    3278        return self.binary(expression, "IS DISTINCT FROM")
    3279
    3280    def slice_sql(self, expression: exp.Slice) -> str:
    3281        return self.binary(expression, ":")
    3282
    3283    def sub_sql(self, expression: exp.Sub) -> str:
    3284        return self.binary(expression, "-")
    3285
    3286    def trycast_sql(self, expression: exp.TryCast) -> str:
    3287        return self.cast_sql(expression, safe_prefix="TRY_")
    3288
    3289    def try_sql(self, expression: exp.Try) -> str:
    3290        if not self.TRY_SUPPORTED:
    3291            self.unsupported("Unsupported TRY function")
    3292            return self.sql(expression, "this")
    3293
    3294        return self.func("TRY", expression.this)
    3295
    3296    def log_sql(self, expression: exp.Log) -> str:
    3297        this = expression.this
    3298        expr = expression.expression
    3299
    3300        if self.dialect.LOG_BASE_FIRST is False:
    3301            this, expr = expr, this
    3302        elif self.dialect.LOG_BASE_FIRST is None and expr:
    3303            if this.name in ("2", "10"):
    3304                return self.func(f"LOG{this.name}", expr)
    3305
    3306            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
    3307
    3308        return self.func("LOG", this, expr)
    3309
    3310    def use_sql(self, expression: exp.Use) -> str:
    3311        kind = self.sql(expression, "kind")
    3312        kind = f" {kind}" if kind else ""
    3313        this = self.sql(expression, "this")
    3314        this = f" {this}" if this else ""
    3315        return f"USE{kind}{this}"
    3316
    3317    def binary(self, expression: exp.Binary, op: str) -> str:
    3318        op = self.maybe_comment(op, comments=expression.comments)
    3319        return f"{self.sql(expression, 'this')} {op} {self.sql(expression, 'expression')}"
    3320
    3321    def function_fallback_sql(self, expression: exp.Func) -> str:
    3322        args = []
    3323
    3324        for key in expression.arg_types:
    3325            arg_value = expression.args.get(key)
    3326
    3327            if isinstance(arg_value, list):
    3328                for value in arg_value:
    3329                    args.append(value)
    3330            elif arg_value is not None:
    3331                args.append(arg_value)
    3332
    3333        if self.normalize_functions:
    3334            name = expression.sql_name()
    3335        else:
    3336            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3337
    3338        return self.func(name, *args)
    3339
    3340    def func(
    3341        self,
    3342        name: str,
    3343        *args: t.Optional[exp.Expression | str],
    3344        prefix: str = "(",
    3345        suffix: str = ")",
    3346    ) -> str:
    3347        return f"{self.normalize_func(name)}{prefix}{self.format_args(*args)}{suffix}"
    3348
    3349    def format_args(self, *args: t.Optional[str | exp.Expression]) -> str:
    3350        arg_sqls = tuple(self.sql(arg) for arg in args if arg is not None)
    3351        if self.pretty and self.too_wide(arg_sqls):
    3352            return self.indent("\n" + ",\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True)
    3353        return ", ".join(arg_sqls)
    3354
    3355    def too_wide(self, args: t.Iterable) -> bool:
    3356        return sum(len(arg) for arg in args) > self.max_text_width
    3357
    3358    def format_time(
    3359        self,
    3360        expression: exp.Expression,
    3361        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
    3362        inverse_time_trie: t.Optional[t.Dict] = None,
    3363    ) -> t.Optional[str]:
    3364        return format_time(
    3365            self.sql(expression, "format"),
    3366            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
    3367            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
    3368        )
    3369
    3370    def expressions(
    3371        self,
    3372        expression: t.Optional[exp.Expression] = None,
    3373        key: t.Optional[str] = None,
    3374        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    3375        flat: bool = False,
    3376        indent: bool = True,
    3377        skip_first: bool = False,
    3378        skip_last: bool = False,
    3379        sep: str = ", ",
    3380        prefix: str = "",
    3381        dynamic: bool = False,
    3382        new_line: bool = False,
    3383    ) -> str:
    3384        expressions = expression.args.get(key or "expressions") if expression else sqls
    3385
    3386        if not expressions:
    3387            return ""
    3388
    3389        if flat:
    3390            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    3391
    3392        num_sqls = len(expressions)
    3393
    3394        # These are calculated once in case we have the leading_comma / pretty option set, correspondingly
    3395        if self.pretty and not self.leading_comma:
    3396            stripped_sep = sep.strip()
    3397
    3398        result_sqls = []
    3399        for i, e in enumerate(expressions):
    3400            sql = self.sql(e, comment=False)
    3401            if not sql:
    3402                continue
    3403
    3404            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    3405
    3406            if self.pretty:
    3407                if self.leading_comma:
    3408                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
    3409                else:
    3410                    result_sqls.append(
    3411                        f"{prefix}{sql}{stripped_sep if i + 1 < num_sqls else ''}{comments}"
    3412                    )
    3413            else:
    3414                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    3415
    3416        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
    3417            if new_line:
    3418                result_sqls.insert(0, "")
    3419                result_sqls.append("")
    3420            result_sql = "\n".join(result_sqls)
    3421        else:
    3422            result_sql = "".join(result_sqls)
    3423        return (
    3424            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
    3425            if indent
    3426            else result_sql
    3427        )
    3428
    3429    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3430        flat = flat or isinstance(expression.parent, exp.Properties)
    3431        expressions_sql = self.expressions(expression, flat=flat)
    3432        if flat:
    3433            return f"{op} {expressions_sql}"
    3434        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
    3435
    3436    def naked_property(self, expression: exp.Property) -> str:
    3437        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3438        if not property_name:
    3439            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3440        return f"{property_name} {self.sql(expression, 'this')}"
    3441
    3442    def tag_sql(self, expression: exp.Tag) -> str:
    3443        return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}"
    3444
    3445    def token_sql(self, token_type: TokenType) -> str:
    3446        return self.TOKEN_MAPPING.get(token_type, token_type.name)
    3447
    3448    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3449        this = self.sql(expression, "this")
    3450        expressions = self.no_identify(self.expressions, expression)
    3451        expressions = (
    3452            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3453        )
    3454        return f"{this}{expressions}"
    3455
    3456    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3457        this = self.sql(expression, "this")
    3458        expressions = self.expressions(expression, flat=True)
    3459        return f"{this}({expressions})"
    3460
    3461    def kwarg_sql(self, expression: exp.Kwarg) -> str:
    3462        return self.binary(expression, "=>")
    3463
    3464    def when_sql(self, expression: exp.When) -> str:
    3465        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3466        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3467        condition = self.sql(expression, "condition")
    3468        condition = f" AND {condition}" if condition else ""
    3469
    3470        then_expression = expression.args.get("then")
    3471        if isinstance(then_expression, exp.Insert):
    3472            this = self.sql(then_expression, "this")
    3473            this = f"INSERT {this}" if this else "INSERT"
    3474            then = self.sql(then_expression, "expression")
    3475            then = f"{this} VALUES {then}" if then else this
    3476        elif isinstance(then_expression, exp.Update):
    3477            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3478                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3479            else:
    3480                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    3481        else:
    3482            then = self.sql(then_expression)
    3483        return f"WHEN {matched}{source}{condition} THEN {then}"
    3484
    3485    def merge_sql(self, expression: exp.Merge) -> str:
    3486        table = expression.this
    3487        table_alias = ""
    3488
    3489        hints = table.args.get("hints")
    3490        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3491            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3492            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3493
    3494        this = self.sql(table)
    3495        using = f"USING {self.sql(expression, 'using')}"
    3496        on = f"ON {self.sql(expression, 'on')}"
    3497        expressions = self.expressions(expression, sep=" ", indent=False)
    3498        sep = self.sep()
    3499
    3500        return self.prepend_ctes(
    3501            expression, f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{expressions}"
    3502        )
    3503
    3504    def tochar_sql(self, expression: exp.ToChar) -> str:
    3505        if expression.args.get("format"):
    3506            self.unsupported("Format argument unsupported for TO_CHAR/TO_VARCHAR function")
    3507
    3508        return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT))
    3509
    3510    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3511        if not self.SUPPORTS_TO_NUMBER:
    3512            self.unsupported("Unsupported TO_NUMBER function")
    3513            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3514
    3515        fmt = expression.args.get("format")
    3516        if not fmt:
    3517            self.unsupported("Conversion format is required for TO_NUMBER")
    3518            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3519
    3520        return self.func("TO_NUMBER", expression.this, fmt)
    3521
    3522    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3523        this = self.sql(expression, "this")
    3524        kind = self.sql(expression, "kind")
    3525        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3526        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3527        return f"{this}({kind}{args})"
    3528
    3529    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3530        this = self.sql(expression, "this")
    3531        max = self.sql(expression, "max")
    3532        min = self.sql(expression, "min")
    3533        return f"{this}(MIN {min} MAX {max})"
    3534
    3535    def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str:
    3536        return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}"
    3537
    3538    def oncluster_sql(self, expression: exp.OnCluster) -> str:
    3539        return ""
    3540
    3541    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3542        expressions = self.expressions(expression, key="expressions", flat=True)
    3543        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3544        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3545        buckets = self.sql(expression, "buckets")
    3546        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
    3547
    3548    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3549        this = self.sql(expression, "this")
    3550        having = self.sql(expression, "having")
    3551
    3552        if having:
    3553            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3554
    3555        return self.func("ANY_VALUE", this)
    3556
    3557    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3558        transform = self.func("TRANSFORM", *expression.expressions)
    3559        row_format_before = self.sql(expression, "row_format_before")
    3560        row_format_before = f" {row_format_before}" if row_format_before else ""
    3561        record_writer = self.sql(expression, "record_writer")
    3562        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3563        using = f" USING {self.sql(expression, 'command_script')}"
    3564        schema = self.sql(expression, "schema")
    3565        schema = f" AS {schema}" if schema else ""
    3566        row_format_after = self.sql(expression, "row_format_after")
    3567        row_format_after = f" {row_format_after}" if row_format_after else ""
    3568        record_reader = self.sql(expression, "record_reader")
    3569        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3570        return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"
    3571
    3572    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3573        key_block_size = self.sql(expression, "key_block_size")
    3574        if key_block_size:
    3575            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3576
    3577        using = self.sql(expression, "using")
    3578        if using:
    3579            return f"USING {using}"
    3580
    3581        parser = self.sql(expression, "parser")
    3582        if parser:
    3583            return f"WITH PARSER {parser}"
    3584
    3585        comment = self.sql(expression, "comment")
    3586        if comment:
    3587            return f"COMMENT {comment}"
    3588
    3589        visible = expression.args.get("visible")
    3590        if visible is not None:
    3591            return "VISIBLE" if visible else "INVISIBLE"
    3592
    3593        engine_attr = self.sql(expression, "engine_attr")
    3594        if engine_attr:
    3595            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3596
    3597        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3598        if secondary_engine_attr:
    3599            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3600
    3601        self.unsupported("Unsupported index constraint option.")
    3602        return ""
    3603
    3604    def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str:
    3605        enforced = " ENFORCED" if expression.args.get("enforced") else ""
    3606        return f"CHECK ({self.sql(expression, 'this')}){enforced}"
    3607
    3608    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3609        kind = self.sql(expression, "kind")
    3610        kind = f"{kind} INDEX" if kind else "INDEX"
    3611        this = self.sql(expression, "this")
    3612        this = f" {this}" if this else ""
    3613        index_type = self.sql(expression, "index_type")
    3614        index_type = f" USING {index_type}" if index_type else ""
    3615        expressions = self.expressions(expression, flat=True)
    3616        expressions = f" ({expressions})" if expressions else ""
    3617        options = self.expressions(expression, key="options", sep=" ")
    3618        options = f" {options}" if options else ""
    3619        return f"{kind}{this}{index_type}{expressions}{options}"
    3620
    3621    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3622        if self.NVL2_SUPPORTED:
    3623            return self.function_fallback_sql(expression)
    3624
    3625        case = exp.Case().when(
    3626            expression.this.is_(exp.null()).not_(copy=False),
    3627            expression.args["true"],
    3628            copy=False,
    3629        )
    3630        else_cond = expression.args.get("false")
    3631        if else_cond:
    3632            case.else_(else_cond, copy=False)
    3633
    3634        return self.sql(case)
    3635
    3636    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3637        this = self.sql(expression, "this")
    3638        expr = self.sql(expression, "expression")
    3639        iterator = self.sql(expression, "iterator")
    3640        condition = self.sql(expression, "condition")
    3641        condition = f" IF {condition}" if condition else ""
    3642        return f"{this} FOR {expr} IN {iterator}{condition}"
    3643
    3644    def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str:
    3645        return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})"
    3646
    3647    def opclass_sql(self, expression: exp.Opclass) -> str:
    3648        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
    3649
    3650    def predict_sql(self, expression: exp.Predict) -> str:
    3651        model = self.sql(expression, "this")
    3652        model = f"MODEL {model}"
    3653        table = self.sql(expression, "expression")
    3654        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    3655        parameters = self.sql(expression, "params_struct")
    3656        return self.func("PREDICT", model, table, parameters or None)
    3657
    3658    def forin_sql(self, expression: exp.ForIn) -> str:
    3659        this = self.sql(expression, "this")
    3660        expression_sql = self.sql(expression, "expression")
    3661        return f"FOR {this} DO {expression_sql}"
    3662
    3663    def refresh_sql(self, expression: exp.Refresh) -> str:
    3664        this = self.sql(expression, "this")
    3665        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    3666        return f"REFRESH {table}{this}"
    3667
    3668    def operator_sql(self, expression: exp.Operator) -> str:
    3669        return self.binary(expression, f"OPERATOR({self.sql(expression, 'operator')})")
    3670
    3671    def toarray_sql(self, expression: exp.ToArray) -> str:
    3672        arg = expression.this
    3673        if not arg.type:
    3674            from sqlglot.optimizer.annotate_types import annotate_types
    3675
    3676            arg = annotate_types(arg)
    3677
    3678        if arg.is_type(exp.DataType.Type.ARRAY):
    3679            return self.sql(arg)
    3680
    3681        cond_for_null = arg.is_(exp.null())
    3682        return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False)))
    3683
    3684    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    3685        this = expression.this
    3686        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    3687            return self.sql(this)
    3688
    3689        return self.sql(exp.cast(this, exp.DataType.Type.TIME))
    3690
    3691    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
    3692        this = expression.this
    3693        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
    3694            return self.sql(this)
    3695
    3696        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP))
    3697
    3698    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    3699        this = expression.this
    3700        time_format = self.format_time(expression)
    3701
    3702        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    3703            return self.sql(
    3704                exp.cast(
    3705                    exp.StrToTime(this=this, format=expression.args["format"]),
    3706                    exp.DataType.Type.DATE,
    3707                )
    3708            )
    3709
    3710        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    3711            return self.sql(this)
    3712
    3713        return self.sql(exp.cast(this, exp.DataType.Type.DATE))
    3714
    3715    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    3716        return self.sql(
    3717            exp.func(
    3718                "DATEDIFF",
    3719                expression.this,
    3720                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
    3721                "day",
    3722            )
    3723        )
    3724
    3725    def lastday_sql(self, expression: exp.LastDay) -> str:
    3726        if self.LAST_DAY_SUPPORTS_DATE_PART:
    3727            return self.function_fallback_sql(expression)
    3728
    3729        unit = expression.text("unit")
    3730        if unit and unit != "MONTH":
    3731            self.unsupported("Date parts are not supported in LAST_DAY.")
    3732
    3733        return self.func("LAST_DAY", expression.this)
    3734
    3735    def dateadd_sql(self, expression: exp.DateAdd) -> str:
    3736        from sqlglot.dialects.dialect import unit_to_str
    3737
    3738        return self.func(
    3739            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
    3740        )
    3741
    3742    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    3743        if self.CAN_IMPLEMENT_ARRAY_ANY:
    3744            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    3745            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    3746            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    3747            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    3748
    3749        from sqlglot.dialects import Dialect
    3750
    3751        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    3752        if self.dialect.__class__ != Dialect:
    3753            self.unsupported("ARRAY_ANY is unsupported")
    3754
    3755        return self.function_fallback_sql(expression)
    3756
    3757    def generateseries_sql(self, expression: exp.GenerateSeries) -> str:
    3758        expression.set("is_end_exclusive", None)
    3759        return self.function_fallback_sql(expression)
    3760
    3761    def struct_sql(self, expression: exp.Struct) -> str:
    3762        expression.set(
    3763            "expressions",
    3764            [
    3765                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    3766                if isinstance(e, exp.PropertyEQ)
    3767                else e
    3768                for e in expression.expressions
    3769            ],
    3770        )
    3771
    3772        return self.function_fallback_sql(expression)
    3773
    3774    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    3775        low = self.sql(expression, "this")
    3776        high = self.sql(expression, "expression")
    3777
    3778        return f"{low} TO {high}"
    3779
    3780    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    3781        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    3782        tables = f" {self.expressions(expression)}"
    3783
    3784        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3785
    3786        on_cluster = self.sql(expression, "cluster")
    3787        on_cluster = f" {on_cluster}" if on_cluster else ""
    3788
    3789        identity = self.sql(expression, "identity")
    3790        identity = f" {identity} IDENTITY" if identity else ""
    3791
    3792        option = self.sql(expression, "option")
    3793        option = f" {option}" if option else ""
    3794
    3795        partition = self.sql(expression, "partition")
    3796        partition = f" {partition}" if partition else ""
    3797
    3798        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"
    3799
    3800    # This transpiles T-SQL's CONVERT function
    3801    # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16
    3802    def convert_sql(self, expression: exp.Convert) -> str:
    3803        to = expression.this
    3804        value = expression.expression
    3805        style = expression.args.get("style")
    3806        safe = expression.args.get("safe")
    3807        strict = expression.args.get("strict")
    3808
    3809        if not to or not value:
    3810            return ""
    3811
    3812        # Retrieve length of datatype and override to default if not specified
    3813        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3814            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    3815
    3816        transformed: t.Optional[exp.Expression] = None
    3817        cast = exp.Cast if strict else exp.TryCast
    3818
    3819        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
    3820        if isinstance(style, exp.Literal) and style.is_int:
    3821            from sqlglot.dialects.tsql import TSQL
    3822
    3823            style_value = style.name
    3824            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
    3825            if not converted_style:
    3826                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
    3827
    3828            fmt = exp.Literal.string(converted_style)
    3829
    3830            if to.this == exp.DataType.Type.DATE:
    3831                transformed = exp.StrToDate(this=value, format=fmt)
    3832            elif to.this == exp.DataType.Type.DATETIME:
    3833                transformed = exp.StrToTime(this=value, format=fmt)
    3834            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3835                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
    3836            elif to.this == exp.DataType.Type.TEXT:
    3837                transformed = exp.TimeToStr(this=value, format=fmt)
    3838
    3839        if not transformed:
    3840            transformed = cast(this=value, to=to, safe=safe)
    3841
    3842        return self.sql(transformed)
    3843
    3844    def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str:
    3845        this = expression.this
    3846        if isinstance(this, exp.JSONPathWildcard):
    3847            this = self.json_path_part(this)
    3848            return f".{this}" if this else ""
    3849
    3850        if exp.SAFE_IDENTIFIER_RE.match(this):
    3851            return f".{this}"
    3852
    3853        this = self.json_path_part(this)
    3854        return f"[{this}]" if self.JSON_PATH_BRACKETED_KEY_SUPPORTED else f".{this}"
    3855
    3856    def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str:
    3857        this = self.json_path_part(expression.this)
    3858        return f"[{this}]" if this else ""
    3859
    3860    def _simplify_unless_literal(self, expression: E) -> E:
    3861        if not isinstance(expression, exp.Literal):
    3862            from sqlglot.optimizer.simplify import simplify
    3863
    3864            expression = simplify(expression, dialect=self.dialect)
    3865
    3866        return expression
    3867
    3868    def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str:
    3869        if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"):
    3870            # The first modifier here will be the one closest to the AggFunc's arg
    3871            mods = sorted(
    3872                expression.find_all(exp.HavingMax, exp.Order, exp.Limit),
    3873                key=lambda x: 0
    3874                if isinstance(x, exp.HavingMax)
    3875                else (1 if isinstance(x, exp.Order) else 2),
    3876            )
    3877
    3878            if mods:
    3879                mod = mods[0]
    3880                this = expression.__class__(this=mod.this.copy())
    3881                this.meta["inline"] = True
    3882                mod.this.replace(this)
    3883                return self.sql(expression.this)
    3884
    3885            agg_func = expression.find(exp.AggFunc)
    3886
    3887            if agg_func:
    3888                return self.sql(agg_func)[:-1] + f" {text})"
    3889
    3890        return f"{self.sql(expression, 'this')} {text}"
    3891
    3892    def _replace_line_breaks(self, string: str) -> str:
    3893        """We don't want to extra indent line breaks so we temporarily replace them with sentinels."""
    3894        if self.pretty:
    3895            return string.replace("\n", self.SENTINEL_LINE_BREAK)
    3896        return string
    3897
    3898    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
    3899        option = self.sql(expression, "this")
    3900
    3901        if expression.expressions:
    3902            upper = option.upper()
    3903
    3904            # Snowflake FILE_FORMAT options are separated by whitespace
    3905            sep = " " if upper == "FILE_FORMAT" else ", "
    3906
    3907            # Databricks copy/format options do not set their list of values with EQ
    3908            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
    3909            values = self.expressions(expression, flat=True, sep=sep)
    3910            return f"{option}{op}({values})"
    3911
    3912        value = self.sql(expression, "expression")
    3913
    3914        if not value:
    3915            return option
    3916
    3917        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
    3918
    3919        return f"{option}{op}{value}"
    3920
    3921    def credentials_sql(self, expression: exp.Credentials) -> str:
    3922        cred_expr = expression.args.get("credentials")
    3923        if isinstance(cred_expr, exp.Literal):
    3924            # Redshift case: CREDENTIALS <string>
    3925            credentials = self.sql(expression, "credentials")
    3926            credentials = f"CREDENTIALS {credentials}" if credentials else ""
    3927        else:
    3928            # Snowflake case: CREDENTIALS = (...)
    3929            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
    3930            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
    3931
    3932        storage = self.sql(expression, "storage")
    3933        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
    3934
    3935        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
    3936        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
    3937
    3938        iam_role = self.sql(expression, "iam_role")
    3939        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
    3940
    3941        region = self.sql(expression, "region")
    3942        region = f" REGION {region}" if region else ""
    3943
    3944        return f"{credentials}{storage}{encryption}{iam_role}{region}"
    3945
    3946    def copy_sql(self, expression: exp.Copy) -> str:
    3947        this = self.sql(expression, "this")
    3948        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
    3949
    3950        credentials = self.sql(expression, "credentials")
    3951        credentials = self.seg(credentials) if credentials else ""
    3952        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
    3953        files = self.expressions(expression, key="files", flat=True)
    3954
    3955        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
    3956        params = self.expressions(
    3957            expression,
    3958            key="params",
    3959            sep=sep,
    3960            new_line=True,
    3961            skip_last=True,
    3962            skip_first=True,
    3963            indent=self.COPY_PARAMS_ARE_WRAPPED,
    3964        )
    3965
    3966        if params:
    3967            if self.COPY_PARAMS_ARE_WRAPPED:
    3968                params = f" WITH ({params})"
    3969            elif not self.pretty:
    3970                params = f" {params}"
    3971
    3972        return f"COPY{this}{kind} {files}{credentials}{params}"
    3973
    3974    def semicolon_sql(self, expression: exp.Semicolon) -> str:
    3975        return ""
    3976
    3977    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
    3978        on_sql = "ON" if expression.args.get("on") else "OFF"
    3979        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
    3980        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
    3981        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    3982        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
    3983
    3984        if filter_col or retention_period:
    3985            on_sql = self.func("ON", filter_col, retention_period)
    3986
    3987        return f"DATA_DELETION={on_sql}"
    3988
    3989    def maskingpolicycolumnconstraint_sql(
    3990        self, expression: exp.MaskingPolicyColumnConstraint
    3991    ) -> str:
    3992        this = self.sql(expression, "this")
    3993        expressions = self.expressions(expression, flat=True)
    3994        expressions = f" USING ({expressions})" if expressions else ""
    3995        return f"MASKING POLICY {this}{expressions}"
    3996
    3997    def gapfill_sql(self, expression: exp.GapFill) -> str:
    3998        this = self.sql(expression, "this")
    3999        this = f"TABLE {this}"
    4000        return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"])
    4001
    4002    def scope_resolution(self, rhs: str, scope_name: str) -> str:
    4003        return self.func("SCOPE_RESOLUTION", scope_name or None, rhs)
    4004
    4005    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
    4006        this = self.sql(expression, "this")
    4007        expr = expression.expression
    4008
    4009        if isinstance(expr, exp.Func):
    4010            # T-SQL's CLR functions are case sensitive
    4011            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
    4012        else:
    4013            expr = self.sql(expression, "expression")
    4014
    4015        return self.scope_resolution(expr, this)
    4016
    4017    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
    4018        if self.PARSE_JSON_NAME is None:
    4019            return self.sql(expression.this)
    4020
    4021        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)
    4022
    4023    def length_sql(self, expression: exp.Length) -> str:
    4024        return self.func("LENGTH", expression.this)
    4025
    4026    def rand_sql(self, expression: exp.Rand) -> str:
    4027        lower = self.sql(expression, "lower")
    4028        upper = self.sql(expression, "upper")
    4029
    4030        if lower and upper:
    4031            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
    4032        return self.func("RAND", expression.this)
    4033
    4034    def strtodate_sql(self, expression: exp.StrToDate) -> str:
    4035        return self.func("STR_TO_DATE", expression.this, expression.args.get("format"))
    4036
    4037    def strtotime_sql(self, expression: exp.StrToTime) -> str:
    4038        return self.func(
    4039            "STR_TO_TIME",
    4040            expression.this,
    4041            expression.args.get("format"),
    4042            expression.args.get("zone"),
    4043        )
    4044
    4045    def changes_sql(self, expression: exp.Changes) -> str:
    4046        information = self.sql(expression, "information")
    4047        information = f"INFORMATION => {information}"
    4048        at_before = self.sql(expression, "at_before")
    4049        at_before = f"{self.seg('')}{at_before}" if at_before else ""
    4050        end = self.sql(expression, "end")
    4051        end = f"{self.seg('')}{end}" if end else ""
    4052
    4053        return f"CHANGES ({information}){at_before}{end}"
    4054
    4055    def pad_sql(self, expression: exp.Pad) -> str:
    4056        prefix = "L" if expression.args.get("is_left") else "R"
    4057
    4058        fill_pattern = self.sql(expression, "fill_pattern") or None
    4059        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
    4060            fill_pattern = "' '"
    4061
    4062        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        return f"UNIQUE{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        postcreate_props_sql = ""
    1031        if properties_locs.get(exp.Properties.Location.POST_CREATE):
    1032            postcreate_props_sql = self.properties(
    1033                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
    1034                sep=" ",
    1035                prefix=" ",
    1036                wrapped=False,
    1037            )
    1038
    1039        modifiers = "".join((replace, unique, postcreate_props_sql))
    1040
    1041        postexpression_props_sql = ""
    1042        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
    1043            postexpression_props_sql = self.properties(
    1044                exp.Properties(
    1045                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
    1046                ),
    1047                sep=" ",
    1048                prefix=" ",
    1049                wrapped=False,
    1050            )
    1051
    1052        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    1053        no_schema_binding = (
    1054            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
    1055        )
    1056
    1057        clone = self.sql(expression, "clone")
    1058        clone = f" {clone}" if clone else ""
    1059
    1060        expression_sql = f"CREATE{modifiers} {kind}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
    1061        return self.prepend_ctes(expression, expression_sql)
    1062
    1063    def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str:
    1064        start = self.sql(expression, "start")
    1065        start = f"START WITH {start}" if start else ""
    1066        increment = self.sql(expression, "increment")
    1067        increment = f" INCREMENT BY {increment}" if increment else ""
    1068        minvalue = self.sql(expression, "minvalue")
    1069        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    1070        maxvalue = self.sql(expression, "maxvalue")
    1071        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    1072        owned = self.sql(expression, "owned")
    1073        owned = f" OWNED BY {owned}" if owned else ""
    1074
    1075        cache = expression.args.get("cache")
    1076        if cache is None:
    1077            cache_str = ""
    1078        elif cache is True:
    1079            cache_str = " CACHE"
    1080        else:
    1081            cache_str = f" CACHE {cache}"
    1082
    1083        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1084        options = f" {options}" if options else ""
    1085
    1086        return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()
    1087
    1088    def clone_sql(self, expression: exp.Clone) -> str:
    1089        this = self.sql(expression, "this")
    1090        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    1091        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
    1092        return f"{shallow}{keyword} {this}"
    1093
    1094    def describe_sql(self, expression: exp.Describe) -> str:
    1095        style = expression.args.get("style")
    1096        style = f" {style}" if style else ""
    1097        return f"DESCRIBE{style} {self.sql(expression, 'this')}"
    1098
    1099    def heredoc_sql(self, expression: exp.Heredoc) -> str:
    1100        tag = self.sql(expression, "tag")
    1101        return f"${tag}${self.sql(expression, 'this')}${tag}$"
    1102
    1103    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    1104        with_ = self.sql(expression, "with")
    1105        if with_:
    1106            sql = f"{with_}{self.sep()}{sql}"
    1107        return sql
    1108
    1109    def with_sql(self, expression: exp.With) -> str:
    1110        sql = self.expressions(expression, flat=True)
    1111        recursive = (
    1112            "RECURSIVE "
    1113            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
    1114            else ""
    1115        )
    1116
    1117        return f"WITH {recursive}{sql}"
    1118
    1119    def cte_sql(self, expression: exp.CTE) -> str:
    1120        alias = self.sql(expression, "alias")
    1121
    1122        materialized = expression.args.get("materialized")
    1123        if materialized is False:
    1124            materialized = "NOT MATERIALIZED "
    1125        elif materialized:
    1126            materialized = "MATERIALIZED "
    1127
    1128        return f"{alias} AS {materialized or ''}{self.wrap(expression)}"
    1129
    1130    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    1131        alias = self.sql(expression, "this")
    1132        columns = self.expressions(expression, key="columns", flat=True)
    1133        columns = f"({columns})" if columns else ""
    1134
    1135        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
    1136            columns = ""
    1137            self.unsupported("Named columns are not supported in table alias.")
    1138
    1139        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
    1140            alias = self._next_name()
    1141
    1142        return f"{alias}{columns}"
    1143
    1144    def bitstring_sql(self, expression: exp.BitString) -> str:
    1145        this = self.sql(expression, "this")
    1146        if self.dialect.BIT_START:
    1147            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    1148        return f"{int(this, 2)}"
    1149
    1150    def hexstring_sql(self, expression: exp.HexString) -> str:
    1151        this = self.sql(expression, "this")
    1152        if self.dialect.HEX_START:
    1153            return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
    1154        return f"{int(this, 16)}"
    1155
    1156    def bytestring_sql(self, expression: exp.ByteString) -> str:
    1157        this = self.sql(expression, "this")
    1158        if self.dialect.BYTE_START:
    1159            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    1160        return this
    1161
    1162    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
    1163        this = self.sql(expression, "this")
    1164        escape = expression.args.get("escape")
    1165
    1166        if self.dialect.UNICODE_START:
    1167            escape_substitute = r"\\\1"
    1168            left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END
    1169        else:
    1170            escape_substitute = r"\\u\1"
    1171            left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END
    1172
    1173        if escape:
    1174            escape_pattern = re.compile(rf"{escape.name}(\d+)")
    1175            escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else ""
    1176        else:
    1177            escape_pattern = ESCAPED_UNICODE_RE
    1178            escape_sql = ""
    1179
    1180        if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE):
    1181            this = escape_pattern.sub(escape_substitute, this)
    1182
    1183        return f"{left_quote}{this}{right_quote}{escape_sql}"
    1184
    1185    def rawstring_sql(self, expression: exp.RawString) -> str:
    1186        string = self.escape_str(expression.this.replace("\\", "\\\\"), escape_backslash=False)
    1187        return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}"
    1188
    1189    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    1190        this = self.sql(expression, "this")
    1191        specifier = self.sql(expression, "expression")
    1192        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    1193        return f"{this}{specifier}"
    1194
    1195    def datatype_sql(self, expression: exp.DataType) -> str:
    1196        type_value = expression.this
    1197
    1198        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
    1199            type_sql = self.sql(expression, "kind")
    1200        else:
    1201            type_sql = (
    1202                self.TYPE_MAPPING.get(type_value, type_value.value)
    1203                if isinstance(type_value, exp.DataType.Type)
    1204                else type_value
    1205            )
    1206
    1207        nested = ""
    1208        interior = self.expressions(expression, flat=True)
    1209        values = ""
    1210
    1211        if interior:
    1212            if expression.args.get("nested"):
    1213                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    1214                if expression.args.get("values") is not None:
    1215                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    1216                    values = self.expressions(expression, key="values", flat=True)
    1217                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    1218            elif type_value == exp.DataType.Type.INTERVAL:
    1219                nested = f" {interior}"
    1220            else:
    1221                nested = f"({interior})"
    1222
    1223        type_sql = f"{type_sql}{nested}{values}"
    1224        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
    1225            exp.DataType.Type.TIMETZ,
    1226            exp.DataType.Type.TIMESTAMPTZ,
    1227        ):
    1228            type_sql = f"{type_sql} WITH TIME ZONE"
    1229
    1230        return type_sql
    1231
    1232    def directory_sql(self, expression: exp.Directory) -> str:
    1233        local = "LOCAL " if expression.args.get("local") else ""
    1234        row_format = self.sql(expression, "row_format")
    1235        row_format = f" {row_format}" if row_format else ""
    1236        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"
    1237
    1238    def delete_sql(self, expression: exp.Delete) -> str:
    1239        this = self.sql(expression, "this")
    1240        this = f" FROM {this}" if this else ""
    1241        using = self.sql(expression, "using")
    1242        using = f" USING {using}" if using else ""
    1243        where = self.sql(expression, "where")
    1244        returning = self.sql(expression, "returning")
    1245        limit = self.sql(expression, "limit")
    1246        tables = self.expressions(expression, key="tables")
    1247        tables = f" {tables}" if tables else ""
    1248        if self.RETURNING_END:
    1249            expression_sql = f"{this}{using}{where}{returning}{limit}"
    1250        else:
    1251            expression_sql = f"{returning}{this}{using}{where}{limit}"
    1252        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")
    1253
    1254    def drop_sql(self, expression: exp.Drop) -> str:
    1255        this = self.sql(expression, "this")
    1256        expressions = self.expressions(expression, flat=True)
    1257        expressions = f" ({expressions})" if expressions else ""
    1258        kind = expression.args["kind"]
    1259        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    1260        on_cluster = self.sql(expression, "cluster")
    1261        on_cluster = f" {on_cluster}" if on_cluster else ""
    1262        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1263        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    1264        cascade = " CASCADE" if expression.args.get("cascade") else ""
    1265        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    1266        purge = " PURGE" if expression.args.get("purge") else ""
    1267        return f"DROP{temporary}{materialized} {kind}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}"
    1268
    1269    def except_sql(self, expression: exp.Except) -> str:
    1270        return self.set_operations(expression)
    1271
    1272    def except_op(self, expression: exp.Except) -> str:
    1273        return f"EXCEPT{'' if expression.args.get('distinct') else ' ALL'}"
    1274
    1275    def fetch_sql(self, expression: exp.Fetch) -> str:
    1276        direction = expression.args.get("direction")
    1277        direction = f" {direction}" if direction else ""
    1278        count = expression.args.get("count")
    1279        count = f" {count}" if count else ""
    1280        if expression.args.get("percent"):
    1281            count = f"{count} PERCENT"
    1282        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    1283        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"
    1284
    1285    def filter_sql(self, expression: exp.Filter) -> str:
    1286        if self.AGGREGATE_FILTER_SUPPORTED:
    1287            this = self.sql(expression, "this")
    1288            where = self.sql(expression, "expression").strip()
    1289            return f"{this} FILTER({where})"
    1290
    1291        agg = expression.this
    1292        agg_arg = agg.this
    1293        cond = expression.expression.this
    1294        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1295        return self.sql(agg)
    1296
    1297    def hint_sql(self, expression: exp.Hint) -> str:
    1298        if not self.QUERY_HINTS:
    1299            self.unsupported("Hints are not supported")
    1300            return ""
    1301
    1302        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"
    1303
    1304    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
    1305        using = self.sql(expression, "using")
    1306        using = f" USING {using}" if using else ""
    1307        columns = self.expressions(expression, key="columns", flat=True)
    1308        columns = f"({columns})" if columns else ""
    1309        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1310        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1311        where = self.sql(expression, "where")
    1312        include = self.expressions(expression, key="include", flat=True)
    1313        if include:
    1314            include = f" INCLUDE ({include})"
    1315        with_storage = self.expressions(expression, key="with_storage", flat=True)
    1316        with_storage = f" WITH ({with_storage})" if with_storage else ""
    1317        tablespace = self.sql(expression, "tablespace")
    1318        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
    1319        on = self.sql(expression, "on")
    1320        on = f" ON {on}" if on else ""
    1321
    1322        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"
    1323
    1324    def index_sql(self, expression: exp.Index) -> str:
    1325        unique = "UNIQUE " if expression.args.get("unique") else ""
    1326        primary = "PRIMARY " if expression.args.get("primary") else ""
    1327        amp = "AMP " if expression.args.get("amp") else ""
    1328        name = self.sql(expression, "this")
    1329        name = f"{name} " if name else ""
    1330        table = self.sql(expression, "table")
    1331        table = f"{self.INDEX_ON} {table}" if table else ""
    1332
    1333        index = "INDEX " if not table else ""
    1334
    1335        params = self.sql(expression, "params")
    1336        return f"{unique}{primary}{amp}{index}{name}{table}{params}"
    1337
    1338    def identifier_sql(self, expression: exp.Identifier) -> str:
    1339        text = expression.name
    1340        lower = text.lower()
    1341        text = lower if self.normalize and not expression.quoted else text
    1342        text = text.replace(self.dialect.IDENTIFIER_END, self._escaped_identifier_end)
    1343        if (
    1344            expression.quoted
    1345            or self.dialect.can_identify(text, self.identify)
    1346            or lower in self.RESERVED_KEYWORDS
    1347            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1348        ):
    1349            text = f"{self.dialect.IDENTIFIER_START}{text}{self.dialect.IDENTIFIER_END}"
    1350        return text
    1351
    1352    def hex_sql(self, expression: exp.Hex) -> str:
    1353        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1354        if self.dialect.HEX_LOWERCASE:
    1355            text = self.func("LOWER", text)
    1356
    1357        return text
    1358
    1359    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
    1360        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1361        if not self.dialect.HEX_LOWERCASE:
    1362            text = self.func("LOWER", text)
    1363        return text
    1364
    1365    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1366        input_format = self.sql(expression, "input_format")
    1367        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1368        output_format = self.sql(expression, "output_format")
    1369        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1370        return self.sep().join((input_format, output_format))
    1371
    1372    def national_sql(self, expression: exp.National, prefix: str = "N") -> str:
    1373        string = self.sql(exp.Literal.string(expression.name))
    1374        return f"{prefix}{string}"
    1375
    1376    def partition_sql(self, expression: exp.Partition) -> str:
    1377        return f"PARTITION({self.expressions(expression, flat=True)})"
    1378
    1379    def properties_sql(self, expression: exp.Properties) -> str:
    1380        root_properties = []
    1381        with_properties = []
    1382
    1383        for p in expression.expressions:
    1384            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1385            if p_loc == exp.Properties.Location.POST_WITH:
    1386                with_properties.append(p)
    1387            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1388                root_properties.append(p)
    1389
    1390        root_props = self.root_properties(exp.Properties(expressions=root_properties))
    1391        with_props = self.with_properties(exp.Properties(expressions=with_properties))
    1392
    1393        if root_props and with_props and not self.pretty:
    1394            with_props = " " + with_props
    1395
    1396        return root_props + with_props
    1397
    1398    def root_properties(self, properties: exp.Properties) -> str:
    1399        if properties.expressions:
    1400            return self.expressions(properties, indent=False, sep=" ")
    1401        return ""
    1402
    1403    def properties(
    1404        self,
    1405        properties: exp.Properties,
    1406        prefix: str = "",
    1407        sep: str = ", ",
    1408        suffix: str = "",
    1409        wrapped: bool = True,
    1410    ) -> str:
    1411        if properties.expressions:
    1412            expressions = self.expressions(properties, sep=sep, indent=False)
    1413            if expressions:
    1414                expressions = self.wrap(expressions) if wrapped else expressions
    1415                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1416        return ""
    1417
    1418    def with_properties(self, properties: exp.Properties) -> str:
    1419        return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep=""))
    1420
    1421    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1422        properties_locs = defaultdict(list)
    1423        for p in properties.expressions:
    1424            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1425            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1426                properties_locs[p_loc].append(p)
    1427            else:
    1428                self.unsupported(f"Unsupported property {p.key}")
    1429
    1430        return properties_locs
    1431
    1432    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1433        if isinstance(expression.this, exp.Dot):
    1434            return self.sql(expression, "this")
    1435        return f"'{expression.name}'" if string_key else expression.name
    1436
    1437    def property_sql(self, expression: exp.Property) -> str:
    1438        property_cls = expression.__class__
    1439        if property_cls == exp.Property:
    1440            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1441
    1442        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1443        if not property_name:
    1444            self.unsupported(f"Unsupported property {expression.key}")
    1445
    1446        return f"{property_name}={self.sql(expression, 'this')}"
    1447
    1448    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1449        if self.SUPPORTS_CREATE_TABLE_LIKE:
    1450            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1451            options = f" {options}" if options else ""
    1452
    1453            like = f"LIKE {self.sql(expression, 'this')}{options}"
    1454            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
    1455                like = f"({like})"
    1456
    1457            return like
    1458
    1459        if expression.expressions:
    1460            self.unsupported("Transpilation of LIKE property options is unsupported")
    1461
    1462        select = exp.select("*").from_(expression.this).limit(0)
    1463        return f"AS {self.sql(select)}"
    1464
    1465    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1466        no = "NO " if expression.args.get("no") else ""
    1467        protection = " PROTECTION" if expression.args.get("protection") else ""
    1468        return f"{no}FALLBACK{protection}"
    1469
    1470    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1471        no = "NO " if expression.args.get("no") else ""
    1472        local = expression.args.get("local")
    1473        local = f"{local} " if local else ""
    1474        dual = "DUAL " if expression.args.get("dual") else ""
    1475        before = "BEFORE " if expression.args.get("before") else ""
    1476        after = "AFTER " if expression.args.get("after") else ""
    1477        return f"{no}{local}{dual}{before}{after}JOURNAL"
    1478
    1479    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1480        freespace = self.sql(expression, "this")
    1481        percent = " PERCENT" if expression.args.get("percent") else ""
    1482        return f"FREESPACE={freespace}{percent}"
    1483
    1484    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1485        if expression.args.get("default"):
    1486            property = "DEFAULT"
    1487        elif expression.args.get("on"):
    1488            property = "ON"
    1489        else:
    1490            property = "OFF"
    1491        return f"CHECKSUM={property}"
    1492
    1493    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1494        if expression.args.get("no"):
    1495            return "NO MERGEBLOCKRATIO"
    1496        if expression.args.get("default"):
    1497            return "DEFAULT MERGEBLOCKRATIO"
    1498
    1499        percent = " PERCENT" if expression.args.get("percent") else ""
    1500        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
    1501
    1502    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1503        default = expression.args.get("default")
    1504        minimum = expression.args.get("minimum")
    1505        maximum = expression.args.get("maximum")
    1506        if default or minimum or maximum:
    1507            if default:
    1508                prop = "DEFAULT"
    1509            elif minimum:
    1510                prop = "MINIMUM"
    1511            else:
    1512                prop = "MAXIMUM"
    1513            return f"{prop} DATABLOCKSIZE"
    1514        units = expression.args.get("units")
    1515        units = f" {units}" if units else ""
    1516        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
    1517
    1518    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1519        autotemp = expression.args.get("autotemp")
    1520        always = expression.args.get("always")
    1521        default = expression.args.get("default")
    1522        manual = expression.args.get("manual")
    1523        never = expression.args.get("never")
    1524
    1525        if autotemp is not None:
    1526            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1527        elif always:
    1528            prop = "ALWAYS"
    1529        elif default:
    1530            prop = "DEFAULT"
    1531        elif manual:
    1532            prop = "MANUAL"
    1533        elif never:
    1534            prop = "NEVER"
    1535        return f"BLOCKCOMPRESSION={prop}"
    1536
    1537    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1538        no = expression.args.get("no")
    1539        no = " NO" if no else ""
    1540        concurrent = expression.args.get("concurrent")
    1541        concurrent = " CONCURRENT" if concurrent else ""
    1542        target = self.sql(expression, "target")
    1543        target = f" {target}" if target else ""
    1544        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"
    1545
    1546    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1547        if isinstance(expression.this, list):
    1548            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1549        if expression.this:
    1550            modulus = self.sql(expression, "this")
    1551            remainder = self.sql(expression, "expression")
    1552            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1553
    1554        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1555        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1556        return f"FROM ({from_expressions}) TO ({to_expressions})"
    1557
    1558    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1559        this = self.sql(expression, "this")
    1560
    1561        for_values_or_default = expression.expression
    1562        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1563            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1564        else:
    1565            for_values_or_default = " DEFAULT"
    1566
    1567        return f"PARTITION OF {this}{for_values_or_default}"
    1568
    1569    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1570        kind = expression.args.get("kind")
    1571        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1572        for_or_in = expression.args.get("for_or_in")
    1573        for_or_in = f" {for_or_in}" if for_or_in else ""
    1574        lock_type = expression.args.get("lock_type")
    1575        override = " OVERRIDE" if expression.args.get("override") else ""
    1576        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"
    1577
    1578    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1579        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1580        statistics = expression.args.get("statistics")
    1581        statistics_sql = ""
    1582        if statistics is not None:
    1583            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1584        return f"{data_sql}{statistics_sql}"
    1585
    1586    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1587        this = self.sql(expression, "this")
    1588        this = f"HISTORY_TABLE={this}" if this else ""
    1589        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
    1590        data_consistency = (
    1591            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
    1592        )
    1593        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    1594        retention_period = (
    1595            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
    1596        )
    1597
    1598        if this:
    1599            on_sql = self.func("ON", this, data_consistency, retention_period)
    1600        else:
    1601            on_sql = "ON" if expression.args.get("on") else "OFF"
    1602
    1603        sql = f"SYSTEM_VERSIONING={on_sql}"
    1604
    1605        return f"WITH({sql})" if expression.args.get("with") else sql
    1606
    1607    def insert_sql(self, expression: exp.Insert) -> str:
    1608        hint = self.sql(expression, "hint")
    1609        overwrite = expression.args.get("overwrite")
    1610
    1611        if isinstance(expression.this, exp.Directory):
    1612            this = " OVERWRITE" if overwrite else " INTO"
    1613        else:
    1614            this = self.INSERT_OVERWRITE if overwrite else " INTO"
    1615
    1616        stored = self.sql(expression, "stored")
    1617        stored = f" {stored}" if stored else ""
    1618        alternative = expression.args.get("alternative")
    1619        alternative = f" OR {alternative}" if alternative else ""
    1620        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1621        is_function = expression.args.get("is_function")
    1622        if is_function:
    1623            this = f"{this} FUNCTION"
    1624        this = f"{this} {self.sql(expression, 'this')}"
    1625
    1626        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1627        where = self.sql(expression, "where")
    1628        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1629        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1630        on_conflict = self.sql(expression, "conflict")
    1631        on_conflict = f" {on_conflict}" if on_conflict else ""
    1632        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1633        returning = self.sql(expression, "returning")
    1634
    1635        if self.RETURNING_END:
    1636            expression_sql = f"{expression_sql}{on_conflict}{returning}"
    1637        else:
    1638            expression_sql = f"{returning}{expression_sql}{on_conflict}"
    1639
    1640        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{where}{expression_sql}"
    1641        return self.prepend_ctes(expression, sql)
    1642
    1643    def intersect_sql(self, expression: exp.Intersect) -> str:
    1644        return self.set_operations(expression)
    1645
    1646    def intersect_op(self, expression: exp.Intersect) -> str:
    1647        return f"INTERSECT{'' if expression.args.get('distinct') else ' ALL'}"
    1648
    1649    def introducer_sql(self, expression: exp.Introducer) -> str:
    1650        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
    1651
    1652    def kill_sql(self, expression: exp.Kill) -> str:
    1653        kind = self.sql(expression, "kind")
    1654        kind = f" {kind}" if kind else ""
    1655        this = self.sql(expression, "this")
    1656        this = f" {this}" if this else ""
    1657        return f"KILL{kind}{this}"
    1658
    1659    def pseudotype_sql(self, expression: exp.PseudoType) -> str:
    1660        return expression.name
    1661
    1662    def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str:
    1663        return expression.name
    1664
    1665    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1666        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1667
    1668        constraint = self.sql(expression, "constraint")
    1669        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
    1670
    1671        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
    1672        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
    1673        action = self.sql(expression, "action")
    1674
    1675        expressions = self.expressions(expression, flat=True)
    1676        if expressions:
    1677            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1678            expressions = f" {set_keyword}{expressions}"
    1679
    1680        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}"
    1681
    1682    def returning_sql(self, expression: exp.Returning) -> str:
    1683        return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}"
    1684
    1685    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1686        fields = self.sql(expression, "fields")
    1687        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1688        escaped = self.sql(expression, "escaped")
    1689        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1690        items = self.sql(expression, "collection_items")
    1691        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1692        keys = self.sql(expression, "map_keys")
    1693        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1694        lines = self.sql(expression, "lines")
    1695        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1696        null = self.sql(expression, "null")
    1697        null = f" NULL DEFINED AS {null}" if null else ""
    1698        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
    1699
    1700    def withtablehint_sql(self, expression: exp.WithTableHint) -> str:
    1701        return f"WITH ({self.expressions(expression, flat=True)})"
    1702
    1703    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1704        this = f"{self.sql(expression, 'this')} INDEX"
    1705        target = self.sql(expression, "target")
    1706        target = f" FOR {target}" if target else ""
    1707        return f"{this}{target} ({self.expressions(expression, flat=True)})"
    1708
    1709    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1710        this = self.sql(expression, "this")
    1711        kind = self.sql(expression, "kind")
    1712        expr = self.sql(expression, "expression")
    1713        return f"{this} ({kind} => {expr})"
    1714
    1715    def table_parts(self, expression: exp.Table) -> str:
    1716        return ".".join(
    1717            self.sql(part)
    1718            for part in (
    1719                expression.args.get("catalog"),
    1720                expression.args.get("db"),
    1721                expression.args.get("this"),
    1722            )
    1723            if part is not None
    1724        )
    1725
    1726    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1727        table = self.table_parts(expression)
    1728        only = "ONLY " if expression.args.get("only") else ""
    1729        partition = self.sql(expression, "partition")
    1730        partition = f" {partition}" if partition else ""
    1731        version = self.sql(expression, "version")
    1732        version = f" {version}" if version else ""
    1733        alias = self.sql(expression, "alias")
    1734        alias = f"{sep}{alias}" if alias else ""
    1735        hints = self.expressions(expression, key="hints", sep=" ")
    1736        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1737        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1738        pivots = f" {pivots}" if pivots else ""
    1739        joins = self.indent(
    1740            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    1741        )
    1742        laterals = self.expressions(expression, key="laterals", sep="")
    1743
    1744        file_format = self.sql(expression, "format")
    1745        if file_format:
    1746            pattern = self.sql(expression, "pattern")
    1747            pattern = f", PATTERN => {pattern}" if pattern else ""
    1748            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    1749
    1750        ordinality = expression.args.get("ordinality") or ""
    1751        if ordinality:
    1752            ordinality = f" WITH ORDINALITY{alias}"
    1753            alias = ""
    1754
    1755        when = self.sql(expression, "when")
    1756        if when:
    1757            table = f"{table} {when}"
    1758
    1759        changes = self.sql(expression, "changes")
    1760        changes = f" {changes}" if changes else ""
    1761
    1762        rows_from = self.expressions(expression, key="rows_from")
    1763        if rows_from:
    1764            table = f"ROWS FROM {self.wrap(rows_from)}"
    1765
    1766        return f"{only}{table}{changes}{partition}{version}{file_format}{alias}{hints}{pivots}{joins}{laterals}{ordinality}"
    1767
    1768    def tablesample_sql(
    1769        self,
    1770        expression: exp.TableSample,
    1771        sep: str = " AS ",
    1772        tablesample_keyword: t.Optional[str] = None,
    1773    ) -> str:
    1774        if self.dialect.ALIAS_POST_TABLESAMPLE and expression.this and expression.this.alias:
    1775            table = expression.this.copy()
    1776            table.set("alias", None)
    1777            this = self.sql(table)
    1778            alias = f"{sep}{self.sql(expression.this, 'alias')}"
    1779        else:
    1780            this = self.sql(expression, "this")
    1781            alias = ""
    1782
    1783        method = self.sql(expression, "method")
    1784        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1785        numerator = self.sql(expression, "bucket_numerator")
    1786        denominator = self.sql(expression, "bucket_denominator")
    1787        field = self.sql(expression, "bucket_field")
    1788        field = f" ON {field}" if field else ""
    1789        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1790        seed = self.sql(expression, "seed")
    1791        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
    1792
    1793        size = self.sql(expression, "size")
    1794        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
    1795            size = f"{size} ROWS"
    1796
    1797        percent = self.sql(expression, "percent")
    1798        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
    1799            percent = f"{percent} PERCENT"
    1800
    1801        expr = f"{bucket}{percent}{size}"
    1802        if self.TABLESAMPLE_REQUIRES_PARENS:
    1803            expr = f"({expr})"
    1804
    1805        return (
    1806            f"{this} {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}{alias}"
    1807        )
    1808
    1809    def pivot_sql(self, expression: exp.Pivot) -> str:
    1810        expressions = self.expressions(expression, flat=True)
    1811
    1812        if expression.this:
    1813            this = self.sql(expression, "this")
    1814            if not expressions:
    1815                return f"UNPIVOT {this}"
    1816
    1817            on = f"{self.seg('ON')} {expressions}"
    1818            using = self.expressions(expression, key="using", flat=True)
    1819            using = f"{self.seg('USING')} {using}" if using else ""
    1820            group = self.sql(expression, "group")
    1821            return f"PIVOT {this}{on}{using}{group}"
    1822
    1823        alias = self.sql(expression, "alias")
    1824        alias = f" AS {alias}" if alias else ""
    1825        direction = "UNPIVOT" if expression.unpivot else "PIVOT"
    1826        field = self.sql(expression, "field")
    1827        include_nulls = expression.args.get("include_nulls")
    1828        if include_nulls is not None:
    1829            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    1830        else:
    1831            nulls = ""
    1832        return f"{direction}{nulls}({expressions} FOR {field}){alias}"
    1833
    1834    def version_sql(self, expression: exp.Version) -> str:
    1835        this = f"FOR {expression.name}"
    1836        kind = expression.text("kind")
    1837        expr = self.sql(expression, "expression")
    1838        return f"{this} {kind} {expr}"
    1839
    1840    def tuple_sql(self, expression: exp.Tuple) -> str:
    1841        return f"({self.expressions(expression, flat=True)})"
    1842
    1843    def update_sql(self, expression: exp.Update) -> str:
    1844        this = self.sql(expression, "this")
    1845        set_sql = self.expressions(expression, flat=True)
    1846        from_sql = self.sql(expression, "from")
    1847        where_sql = self.sql(expression, "where")
    1848        returning = self.sql(expression, "returning")
    1849        order = self.sql(expression, "order")
    1850        limit = self.sql(expression, "limit")
    1851        if self.RETURNING_END:
    1852            expression_sql = f"{from_sql}{where_sql}{returning}"
    1853        else:
    1854            expression_sql = f"{returning}{from_sql}{where_sql}"
    1855        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    1856        return self.prepend_ctes(expression, sql)
    1857
    1858    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
    1859        values_as_table = values_as_table and self.VALUES_AS_TABLE
    1860
    1861        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    1862        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
    1863            args = self.expressions(expression)
    1864            alias = self.sql(expression, "alias")
    1865            values = f"VALUES{self.seg('')}{args}"
    1866            values = (
    1867                f"({values})"
    1868                if self.WRAP_DERIVED_VALUES and (alias or isinstance(expression.parent, exp.From))
    1869                else values
    1870            )
    1871            return f"{values} AS {alias}" if alias else values
    1872
    1873        # Converts `VALUES...` expression into a series of select unions.
    1874        alias_node = expression.args.get("alias")
    1875        column_names = alias_node and alias_node.columns
    1876
    1877        selects: t.List[exp.Query] = []
    1878
    1879        for i, tup in enumerate(expression.expressions):
    1880            row = tup.expressions
    1881
    1882            if i == 0 and column_names:
    1883                row = [
    1884                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    1885                ]
    1886
    1887            selects.append(exp.Select(expressions=row))
    1888
    1889        if self.pretty:
    1890            # This may result in poor performance for large-cardinality `VALUES` tables, due to
    1891            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
    1892            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
    1893            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
    1894            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
    1895
    1896        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
    1897        unions = " UNION ALL ".join(self.sql(select) for select in selects)
    1898        return f"({unions}){alias}"
    1899
    1900    def var_sql(self, expression: exp.Var) -> str:
    1901        return self.sql(expression, "this")
    1902
    1903    def into_sql(self, expression: exp.Into) -> str:
    1904        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1905        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
    1906        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
    1907
    1908    def from_sql(self, expression: exp.From) -> str:
    1909        return f"{self.seg('FROM')} {self.sql(expression, 'this')}"
    1910
    1911    def group_sql(self, expression: exp.Group) -> str:
    1912        group_by_all = expression.args.get("all")
    1913        if group_by_all is True:
    1914            modifier = " ALL"
    1915        elif group_by_all is False:
    1916            modifier = " DISTINCT"
    1917        else:
    1918            modifier = ""
    1919
    1920        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
    1921
    1922        grouping_sets = self.expressions(expression, key="grouping_sets", indent=False)
    1923        grouping_sets = (
    1924            f"{self.seg('GROUPING SETS')} {self.wrap(grouping_sets)}" if grouping_sets else ""
    1925        )
    1926
    1927        cube = expression.args.get("cube", [])
    1928        if seq_get(cube, 0) is True:
    1929            return f"{group_by}{self.seg('WITH CUBE')}"
    1930        else:
    1931            cube_sql = self.expressions(expression, key="cube", indent=False)
    1932            cube_sql = f"{self.seg('CUBE')} {self.wrap(cube_sql)}" if cube_sql else ""
    1933
    1934        rollup = expression.args.get("rollup", [])
    1935        if seq_get(rollup, 0) is True:
    1936            return f"{group_by}{self.seg('WITH ROLLUP')}"
    1937        else:
    1938            rollup_sql = self.expressions(expression, key="rollup", indent=False)
    1939            rollup_sql = f"{self.seg('ROLLUP')} {self.wrap(rollup_sql)}" if rollup_sql else ""
    1940
    1941        groupings = csv(
    1942            grouping_sets,
    1943            cube_sql,
    1944            rollup_sql,
    1945            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    1946            sep=self.GROUPINGS_SEP,
    1947        )
    1948
    1949        if expression.args.get("expressions") and groupings:
    1950            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    1951
    1952        return f"{group_by}{groupings}"
    1953
    1954    def having_sql(self, expression: exp.Having) -> str:
    1955        this = self.indent(self.sql(expression, "this"))
    1956        return f"{self.seg('HAVING')}{self.sep()}{this}"
    1957
    1958    def connect_sql(self, expression: exp.Connect) -> str:
    1959        start = self.sql(expression, "start")
    1960        start = self.seg(f"START WITH {start}") if start else ""
    1961        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
    1962        connect = self.sql(expression, "connect")
    1963        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
    1964        return start + connect
    1965
    1966    def prior_sql(self, expression: exp.Prior) -> str:
    1967        return f"PRIOR {self.sql(expression, 'this')}"
    1968
    1969    def join_sql(self, expression: exp.Join) -> str:
    1970        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    1971            side = None
    1972        else:
    1973            side = expression.side
    1974
    1975        op_sql = " ".join(
    1976            op
    1977            for op in (
    1978                expression.method,
    1979                "GLOBAL" if expression.args.get("global") else None,
    1980                side,
    1981                expression.kind,
    1982                expression.hint if self.JOIN_HINTS else None,
    1983            )
    1984            if op
    1985        )
    1986        match_cond = self.sql(expression, "match_condition")
    1987        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
    1988        on_sql = self.sql(expression, "on")
    1989        using = expression.args.get("using")
    1990
    1991        if not on_sql and using:
    1992            on_sql = csv(*(self.sql(column) for column in using))
    1993
    1994        this = expression.this
    1995        this_sql = self.sql(this)
    1996
    1997        if on_sql:
    1998            on_sql = self.indent(on_sql, skip_first=True)
    1999            space = self.seg(" " * self.pad) if self.pretty else " "
    2000            if using:
    2001                on_sql = f"{space}USING ({on_sql})"
    2002            else:
    2003                on_sql = f"{space}ON {on_sql}"
    2004        elif not op_sql:
    2005            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
    2006                return f" {this_sql}"
    2007
    2008            return f", {this_sql}"
    2009
    2010        if op_sql != "STRAIGHT_JOIN":
    2011            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    2012
    2013        return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}"
    2014
    2015    def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str:
    2016        args = self.expressions(expression, flat=True)
    2017        args = f"({args})" if len(args.split(",")) > 1 else args
    2018        return f"{args} {arrow_sep} {self.sql(expression, 'this')}"
    2019
    2020    def lateral_op(self, expression: exp.Lateral) -> str:
    2021        cross_apply = expression.args.get("cross_apply")
    2022
    2023        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    2024        if cross_apply is True:
    2025            op = "INNER JOIN "
    2026        elif cross_apply is False:
    2027            op = "LEFT JOIN "
    2028        else:
    2029            op = ""
    2030
    2031        return f"{op}LATERAL"
    2032
    2033    def lateral_sql(self, expression: exp.Lateral) -> str:
    2034        this = self.sql(expression, "this")
    2035
    2036        if expression.args.get("view"):
    2037            alias = expression.args["alias"]
    2038            columns = self.expressions(alias, key="columns", flat=True)
    2039            table = f" {alias.name}" if alias.name else ""
    2040            columns = f" AS {columns}" if columns else ""
    2041            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    2042            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    2043
    2044        alias = self.sql(expression, "alias")
    2045        alias = f" AS {alias}" if alias else ""
    2046        return f"{self.lateral_op(expression)} {this}{alias}"
    2047
    2048    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    2049        this = self.sql(expression, "this")
    2050
    2051        args = [
    2052            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    2053            for e in (expression.args.get(k) for k in ("offset", "expression"))
    2054            if e
    2055        ]
    2056
    2057        args_sql = ", ".join(self.sql(e) for e in args)
    2058        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
    2059        expressions = self.expressions(expression, flat=True)
    2060        expressions = f" BY {expressions}" if expressions else ""
    2061
    2062        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}"
    2063
    2064    def offset_sql(self, expression: exp.Offset) -> str:
    2065        this = self.sql(expression, "this")
    2066        value = expression.expression
    2067        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    2068        expressions = self.expressions(expression, flat=True)
    2069        expressions = f" BY {expressions}" if expressions else ""
    2070        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"
    2071
    2072    def setitem_sql(self, expression: exp.SetItem) -> str:
    2073        kind = self.sql(expression, "kind")
    2074        kind = f"{kind} " if kind else ""
    2075        this = self.sql(expression, "this")
    2076        expressions = self.expressions(expression)
    2077        collate = self.sql(expression, "collate")
    2078        collate = f" COLLATE {collate}" if collate else ""
    2079        global_ = "GLOBAL " if expression.args.get("global") else ""
    2080        return f"{global_}{kind}{this}{expressions}{collate}"
    2081
    2082    def set_sql(self, expression: exp.Set) -> str:
    2083        expressions = (
    2084            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    2085        )
    2086        tag = " TAG" if expression.args.get("tag") else ""
    2087        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"
    2088
    2089    def pragma_sql(self, expression: exp.Pragma) -> str:
    2090        return f"PRAGMA {self.sql(expression, 'this')}"
    2091
    2092    def lock_sql(self, expression: exp.Lock) -> str:
    2093        if not self.LOCKING_READS_SUPPORTED:
    2094            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    2095            return ""
    2096
    2097        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    2098        expressions = self.expressions(expression, flat=True)
    2099        expressions = f" OF {expressions}" if expressions else ""
    2100        wait = expression.args.get("wait")
    2101
    2102        if wait is not None:
    2103            if isinstance(wait, exp.Literal):
    2104                wait = f" WAIT {self.sql(wait)}"
    2105            else:
    2106                wait = " NOWAIT" if wait else " SKIP LOCKED"
    2107
    2108        return f"{lock_type}{expressions}{wait or ''}"
    2109
    2110    def literal_sql(self, expression: exp.Literal) -> str:
    2111        text = expression.this or ""
    2112        if expression.is_string:
    2113            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    2114        return text
    2115
    2116    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
    2117        if self.dialect.ESCAPED_SEQUENCES:
    2118            to_escaped = self.dialect.ESCAPED_SEQUENCES
    2119            text = "".join(
    2120                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
    2121            )
    2122
    2123        return self._replace_line_breaks(text).replace(
    2124            self.dialect.QUOTE_END, self._escaped_quote_end
    2125        )
    2126
    2127    def loaddata_sql(self, expression: exp.LoadData) -> str:
    2128        local = " LOCAL" if expression.args.get("local") else ""
    2129        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    2130        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    2131        this = f" INTO TABLE {self.sql(expression, 'this')}"
    2132        partition = self.sql(expression, "partition")
    2133        partition = f" {partition}" if partition else ""
    2134        input_format = self.sql(expression, "input_format")
    2135        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    2136        serde = self.sql(expression, "serde")
    2137        serde = f" SERDE {serde}" if serde else ""
    2138        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
    2139
    2140    def null_sql(self, *_) -> str:
    2141        return "NULL"
    2142
    2143    def boolean_sql(self, expression: exp.Boolean) -> str:
    2144        return "TRUE" if expression.this else "FALSE"
    2145
    2146    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2147        this = self.sql(expression, "this")
    2148        this = f"{this} " if this else this
    2149        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2150        order = self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat)  # type: ignore
    2151        interpolated_values = [
    2152            f"{self.sql(named_expression, 'alias')} AS {self.sql(named_expression, 'this')}"
    2153            for named_expression in expression.args.get("interpolate") or []
    2154        ]
    2155        interpolate = (
    2156            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    2157        )
    2158        return f"{order}{interpolate}"
    2159
    2160    def withfill_sql(self, expression: exp.WithFill) -> str:
    2161        from_sql = self.sql(expression, "from")
    2162        from_sql = f" FROM {from_sql}" if from_sql else ""
    2163        to_sql = self.sql(expression, "to")
    2164        to_sql = f" TO {to_sql}" if to_sql else ""
    2165        step_sql = self.sql(expression, "step")
    2166        step_sql = f" STEP {step_sql}" if step_sql else ""
    2167        return f"WITH FILL{from_sql}{to_sql}{step_sql}"
    2168
    2169    def cluster_sql(self, expression: exp.Cluster) -> str:
    2170        return self.op_expressions("CLUSTER BY", expression)
    2171
    2172    def distribute_sql(self, expression: exp.Distribute) -> str:
    2173        return self.op_expressions("DISTRIBUTE BY", expression)
    2174
    2175    def sort_sql(self, expression: exp.Sort) -> str:
    2176        return self.op_expressions("SORT BY", expression)
    2177
    2178    def ordered_sql(self, expression: exp.Ordered) -> str:
    2179        desc = expression.args.get("desc")
    2180        asc = not desc
    2181
    2182        nulls_first = expression.args.get("nulls_first")
    2183        nulls_last = not nulls_first
    2184        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
    2185        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
    2186        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
    2187
    2188        this = self.sql(expression, "this")
    2189
    2190        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
    2191        nulls_sort_change = ""
    2192        if nulls_first and (
    2193            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    2194        ):
    2195            nulls_sort_change = " NULLS FIRST"
    2196        elif (
    2197            nulls_last
    2198            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    2199            and not nulls_are_last
    2200        ):
    2201            nulls_sort_change = " NULLS LAST"
    2202
    2203        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
    2204        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    2205            window = expression.find_ancestor(exp.Window, exp.Select)
    2206            if isinstance(window, exp.Window) and window.args.get("spec"):
    2207                self.unsupported(
    2208                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
    2209                )
    2210                nulls_sort_change = ""
    2211            elif self.NULL_ORDERING_SUPPORTED is None:
    2212                if expression.this.is_int:
    2213                    self.unsupported(
    2214                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
    2215                    )
    2216                elif not isinstance(expression.this, exp.Rand):
    2217                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
    2218                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
    2219                nulls_sort_change = ""
    2220
    2221        with_fill = self.sql(expression, "with_fill")
    2222        with_fill = f" {with_fill}" if with_fill else ""
    2223
    2224        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"
    2225
    2226    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
    2227        window_frame = self.sql(expression, "window_frame")
    2228        window_frame = f"{window_frame} " if window_frame else ""
    2229
    2230        this = self.sql(expression, "this")
    2231
    2232        return f"{window_frame}{this}"
    2233
    2234    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    2235        partition = self.partition_by_sql(expression)
    2236        order = self.sql(expression, "order")
    2237        measures = self.expressions(expression, key="measures")
    2238        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    2239        rows = self.sql(expression, "rows")
    2240        rows = self.seg(rows) if rows else ""
    2241        after = self.sql(expression, "after")
    2242        after = self.seg(after) if after else ""
    2243        pattern = self.sql(expression, "pattern")
    2244        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    2245        definition_sqls = [
    2246            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    2247            for definition in expression.args.get("define", [])
    2248        ]
    2249        definitions = self.expressions(sqls=definition_sqls)
    2250        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    2251        body = "".join(
    2252            (
    2253                partition,
    2254                order,
    2255                measures,
    2256                rows,
    2257                after,
    2258                pattern,
    2259                define,
    2260            )
    2261        )
    2262        alias = self.sql(expression, "alias")
    2263        alias = f" {alias}" if alias else ""
    2264        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
    2265
    2266    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    2267        limit = expression.args.get("limit")
    2268
    2269        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    2270            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    2271        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    2272            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    2273
    2274        return csv(
    2275            *sqls,
    2276            *[self.sql(join) for join in expression.args.get("joins") or []],
    2277            self.sql(expression, "connect"),
    2278            self.sql(expression, "match"),
    2279            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2280            self.sql(expression, "prewhere"),
    2281            self.sql(expression, "where"),
    2282            self.sql(expression, "group"),
    2283            self.sql(expression, "having"),
    2284            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
    2285            self.sql(expression, "order"),
    2286            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
    2287            *self.after_limit_modifiers(expression),
    2288            self.options_modifier(expression),
    2289            sep="",
    2290        )
    2291
    2292    def options_modifier(self, expression: exp.Expression) -> str:
    2293        options = self.expressions(expression, key="options")
    2294        return f" {options}" if options else ""
    2295
    2296    def queryoption_sql(self, expression: exp.QueryOption) -> str:
    2297        return ""
    2298
    2299    def offset_limit_modifiers(
    2300        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2301    ) -> t.List[str]:
    2302        return [
    2303            self.sql(expression, "offset") if fetch else self.sql(limit),
    2304            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2305        ]
    2306
    2307    def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
    2308        locks = self.expressions(expression, key="locks", sep=" ")
    2309        locks = f" {locks}" if locks else ""
    2310        return [locks, self.sql(expression, "sample")]
    2311
    2312    def select_sql(self, expression: exp.Select) -> str:
    2313        into = expression.args.get("into")
    2314        if not self.SUPPORTS_SELECT_INTO and into:
    2315            into.pop()
    2316
    2317        hint = self.sql(expression, "hint")
    2318        distinct = self.sql(expression, "distinct")
    2319        distinct = f" {distinct}" if distinct else ""
    2320        kind = self.sql(expression, "kind")
    2321
    2322        limit = expression.args.get("limit")
    2323        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
    2324            top = self.limit_sql(limit, top=True)
    2325            limit.pop()
    2326        else:
    2327            top = ""
    2328
    2329        expressions = self.expressions(expression)
    2330
    2331        if kind:
    2332            if kind in self.SELECT_KINDS:
    2333                kind = f" AS {kind}"
    2334            else:
    2335                if kind == "STRUCT":
    2336                    expressions = self.expressions(
    2337                        sqls=[
    2338                            self.sql(
    2339                                exp.Struct(
    2340                                    expressions=[
    2341                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
    2342                                        if isinstance(e, exp.Alias)
    2343                                        else e
    2344                                        for e in expression.expressions
    2345                                    ]
    2346                                )
    2347                            )
    2348                        ]
    2349                    )
    2350                kind = ""
    2351
    2352        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
    2353        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
    2354        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
    2355        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    2356        sql = self.query_modifiers(
    2357            expression,
    2358            f"SELECT{top_distinct}{kind}{expressions}",
    2359            self.sql(expression, "into", comment=False),
    2360            self.sql(expression, "from", comment=False),
    2361        )
    2362
    2363        sql = self.prepend_ctes(expression, sql)
    2364
    2365        if not self.SUPPORTS_SELECT_INTO and into:
    2366            if into.args.get("temporary"):
    2367                table_kind = " TEMPORARY"
    2368            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
    2369                table_kind = " UNLOGGED"
    2370            else:
    2371                table_kind = ""
    2372            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
    2373
    2374        return sql
    2375
    2376    def schema_sql(self, expression: exp.Schema) -> str:
    2377        this = self.sql(expression, "this")
    2378        sql = self.schema_columns_sql(expression)
    2379        return f"{this} {sql}" if this and sql else this or sql
    2380
    2381    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2382        if expression.expressions:
    2383            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2384        return ""
    2385
    2386    def star_sql(self, expression: exp.Star) -> str:
    2387        except_ = self.expressions(expression, key="except", flat=True)
    2388        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
    2389        replace = self.expressions(expression, key="replace", flat=True)
    2390        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
    2391        rename = self.expressions(expression, key="rename", flat=True)
    2392        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
    2393        return f"*{except_}{replace}{rename}"
    2394
    2395    def parameter_sql(self, expression: exp.Parameter) -> str:
    2396        this = self.sql(expression, "this")
    2397        return f"{self.PARAMETER_TOKEN}{this}"
    2398
    2399    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2400        this = self.sql(expression, "this")
    2401        kind = expression.text("kind")
    2402        if kind:
    2403            kind = f"{kind}."
    2404        return f"@@{kind}{this}"
    2405
    2406    def placeholder_sql(self, expression: exp.Placeholder) -> str:
    2407        return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?"
    2408
    2409    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2410        alias = self.sql(expression, "alias")
    2411        alias = f"{sep}{alias}" if alias else ""
    2412
    2413        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    2414        pivots = f" {pivots}" if pivots else ""
    2415
    2416        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2417        return self.prepend_ctes(expression, sql)
    2418
    2419    def qualify_sql(self, expression: exp.Qualify) -> str:
    2420        this = self.indent(self.sql(expression, "this"))
    2421        return f"{self.seg('QUALIFY')}{self.sep()}{this}"
    2422
    2423    def set_operations(self, expression: exp.SetOperation) -> str:
    2424        if not self.SET_OP_MODIFIERS:
    2425            limit = expression.args.get("limit")
    2426            order = expression.args.get("order")
    2427
    2428            if limit or order:
    2429                select = exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
    2430
    2431                if limit:
    2432                    select = select.limit(limit.pop(), copy=False)
    2433                if order:
    2434                    select = select.order_by(order.pop(), copy=False)
    2435                return self.sql(select)
    2436
    2437        sqls: t.List[str] = []
    2438        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    2439
    2440        while stack:
    2441            node = stack.pop()
    2442
    2443            if isinstance(node, exp.SetOperation):
    2444                stack.append(node.expression)
    2445                stack.append(
    2446                    self.maybe_comment(
    2447                        getattr(self, f"{node.key}_op")(node),
    2448                        comments=node.comments,
    2449                        separated=True,
    2450                    )
    2451                )
    2452                stack.append(node.this)
    2453            else:
    2454                sqls.append(self.sql(node))
    2455
    2456        this = self.sep().join(sqls)
    2457        this = self.query_modifiers(expression, this)
    2458        return self.prepend_ctes(expression, this)
    2459
    2460    def union_sql(self, expression: exp.Union) -> str:
    2461        return self.set_operations(expression)
    2462
    2463    def union_op(self, expression: exp.SetOperation) -> str:
    2464        kind = " DISTINCT" if self.EXPLICIT_SET_OP else ""
    2465        kind = kind if expression.args.get("distinct") else " ALL"
    2466        by_name = " BY NAME" if expression.args.get("by_name") else ""
    2467        return f"UNION{kind}{by_name}"
    2468
    2469    def unnest_sql(self, expression: exp.Unnest) -> str:
    2470        args = self.expressions(expression, flat=True)
    2471
    2472        alias = expression.args.get("alias")
    2473        offset = expression.args.get("offset")
    2474
    2475        if self.UNNEST_WITH_ORDINALITY:
    2476            if alias and isinstance(offset, exp.Expression):
    2477                alias.append("columns", offset)
    2478
    2479        if alias and self.dialect.UNNEST_COLUMN_ONLY:
    2480            columns = alias.columns
    2481            alias = self.sql(columns[0]) if columns else ""
    2482        else:
    2483            alias = self.sql(alias)
    2484
    2485        alias = f" AS {alias}" if alias else alias
    2486        if self.UNNEST_WITH_ORDINALITY:
    2487            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2488        else:
    2489            if isinstance(offset, exp.Expression):
    2490                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2491            elif offset:
    2492                suffix = f"{alias} WITH OFFSET"
    2493            else:
    2494                suffix = alias
    2495
    2496        return f"UNNEST({args}){suffix}"
    2497
    2498    def prewhere_sql(self, expression: exp.PreWhere) -> str:
    2499        return ""
    2500
    2501    def where_sql(self, expression: exp.Where) -> str:
    2502        this = self.indent(self.sql(expression, "this"))
    2503        return f"{self.seg('WHERE')}{self.sep()}{this}"
    2504
    2505    def window_sql(self, expression: exp.Window) -> str:
    2506        this = self.sql(expression, "this")
    2507        partition = self.partition_by_sql(expression)
    2508        order = expression.args.get("order")
    2509        order = self.order_sql(order, flat=True) if order else ""
    2510        spec = self.sql(expression, "spec")
    2511        alias = self.sql(expression, "alias")
    2512        over = self.sql(expression, "over") or "OVER"
    2513
    2514        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2515
    2516        first = expression.args.get("first")
    2517        if first is None:
    2518            first = ""
    2519        else:
    2520            first = "FIRST" if first else "LAST"
    2521
    2522        if not partition and not order and not spec and alias:
    2523            return f"{this} {alias}"
    2524
    2525        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    2526        return f"{this} ({args})"
    2527
    2528    def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str:
    2529        partition = self.expressions(expression, key="partition_by", flat=True)
    2530        return f"PARTITION BY {partition}" if partition else ""
    2531
    2532    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2533        kind = self.sql(expression, "kind")
    2534        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2535        end = (
    2536            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2537            or "CURRENT ROW"
    2538        )
    2539        return f"{kind} BETWEEN {start} AND {end}"
    2540
    2541    def withingroup_sql(self, expression: exp.WithinGroup) -> str:
    2542        this = self.sql(expression, "this")
    2543        expression_sql = self.sql(expression, "expression")[1:]  # order has a leading space
    2544        return f"{this} WITHIN GROUP ({expression_sql})"
    2545
    2546    def between_sql(self, expression: exp.Between) -> str:
    2547        this = self.sql(expression, "this")
    2548        low = self.sql(expression, "low")
    2549        high = self.sql(expression, "high")
    2550        return f"{this} BETWEEN {low} AND {high}"
    2551
    2552    def bracket_offset_expressions(self, expression: exp.Bracket) -> t.List[exp.Expression]:
    2553        return apply_index_offset(
    2554            expression.this,
    2555            expression.expressions,
    2556            self.dialect.INDEX_OFFSET - expression.args.get("offset", 0),
    2557        )
    2558
    2559    def bracket_sql(self, expression: exp.Bracket) -> str:
    2560        expressions = self.bracket_offset_expressions(expression)
    2561        expressions_sql = ", ".join(self.sql(e) for e in expressions)
    2562        return f"{self.sql(expression, 'this')}[{expressions_sql}]"
    2563
    2564    def all_sql(self, expression: exp.All) -> str:
    2565        return f"ALL {self.wrap(expression)}"
    2566
    2567    def any_sql(self, expression: exp.Any) -> str:
    2568        this = self.sql(expression, "this")
    2569        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
    2570            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2571                this = self.wrap(this)
    2572            return f"ANY{this}"
    2573        return f"ANY {this}"
    2574
    2575    def exists_sql(self, expression: exp.Exists) -> str:
    2576        return f"EXISTS{self.wrap(expression)}"
    2577
    2578    def case_sql(self, expression: exp.Case) -> str:
    2579        this = self.sql(expression, "this")
    2580        statements = [f"CASE {this}" if this else "CASE"]
    2581
    2582        for e in expression.args["ifs"]:
    2583            statements.append(f"WHEN {self.sql(e, 'this')}")
    2584            statements.append(f"THEN {self.sql(e, 'true')}")
    2585
    2586        default = self.sql(expression, "default")
    2587
    2588        if default:
    2589            statements.append(f"ELSE {default}")
    2590
    2591        statements.append("END")
    2592
    2593        if self.pretty and self.too_wide(statements):
    2594            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2595
    2596        return " ".join(statements)
    2597
    2598    def constraint_sql(self, expression: exp.Constraint) -> str:
    2599        this = self.sql(expression, "this")
    2600        expressions = self.expressions(expression, flat=True)
    2601        return f"CONSTRAINT {this} {expressions}"
    2602
    2603    def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str:
    2604        order = expression.args.get("order")
    2605        order = f" OVER ({self.order_sql(order, flat=True)})" if order else ""
    2606        return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}"
    2607
    2608    def extract_sql(self, expression: exp.Extract) -> str:
    2609        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2610        expression_sql = self.sql(expression, "expression")
    2611        return f"EXTRACT({this} FROM {expression_sql})"
    2612
    2613    def trim_sql(self, expression: exp.Trim) -> str:
    2614        trim_type = self.sql(expression, "position")
    2615
    2616        if trim_type == "LEADING":
    2617            return self.func("LTRIM", expression.this)
    2618        elif trim_type == "TRAILING":
    2619            return self.func("RTRIM", expression.this)
    2620        else:
    2621            return self.func("TRIM", expression.this, expression.expression)
    2622
    2623    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2624        args = expression.expressions
    2625        if isinstance(expression, exp.ConcatWs):
    2626            args = args[1:]  # Skip the delimiter
    2627
    2628        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2629            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
    2630
    2631        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2632            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2633
    2634        return args
    2635
    2636    def concat_sql(self, expression: exp.Concat) -> str:
    2637        expressions = self.convert_concat_args(expression)
    2638
    2639        # Some dialects don't allow a single-argument CONCAT call
    2640        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2641            return self.sql(expressions[0])
    2642
    2643        return self.func("CONCAT", *expressions)
    2644
    2645    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2646        return self.func(
    2647            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2648        )
    2649
    2650    def check_sql(self, expression: exp.Check) -> str:
    2651        this = self.sql(expression, key="this")
    2652        return f"CHECK ({this})"
    2653
    2654    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2655        expressions = self.expressions(expression, flat=True)
    2656        reference = self.sql(expression, "reference")
    2657        reference = f" {reference}" if reference else ""
    2658        delete = self.sql(expression, "delete")
    2659        delete = f" ON DELETE {delete}" if delete else ""
    2660        update = self.sql(expression, "update")
    2661        update = f" ON UPDATE {update}" if update else ""
    2662        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"
    2663
    2664    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2665        expressions = self.expressions(expression, flat=True)
    2666        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2667        options = f" {options}" if options else ""
    2668        return f"PRIMARY KEY ({expressions}){options}"
    2669
    2670    def if_sql(self, expression: exp.If) -> str:
    2671        return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false")))
    2672
    2673    def matchagainst_sql(self, expression: exp.MatchAgainst) -> str:
    2674        modifier = expression.args.get("modifier")
    2675        modifier = f" {modifier}" if modifier else ""
    2676        return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})"
    2677
    2678    def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str:
    2679        return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}"
    2680
    2681    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
    2682        path = self.expressions(expression, sep="", flat=True).lstrip(".")
    2683        if self.QUOTE_JSON_PATH:
    2684            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
    2685
    2686        return path
    2687
    2688    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
    2689        if isinstance(expression, exp.JSONPathPart):
    2690            transform = self.TRANSFORMS.get(expression.__class__)
    2691            if not callable(transform):
    2692                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
    2693                return ""
    2694
    2695            return transform(self, expression)
    2696
    2697        if isinstance(expression, int):
    2698            return str(expression)
    2699
    2700        if self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
    2701            escaped = expression.replace("'", "\\'")
    2702            escaped = f"\\'{expression}\\'"
    2703        else:
    2704            escaped = expression.replace('"', '\\"')
    2705            escaped = f'"{escaped}"'
    2706
    2707        return escaped
    2708
    2709    def formatjson_sql(self, expression: exp.FormatJson) -> str:
    2710        return f"{self.sql(expression, 'this')} FORMAT JSON"
    2711
    2712    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    2713        null_handling = expression.args.get("null_handling")
    2714        null_handling = f" {null_handling}" if null_handling else ""
    2715
    2716        unique_keys = expression.args.get("unique_keys")
    2717        if unique_keys is not None:
    2718            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2719        else:
    2720            unique_keys = ""
    2721
    2722        return_type = self.sql(expression, "return_type")
    2723        return_type = f" RETURNING {return_type}" if return_type else ""
    2724        encoding = self.sql(expression, "encoding")
    2725        encoding = f" ENCODING {encoding}" if encoding else ""
    2726
    2727        return self.func(
    2728            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    2729            *expression.expressions,
    2730            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2731        )
    2732
    2733    def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str:
    2734        return self.jsonobject_sql(expression)
    2735
    2736    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2737        null_handling = expression.args.get("null_handling")
    2738        null_handling = f" {null_handling}" if null_handling else ""
    2739        return_type = self.sql(expression, "return_type")
    2740        return_type = f" RETURNING {return_type}" if return_type else ""
    2741        strict = " STRICT" if expression.args.get("strict") else ""
    2742        return self.func(
    2743            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2744        )
    2745
    2746    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2747        this = self.sql(expression, "this")
    2748        order = self.sql(expression, "order")
    2749        null_handling = expression.args.get("null_handling")
    2750        null_handling = f" {null_handling}" if null_handling else ""
    2751        return_type = self.sql(expression, "return_type")
    2752        return_type = f" RETURNING {return_type}" if return_type else ""
    2753        strict = " STRICT" if expression.args.get("strict") else ""
    2754        return self.func(
    2755            "JSON_ARRAYAGG",
    2756            this,
    2757            suffix=f"{order}{null_handling}{return_type}{strict})",
    2758        )
    2759
    2760    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2761        path = self.sql(expression, "path")
    2762        path = f" PATH {path}" if path else ""
    2763        nested_schema = self.sql(expression, "nested_schema")
    2764
    2765        if nested_schema:
    2766            return f"NESTED{path} {nested_schema}"
    2767
    2768        this = self.sql(expression, "this")
    2769        kind = self.sql(expression, "kind")
    2770        kind = f" {kind}" if kind else ""
    2771        return f"{this}{kind}{path}"
    2772
    2773    def jsonschema_sql(self, expression: exp.JSONSchema) -> str:
    2774        return self.func("COLUMNS", *expression.expressions)
    2775
    2776    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    2777        this = self.sql(expression, "this")
    2778        path = self.sql(expression, "path")
    2779        path = f", {path}" if path else ""
    2780        error_handling = expression.args.get("error_handling")
    2781        error_handling = f" {error_handling}" if error_handling else ""
    2782        empty_handling = expression.args.get("empty_handling")
    2783        empty_handling = f" {empty_handling}" if empty_handling else ""
    2784        schema = self.sql(expression, "schema")
    2785        return self.func(
    2786            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    2787        )
    2788
    2789    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    2790        this = self.sql(expression, "this")
    2791        kind = self.sql(expression, "kind")
    2792        path = self.sql(expression, "path")
    2793        path = f" {path}" if path else ""
    2794        as_json = " AS JSON" if expression.args.get("as_json") else ""
    2795        return f"{this} {kind}{path}{as_json}"
    2796
    2797    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    2798        this = self.sql(expression, "this")
    2799        path = self.sql(expression, "path")
    2800        path = f", {path}" if path else ""
    2801        expressions = self.expressions(expression)
    2802        with_ = (
    2803            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2804            if expressions
    2805            else ""
    2806        )
    2807        return f"OPENJSON({this}{path}){with_}"
    2808
    2809    def in_sql(self, expression: exp.In) -> str:
    2810        query = expression.args.get("query")
    2811        unnest = expression.args.get("unnest")
    2812        field = expression.args.get("field")
    2813        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    2814
    2815        if query:
    2816            in_sql = self.sql(query)
    2817        elif unnest:
    2818            in_sql = self.in_unnest_op(unnest)
    2819        elif field:
    2820            in_sql = self.sql(field)
    2821        else:
    2822            in_sql = f"({self.expressions(expression, flat=True)})"
    2823
    2824        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
    2825
    2826    def in_unnest_op(self, unnest: exp.Unnest) -> str:
    2827        return f"(SELECT {self.sql(unnest)})"
    2828
    2829    def interval_sql(self, expression: exp.Interval) -> str:
    2830        unit = self.sql(expression, "unit")
    2831        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    2832            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    2833        unit = f" {unit}" if unit else ""
    2834
    2835        if self.SINGLE_STRING_INTERVAL:
    2836            this = expression.this.name if expression.this else ""
    2837            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    2838
    2839        this = self.sql(expression, "this")
    2840        if this:
    2841            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    2842            this = f" {this}" if unwrapped else f" ({this})"
    2843
    2844        return f"INTERVAL{this}{unit}"
    2845
    2846    def return_sql(self, expression: exp.Return) -> str:
    2847        return f"RETURN {self.sql(expression, 'this')}"
    2848
    2849    def reference_sql(self, expression: exp.Reference) -> str:
    2850        this = self.sql(expression, "this")
    2851        expressions = self.expressions(expression, flat=True)
    2852        expressions = f"({expressions})" if expressions else ""
    2853        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2854        options = f" {options}" if options else ""
    2855        return f"REFERENCES {this}{expressions}{options}"
    2856
    2857    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    2858        return self.func(self.sql(expression, "this"), *expression.expressions)
    2859
    2860    def paren_sql(self, expression: exp.Paren) -> str:
    2861        sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
    2862        return f"({sql}{self.seg(')', sep='')}"
    2863
    2864    def neg_sql(self, expression: exp.Neg) -> str:
    2865        # This makes sure we don't convert "- - 5" to "--5", which is a comment
    2866        this_sql = self.sql(expression, "this")
    2867        sep = " " if this_sql[0] == "-" else ""
    2868        return f"-{sep}{this_sql}"
    2869
    2870    def not_sql(self, expression: exp.Not) -> str:
    2871        return f"NOT {self.sql(expression, 'this')}"
    2872
    2873    def alias_sql(self, expression: exp.Alias) -> str:
    2874        alias = self.sql(expression, "alias")
    2875        alias = f" AS {alias}" if alias else ""
    2876        return f"{self.sql(expression, 'this')}{alias}"
    2877
    2878    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    2879        alias = expression.args["alias"]
    2880        identifier_alias = isinstance(alias, exp.Identifier)
    2881
    2882        if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2883            alias.replace(exp.Literal.string(alias.output_name))
    2884        elif not identifier_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2885            alias.replace(exp.to_identifier(alias.output_name))
    2886
    2887        return self.alias_sql(expression)
    2888
    2889    def aliases_sql(self, expression: exp.Aliases) -> str:
    2890        return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})"
    2891
    2892    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    2893        this = self.sql(expression, "this")
    2894        index = self.sql(expression, "expression")
    2895        return f"{this} AT {index}"
    2896
    2897    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    2898        this = self.sql(expression, "this")
    2899        zone = self.sql(expression, "zone")
    2900        return f"{this} AT TIME ZONE {zone}"
    2901
    2902    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    2903        this = self.sql(expression, "this")
    2904        zone = self.sql(expression, "zone")
    2905        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"
    2906
    2907    def add_sql(self, expression: exp.Add) -> str:
    2908        return self.binary(expression, "+")
    2909
    2910    def and_sql(
    2911        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
    2912    ) -> str:
    2913        return self.connector_sql(expression, "AND", stack)
    2914
    2915    def or_sql(
    2916        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
    2917    ) -> str:
    2918        return self.connector_sql(expression, "OR", stack)
    2919
    2920    def xor_sql(
    2921        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
    2922    ) -> str:
    2923        return self.connector_sql(expression, "XOR", stack)
    2924
    2925    def connector_sql(
    2926        self,
    2927        expression: exp.Connector,
    2928        op: str,
    2929        stack: t.Optional[t.List[str | exp.Expression]] = None,
    2930    ) -> str:
    2931        if stack is not None:
    2932            if expression.expressions:
    2933                stack.append(self.expressions(expression, sep=f" {op} "))
    2934            else:
    2935                stack.append(expression.right)
    2936                if expression.comments and self.comments:
    2937                    for comment in expression.comments:
    2938                        if comment:
    2939                            op += f" /*{self.pad_comment(comment)}*/"
    2940                stack.extend((op, expression.left))
    2941            return op
    2942
    2943        stack = [expression]
    2944        sqls: t.List[str] = []
    2945        ops = set()
    2946
    2947        while stack:
    2948            node = stack.pop()
    2949            if isinstance(node, exp.Connector):
    2950                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
    2951            else:
    2952                sql = self.sql(node)
    2953                if sqls and sqls[-1] in ops:
    2954                    sqls[-1] += f" {sql}"
    2955                else:
    2956                    sqls.append(sql)
    2957
    2958        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
    2959        return sep.join(sqls)
    2960
    2961    def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str:
    2962        return self.binary(expression, "&")
    2963
    2964    def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str:
    2965        return self.binary(expression, "<<")
    2966
    2967    def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str:
    2968        return f"~{self.sql(expression, 'this')}"
    2969
    2970    def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str:
    2971        return self.binary(expression, "|")
    2972
    2973    def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str:
    2974        return self.binary(expression, ">>")
    2975
    2976    def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str:
    2977        return self.binary(expression, "^")
    2978
    2979    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    2980        format_sql = self.sql(expression, "format")
    2981        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    2982        to_sql = self.sql(expression, "to")
    2983        to_sql = f" {to_sql}" if to_sql else ""
    2984        action = self.sql(expression, "action")
    2985        action = f" {action}" if action else ""
    2986        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{format_sql}{action})"
    2987
    2988    def currentdate_sql(self, expression: exp.CurrentDate) -> str:
    2989        zone = self.sql(expression, "this")
    2990        return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE"
    2991
    2992    def currenttimestamp_sql(self, expression: exp.CurrentTimestamp) -> str:
    2993        return self.func("CURRENT_TIMESTAMP", expression.this)
    2994
    2995    def collate_sql(self, expression: exp.Collate) -> str:
    2996        if self.COLLATE_IS_FUNC:
    2997            return self.function_fallback_sql(expression)
    2998        return self.binary(expression, "COLLATE")
    2999
    3000    def command_sql(self, expression: exp.Command) -> str:
    3001        return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}"
    3002
    3003    def comment_sql(self, expression: exp.Comment) -> str:
    3004        this = self.sql(expression, "this")
    3005        kind = expression.args["kind"]
    3006        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    3007        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    3008        expression_sql = self.sql(expression, "expression")
    3009        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"
    3010
    3011    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    3012        this = self.sql(expression, "this")
    3013        delete = " DELETE" if expression.args.get("delete") else ""
    3014        recompress = self.sql(expression, "recompress")
    3015        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    3016        to_disk = self.sql(expression, "to_disk")
    3017        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    3018        to_volume = self.sql(expression, "to_volume")
    3019        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    3020        return f"{this}{delete}{recompress}{to_disk}{to_volume}"
    3021
    3022    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    3023        where = self.sql(expression, "where")
    3024        group = self.sql(expression, "group")
    3025        aggregates = self.expressions(expression, key="aggregates")
    3026        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    3027
    3028        if not (where or group or aggregates) and len(expression.expressions) == 1:
    3029            return f"TTL {self.expressions(expression, flat=True)}"
    3030
    3031        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
    3032
    3033    def transaction_sql(self, expression: exp.Transaction) -> str:
    3034        return "BEGIN"
    3035
    3036    def commit_sql(self, expression: exp.Commit) -> str:
    3037        chain = expression.args.get("chain")
    3038        if chain is not None:
    3039            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    3040
    3041        return f"COMMIT{chain or ''}"
    3042
    3043    def rollback_sql(self, expression: exp.Rollback) -> str:
    3044        savepoint = expression.args.get("savepoint")
    3045        savepoint = f" TO {savepoint}" if savepoint else ""
    3046        return f"ROLLBACK{savepoint}"
    3047
    3048    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    3049        this = self.sql(expression, "this")
    3050
    3051        dtype = self.sql(expression, "dtype")
    3052        if dtype:
    3053            collate = self.sql(expression, "collate")
    3054            collate = f" COLLATE {collate}" if collate else ""
    3055            using = self.sql(expression, "using")
    3056            using = f" USING {using}" if using else ""
    3057            return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}"
    3058
    3059        default = self.sql(expression, "default")
    3060        if default:
    3061            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    3062
    3063        comment = self.sql(expression, "comment")
    3064        if comment:
    3065            return f"ALTER COLUMN {this} COMMENT {comment}"
    3066
    3067        allow_null = expression.args.get("allow_null")
    3068        drop = expression.args.get("drop")
    3069
    3070        if not drop and not allow_null:
    3071            self.unsupported("Unsupported ALTER COLUMN syntax")
    3072
    3073        if allow_null is not None:
    3074            keyword = "DROP" if drop else "SET"
    3075            return f"ALTER COLUMN {this} {keyword} NOT NULL"
    3076
    3077        return f"ALTER COLUMN {this} DROP DEFAULT"
    3078
    3079    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
    3080        this = self.sql(expression, "this")
    3081        if not isinstance(expression.this, exp.Var):
    3082            this = f"KEY DISTKEY {this}"
    3083        return f"ALTER DISTSTYLE {this}"
    3084
    3085    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
    3086        compound = " COMPOUND" if expression.args.get("compound") else ""
    3087        this = self.sql(expression, "this")
    3088        expressions = self.expressions(expression, flat=True)
    3089        expressions = f"({expressions})" if expressions else ""
    3090        return f"ALTER{compound} SORTKEY {this or expressions}"
    3091
    3092    def renametable_sql(self, expression: exp.RenameTable) -> str:
    3093        if not self.RENAME_TABLE_WITH_DB:
    3094            # Remove db from tables
    3095            expression = expression.transform(
    3096                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    3097            ).assert_is(exp.RenameTable)
    3098        this = self.sql(expression, "this")
    3099        return f"RENAME TO {this}"
    3100
    3101    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    3102        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3103        old_column = self.sql(expression, "this")
    3104        new_column = self.sql(expression, "to")
    3105        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"
    3106
    3107    def alterset_sql(self, expression: exp.AlterSet) -> str:
    3108        exprs = self.expressions(expression, flat=True)
    3109        return f"SET {exprs}"
    3110
    3111    def altertable_sql(self, expression: exp.AlterTable) -> str:
    3112        actions = expression.args["actions"]
    3113
    3114        if isinstance(actions[0], exp.ColumnDef):
    3115            actions = self.add_column_sql(expression)
    3116        elif isinstance(actions[0], exp.Schema):
    3117            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    3118        elif isinstance(actions[0], exp.Delete):
    3119            actions = self.expressions(expression, key="actions", flat=True)
    3120        else:
    3121            actions = self.expressions(expression, key="actions", flat=True)
    3122
    3123        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3124        on_cluster = self.sql(expression, "cluster")
    3125        on_cluster = f" {on_cluster}" if on_cluster else ""
    3126        only = " ONLY" if expression.args.get("only") else ""
    3127        options = self.expressions(expression, key="options")
    3128        options = f", {options}" if options else ""
    3129        return f"ALTER TABLE{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{options}"
    3130
    3131    def add_column_sql(self, expression: exp.AlterTable) -> str:
    3132        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    3133            return self.expressions(
    3134                expression,
    3135                key="actions",
    3136                prefix="ADD COLUMN ",
    3137            )
    3138        return f"ADD {self.expressions(expression, key='actions', flat=True)}"
    3139
    3140    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    3141        expressions = self.expressions(expression)
    3142        exists = " IF EXISTS " if expression.args.get("exists") else " "
    3143        return f"DROP{exists}{expressions}"
    3144
    3145    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
    3146        return f"ADD {self.expressions(expression)}"
    3147
    3148    def distinct_sql(self, expression: exp.Distinct) -> str:
    3149        this = self.expressions(expression, flat=True)
    3150
    3151        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    3152            case = exp.case()
    3153            for arg in expression.expressions:
    3154                case = case.when(arg.is_(exp.null()), exp.null())
    3155            this = self.sql(case.else_(f"({this})"))
    3156
    3157        this = f" {this}" if this else ""
    3158
    3159        on = self.sql(expression, "on")
    3160        on = f" ON {on}" if on else ""
    3161        return f"DISTINCT{this}{on}"
    3162
    3163    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
    3164        return self._embed_ignore_nulls(expression, "IGNORE NULLS")
    3165
    3166    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
    3167        return self._embed_ignore_nulls(expression, "RESPECT NULLS")
    3168
    3169    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    3170        this_sql = self.sql(expression, "this")
    3171        expression_sql = self.sql(expression, "expression")
    3172        kind = "MAX" if expression.args.get("max") else "MIN"
    3173        return f"{this_sql} HAVING {kind} {expression_sql}"
    3174
    3175    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    3176        return self.sql(
    3177            exp.Cast(
    3178                this=exp.Div(this=expression.this, expression=expression.expression),
    3179                to=exp.DataType(this=exp.DataType.Type.INT),
    3180            )
    3181        )
    3182
    3183    def dpipe_sql(self, expression: exp.DPipe) -> str:
    3184        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    3185            return self.func(
    3186                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
    3187            )
    3188        return self.binary(expression, "||")
    3189
    3190    def div_sql(self, expression: exp.Div) -> str:
    3191        l, r = expression.left, expression.right
    3192
    3193        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    3194            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    3195
    3196        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    3197            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
    3198                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    3199
    3200        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    3201            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    3202                return self.sql(
    3203                    exp.cast(
    3204                        l / r,
    3205                        to=exp.DataType.Type.BIGINT,
    3206                    )
    3207                )
    3208
    3209        return self.binary(expression, "/")
    3210
    3211    def overlaps_sql(self, expression: exp.Overlaps) -> str:
    3212        return self.binary(expression, "OVERLAPS")
    3213
    3214    def distance_sql(self, expression: exp.Distance) -> str:
    3215        return self.binary(expression, "<->")
    3216
    3217    def dot_sql(self, expression: exp.Dot) -> str:
    3218        return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}"
    3219
    3220    def eq_sql(self, expression: exp.EQ) -> str:
    3221        return self.binary(expression, "=")
    3222
    3223    def propertyeq_sql(self, expression: exp.PropertyEQ) -> str:
    3224        return self.binary(expression, ":=")
    3225
    3226    def escape_sql(self, expression: exp.Escape) -> str:
    3227        return self.binary(expression, "ESCAPE")
    3228
    3229    def glob_sql(self, expression: exp.Glob) -> str:
    3230        return self.binary(expression, "GLOB")
    3231
    3232    def gt_sql(self, expression: exp.GT) -> str:
    3233        return self.binary(expression, ">")
    3234
    3235    def gte_sql(self, expression: exp.GTE) -> str:
    3236        return self.binary(expression, ">=")
    3237
    3238    def ilike_sql(self, expression: exp.ILike) -> str:
    3239        return self.binary(expression, "ILIKE")
    3240
    3241    def ilikeany_sql(self, expression: exp.ILikeAny) -> str:
    3242        return self.binary(expression, "ILIKE ANY")
    3243
    3244    def is_sql(self, expression: exp.Is) -> str:
    3245        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3246            return self.sql(
    3247                expression.this if expression.expression.this else exp.not_(expression.this)
    3248            )
    3249        return self.binary(expression, "IS")
    3250
    3251    def like_sql(self, expression: exp.Like) -> str:
    3252        return self.binary(expression, "LIKE")
    3253
    3254    def likeany_sql(self, expression: exp.LikeAny) -> str:
    3255        return self.binary(expression, "LIKE ANY")
    3256
    3257    def similarto_sql(self, expression: exp.SimilarTo) -> str:
    3258        return self.binary(expression, "SIMILAR TO")
    3259
    3260    def lt_sql(self, expression: exp.LT) -> str:
    3261        return self.binary(expression, "<")
    3262
    3263    def lte_sql(self, expression: exp.LTE) -> str:
    3264        return self.binary(expression, "<=")
    3265
    3266    def mod_sql(self, expression: exp.Mod) -> str:
    3267        return self.binary(expression, "%")
    3268
    3269    def mul_sql(self, expression: exp.Mul) -> str:
    3270        return self.binary(expression, "*")
    3271
    3272    def neq_sql(self, expression: exp.NEQ) -> str:
    3273        return self.binary(expression, "<>")
    3274
    3275    def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str:
    3276        return self.binary(expression, "IS NOT DISTINCT FROM")
    3277
    3278    def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str:
    3279        return self.binary(expression, "IS DISTINCT FROM")
    3280
    3281    def slice_sql(self, expression: exp.Slice) -> str:
    3282        return self.binary(expression, ":")
    3283
    3284    def sub_sql(self, expression: exp.Sub) -> str:
    3285        return self.binary(expression, "-")
    3286
    3287    def trycast_sql(self, expression: exp.TryCast) -> str:
    3288        return self.cast_sql(expression, safe_prefix="TRY_")
    3289
    3290    def try_sql(self, expression: exp.Try) -> str:
    3291        if not self.TRY_SUPPORTED:
    3292            self.unsupported("Unsupported TRY function")
    3293            return self.sql(expression, "this")
    3294
    3295        return self.func("TRY", expression.this)
    3296
    3297    def log_sql(self, expression: exp.Log) -> str:
    3298        this = expression.this
    3299        expr = expression.expression
    3300
    3301        if self.dialect.LOG_BASE_FIRST is False:
    3302            this, expr = expr, this
    3303        elif self.dialect.LOG_BASE_FIRST is None and expr:
    3304            if this.name in ("2", "10"):
    3305                return self.func(f"LOG{this.name}", expr)
    3306
    3307            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
    3308
    3309        return self.func("LOG", this, expr)
    3310
    3311    def use_sql(self, expression: exp.Use) -> str:
    3312        kind = self.sql(expression, "kind")
    3313        kind = f" {kind}" if kind else ""
    3314        this = self.sql(expression, "this")
    3315        this = f" {this}" if this else ""
    3316        return f"USE{kind}{this}"
    3317
    3318    def binary(self, expression: exp.Binary, op: str) -> str:
    3319        op = self.maybe_comment(op, comments=expression.comments)
    3320        return f"{self.sql(expression, 'this')} {op} {self.sql(expression, 'expression')}"
    3321
    3322    def function_fallback_sql(self, expression: exp.Func) -> str:
    3323        args = []
    3324
    3325        for key in expression.arg_types:
    3326            arg_value = expression.args.get(key)
    3327
    3328            if isinstance(arg_value, list):
    3329                for value in arg_value:
    3330                    args.append(value)
    3331            elif arg_value is not None:
    3332                args.append(arg_value)
    3333
    3334        if self.normalize_functions:
    3335            name = expression.sql_name()
    3336        else:
    3337            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3338
    3339        return self.func(name, *args)
    3340
    3341    def func(
    3342        self,
    3343        name: str,
    3344        *args: t.Optional[exp.Expression | str],
    3345        prefix: str = "(",
    3346        suffix: str = ")",
    3347    ) -> str:
    3348        return f"{self.normalize_func(name)}{prefix}{self.format_args(*args)}{suffix}"
    3349
    3350    def format_args(self, *args: t.Optional[str | exp.Expression]) -> str:
    3351        arg_sqls = tuple(self.sql(arg) for arg in args if arg is not None)
    3352        if self.pretty and self.too_wide(arg_sqls):
    3353            return self.indent("\n" + ",\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True)
    3354        return ", ".join(arg_sqls)
    3355
    3356    def too_wide(self, args: t.Iterable) -> bool:
    3357        return sum(len(arg) for arg in args) > self.max_text_width
    3358
    3359    def format_time(
    3360        self,
    3361        expression: exp.Expression,
    3362        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
    3363        inverse_time_trie: t.Optional[t.Dict] = None,
    3364    ) -> t.Optional[str]:
    3365        return format_time(
    3366            self.sql(expression, "format"),
    3367            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
    3368            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
    3369        )
    3370
    3371    def expressions(
    3372        self,
    3373        expression: t.Optional[exp.Expression] = None,
    3374        key: t.Optional[str] = None,
    3375        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    3376        flat: bool = False,
    3377        indent: bool = True,
    3378        skip_first: bool = False,
    3379        skip_last: bool = False,
    3380        sep: str = ", ",
    3381        prefix: str = "",
    3382        dynamic: bool = False,
    3383        new_line: bool = False,
    3384    ) -> str:
    3385        expressions = expression.args.get(key or "expressions") if expression else sqls
    3386
    3387        if not expressions:
    3388            return ""
    3389
    3390        if flat:
    3391            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    3392
    3393        num_sqls = len(expressions)
    3394
    3395        # These are calculated once in case we have the leading_comma / pretty option set, correspondingly
    3396        if self.pretty and not self.leading_comma:
    3397            stripped_sep = sep.strip()
    3398
    3399        result_sqls = []
    3400        for i, e in enumerate(expressions):
    3401            sql = self.sql(e, comment=False)
    3402            if not sql:
    3403                continue
    3404
    3405            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    3406
    3407            if self.pretty:
    3408                if self.leading_comma:
    3409                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
    3410                else:
    3411                    result_sqls.append(
    3412                        f"{prefix}{sql}{stripped_sep if i + 1 < num_sqls else ''}{comments}"
    3413                    )
    3414            else:
    3415                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    3416
    3417        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
    3418            if new_line:
    3419                result_sqls.insert(0, "")
    3420                result_sqls.append("")
    3421            result_sql = "\n".join(result_sqls)
    3422        else:
    3423            result_sql = "".join(result_sqls)
    3424        return (
    3425            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
    3426            if indent
    3427            else result_sql
    3428        )
    3429
    3430    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3431        flat = flat or isinstance(expression.parent, exp.Properties)
    3432        expressions_sql = self.expressions(expression, flat=flat)
    3433        if flat:
    3434            return f"{op} {expressions_sql}"
    3435        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
    3436
    3437    def naked_property(self, expression: exp.Property) -> str:
    3438        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3439        if not property_name:
    3440            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3441        return f"{property_name} {self.sql(expression, 'this')}"
    3442
    3443    def tag_sql(self, expression: exp.Tag) -> str:
    3444        return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}"
    3445
    3446    def token_sql(self, token_type: TokenType) -> str:
    3447        return self.TOKEN_MAPPING.get(token_type, token_type.name)
    3448
    3449    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3450        this = self.sql(expression, "this")
    3451        expressions = self.no_identify(self.expressions, expression)
    3452        expressions = (
    3453            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3454        )
    3455        return f"{this}{expressions}"
    3456
    3457    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3458        this = self.sql(expression, "this")
    3459        expressions = self.expressions(expression, flat=True)
    3460        return f"{this}({expressions})"
    3461
    3462    def kwarg_sql(self, expression: exp.Kwarg) -> str:
    3463        return self.binary(expression, "=>")
    3464
    3465    def when_sql(self, expression: exp.When) -> str:
    3466        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3467        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3468        condition = self.sql(expression, "condition")
    3469        condition = f" AND {condition}" if condition else ""
    3470
    3471        then_expression = expression.args.get("then")
    3472        if isinstance(then_expression, exp.Insert):
    3473            this = self.sql(then_expression, "this")
    3474            this = f"INSERT {this}" if this else "INSERT"
    3475            then = self.sql(then_expression, "expression")
    3476            then = f"{this} VALUES {then}" if then else this
    3477        elif isinstance(then_expression, exp.Update):
    3478            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3479                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3480            else:
    3481                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    3482        else:
    3483            then = self.sql(then_expression)
    3484        return f"WHEN {matched}{source}{condition} THEN {then}"
    3485
    3486    def merge_sql(self, expression: exp.Merge) -> str:
    3487        table = expression.this
    3488        table_alias = ""
    3489
    3490        hints = table.args.get("hints")
    3491        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3492            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3493            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3494
    3495        this = self.sql(table)
    3496        using = f"USING {self.sql(expression, 'using')}"
    3497        on = f"ON {self.sql(expression, 'on')}"
    3498        expressions = self.expressions(expression, sep=" ", indent=False)
    3499        sep = self.sep()
    3500
    3501        return self.prepend_ctes(
    3502            expression, f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{expressions}"
    3503        )
    3504
    3505    def tochar_sql(self, expression: exp.ToChar) -> str:
    3506        if expression.args.get("format"):
    3507            self.unsupported("Format argument unsupported for TO_CHAR/TO_VARCHAR function")
    3508
    3509        return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT))
    3510
    3511    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3512        if not self.SUPPORTS_TO_NUMBER:
    3513            self.unsupported("Unsupported TO_NUMBER function")
    3514            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3515
    3516        fmt = expression.args.get("format")
    3517        if not fmt:
    3518            self.unsupported("Conversion format is required for TO_NUMBER")
    3519            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3520
    3521        return self.func("TO_NUMBER", expression.this, fmt)
    3522
    3523    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3524        this = self.sql(expression, "this")
    3525        kind = self.sql(expression, "kind")
    3526        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3527        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3528        return f"{this}({kind}{args})"
    3529
    3530    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3531        this = self.sql(expression, "this")
    3532        max = self.sql(expression, "max")
    3533        min = self.sql(expression, "min")
    3534        return f"{this}(MIN {min} MAX {max})"
    3535
    3536    def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str:
    3537        return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}"
    3538
    3539    def oncluster_sql(self, expression: exp.OnCluster) -> str:
    3540        return ""
    3541
    3542    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3543        expressions = self.expressions(expression, key="expressions", flat=True)
    3544        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3545        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3546        buckets = self.sql(expression, "buckets")
    3547        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
    3548
    3549    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3550        this = self.sql(expression, "this")
    3551        having = self.sql(expression, "having")
    3552
    3553        if having:
    3554            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3555
    3556        return self.func("ANY_VALUE", this)
    3557
    3558    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3559        transform = self.func("TRANSFORM", *expression.expressions)
    3560        row_format_before = self.sql(expression, "row_format_before")
    3561        row_format_before = f" {row_format_before}" if row_format_before else ""
    3562        record_writer = self.sql(expression, "record_writer")
    3563        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3564        using = f" USING {self.sql(expression, 'command_script')}"
    3565        schema = self.sql(expression, "schema")
    3566        schema = f" AS {schema}" if schema else ""
    3567        row_format_after = self.sql(expression, "row_format_after")
    3568        row_format_after = f" {row_format_after}" if row_format_after else ""
    3569        record_reader = self.sql(expression, "record_reader")
    3570        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3571        return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"
    3572
    3573    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3574        key_block_size = self.sql(expression, "key_block_size")
    3575        if key_block_size:
    3576            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3577
    3578        using = self.sql(expression, "using")
    3579        if using:
    3580            return f"USING {using}"
    3581
    3582        parser = self.sql(expression, "parser")
    3583        if parser:
    3584            return f"WITH PARSER {parser}"
    3585
    3586        comment = self.sql(expression, "comment")
    3587        if comment:
    3588            return f"COMMENT {comment}"
    3589
    3590        visible = expression.args.get("visible")
    3591        if visible is not None:
    3592            return "VISIBLE" if visible else "INVISIBLE"
    3593
    3594        engine_attr = self.sql(expression, "engine_attr")
    3595        if engine_attr:
    3596            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3597
    3598        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3599        if secondary_engine_attr:
    3600            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3601
    3602        self.unsupported("Unsupported index constraint option.")
    3603        return ""
    3604
    3605    def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str:
    3606        enforced = " ENFORCED" if expression.args.get("enforced") else ""
    3607        return f"CHECK ({self.sql(expression, 'this')}){enforced}"
    3608
    3609    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3610        kind = self.sql(expression, "kind")
    3611        kind = f"{kind} INDEX" if kind else "INDEX"
    3612        this = self.sql(expression, "this")
    3613        this = f" {this}" if this else ""
    3614        index_type = self.sql(expression, "index_type")
    3615        index_type = f" USING {index_type}" if index_type else ""
    3616        expressions = self.expressions(expression, flat=True)
    3617        expressions = f" ({expressions})" if expressions else ""
    3618        options = self.expressions(expression, key="options", sep=" ")
    3619        options = f" {options}" if options else ""
    3620        return f"{kind}{this}{index_type}{expressions}{options}"
    3621
    3622    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3623        if self.NVL2_SUPPORTED:
    3624            return self.function_fallback_sql(expression)
    3625
    3626        case = exp.Case().when(
    3627            expression.this.is_(exp.null()).not_(copy=False),
    3628            expression.args["true"],
    3629            copy=False,
    3630        )
    3631        else_cond = expression.args.get("false")
    3632        if else_cond:
    3633            case.else_(else_cond, copy=False)
    3634
    3635        return self.sql(case)
    3636
    3637    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3638        this = self.sql(expression, "this")
    3639        expr = self.sql(expression, "expression")
    3640        iterator = self.sql(expression, "iterator")
    3641        condition = self.sql(expression, "condition")
    3642        condition = f" IF {condition}" if condition else ""
    3643        return f"{this} FOR {expr} IN {iterator}{condition}"
    3644
    3645    def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str:
    3646        return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})"
    3647
    3648    def opclass_sql(self, expression: exp.Opclass) -> str:
    3649        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
    3650
    3651    def predict_sql(self, expression: exp.Predict) -> str:
    3652        model = self.sql(expression, "this")
    3653        model = f"MODEL {model}"
    3654        table = self.sql(expression, "expression")
    3655        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    3656        parameters = self.sql(expression, "params_struct")
    3657        return self.func("PREDICT", model, table, parameters or None)
    3658
    3659    def forin_sql(self, expression: exp.ForIn) -> str:
    3660        this = self.sql(expression, "this")
    3661        expression_sql = self.sql(expression, "expression")
    3662        return f"FOR {this} DO {expression_sql}"
    3663
    3664    def refresh_sql(self, expression: exp.Refresh) -> str:
    3665        this = self.sql(expression, "this")
    3666        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    3667        return f"REFRESH {table}{this}"
    3668
    3669    def operator_sql(self, expression: exp.Operator) -> str:
    3670        return self.binary(expression, f"OPERATOR({self.sql(expression, 'operator')})")
    3671
    3672    def toarray_sql(self, expression: exp.ToArray) -> str:
    3673        arg = expression.this
    3674        if not arg.type:
    3675            from sqlglot.optimizer.annotate_types import annotate_types
    3676
    3677            arg = annotate_types(arg)
    3678
    3679        if arg.is_type(exp.DataType.Type.ARRAY):
    3680            return self.sql(arg)
    3681
    3682        cond_for_null = arg.is_(exp.null())
    3683        return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False)))
    3684
    3685    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    3686        this = expression.this
    3687        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    3688            return self.sql(this)
    3689
    3690        return self.sql(exp.cast(this, exp.DataType.Type.TIME))
    3691
    3692    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
    3693        this = expression.this
    3694        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
    3695            return self.sql(this)
    3696
    3697        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP))
    3698
    3699    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    3700        this = expression.this
    3701        time_format = self.format_time(expression)
    3702
    3703        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    3704            return self.sql(
    3705                exp.cast(
    3706                    exp.StrToTime(this=this, format=expression.args["format"]),
    3707                    exp.DataType.Type.DATE,
    3708                )
    3709            )
    3710
    3711        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    3712            return self.sql(this)
    3713
    3714        return self.sql(exp.cast(this, exp.DataType.Type.DATE))
    3715
    3716    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    3717        return self.sql(
    3718            exp.func(
    3719                "DATEDIFF",
    3720                expression.this,
    3721                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
    3722                "day",
    3723            )
    3724        )
    3725
    3726    def lastday_sql(self, expression: exp.LastDay) -> str:
    3727        if self.LAST_DAY_SUPPORTS_DATE_PART:
    3728            return self.function_fallback_sql(expression)
    3729
    3730        unit = expression.text("unit")
    3731        if unit and unit != "MONTH":
    3732            self.unsupported("Date parts are not supported in LAST_DAY.")
    3733
    3734        return self.func("LAST_DAY", expression.this)
    3735
    3736    def dateadd_sql(self, expression: exp.DateAdd) -> str:
    3737        from sqlglot.dialects.dialect import unit_to_str
    3738
    3739        return self.func(
    3740            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
    3741        )
    3742
    3743    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    3744        if self.CAN_IMPLEMENT_ARRAY_ANY:
    3745            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    3746            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    3747            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    3748            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    3749
    3750        from sqlglot.dialects import Dialect
    3751
    3752        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    3753        if self.dialect.__class__ != Dialect:
    3754            self.unsupported("ARRAY_ANY is unsupported")
    3755
    3756        return self.function_fallback_sql(expression)
    3757
    3758    def generateseries_sql(self, expression: exp.GenerateSeries) -> str:
    3759        expression.set("is_end_exclusive", None)
    3760        return self.function_fallback_sql(expression)
    3761
    3762    def struct_sql(self, expression: exp.Struct) -> str:
    3763        expression.set(
    3764            "expressions",
    3765            [
    3766                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    3767                if isinstance(e, exp.PropertyEQ)
    3768                else e
    3769                for e in expression.expressions
    3770            ],
    3771        )
    3772
    3773        return self.function_fallback_sql(expression)
    3774
    3775    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    3776        low = self.sql(expression, "this")
    3777        high = self.sql(expression, "expression")
    3778
    3779        return f"{low} TO {high}"
    3780
    3781    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    3782        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    3783        tables = f" {self.expressions(expression)}"
    3784
    3785        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3786
    3787        on_cluster = self.sql(expression, "cluster")
    3788        on_cluster = f" {on_cluster}" if on_cluster else ""
    3789
    3790        identity = self.sql(expression, "identity")
    3791        identity = f" {identity} IDENTITY" if identity else ""
    3792
    3793        option = self.sql(expression, "option")
    3794        option = f" {option}" if option else ""
    3795
    3796        partition = self.sql(expression, "partition")
    3797        partition = f" {partition}" if partition else ""
    3798
    3799        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"
    3800
    3801    # This transpiles T-SQL's CONVERT function
    3802    # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16
    3803    def convert_sql(self, expression: exp.Convert) -> str:
    3804        to = expression.this
    3805        value = expression.expression
    3806        style = expression.args.get("style")
    3807        safe = expression.args.get("safe")
    3808        strict = expression.args.get("strict")
    3809
    3810        if not to or not value:
    3811            return ""
    3812
    3813        # Retrieve length of datatype and override to default if not specified
    3814        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3815            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    3816
    3817        transformed: t.Optional[exp.Expression] = None
    3818        cast = exp.Cast if strict else exp.TryCast
    3819
    3820        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
    3821        if isinstance(style, exp.Literal) and style.is_int:
    3822            from sqlglot.dialects.tsql import TSQL
    3823
    3824            style_value = style.name
    3825            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
    3826            if not converted_style:
    3827                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
    3828
    3829            fmt = exp.Literal.string(converted_style)
    3830
    3831            if to.this == exp.DataType.Type.DATE:
    3832                transformed = exp.StrToDate(this=value, format=fmt)
    3833            elif to.this == exp.DataType.Type.DATETIME:
    3834                transformed = exp.StrToTime(this=value, format=fmt)
    3835            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3836                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
    3837            elif to.this == exp.DataType.Type.TEXT:
    3838                transformed = exp.TimeToStr(this=value, format=fmt)
    3839
    3840        if not transformed:
    3841            transformed = cast(this=value, to=to, safe=safe)
    3842
    3843        return self.sql(transformed)
    3844
    3845    def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str:
    3846        this = expression.this
    3847        if isinstance(this, exp.JSONPathWildcard):
    3848            this = self.json_path_part(this)
    3849            return f".{this}" if this else ""
    3850
    3851        if exp.SAFE_IDENTIFIER_RE.match(this):
    3852            return f".{this}"
    3853
    3854        this = self.json_path_part(this)
    3855        return f"[{this}]" if self.JSON_PATH_BRACKETED_KEY_SUPPORTED else f".{this}"
    3856
    3857    def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str:
    3858        this = self.json_path_part(expression.this)
    3859        return f"[{this}]" if this else ""
    3860
    3861    def _simplify_unless_literal(self, expression: E) -> E:
    3862        if not isinstance(expression, exp.Literal):
    3863            from sqlglot.optimizer.simplify import simplify
    3864
    3865            expression = simplify(expression, dialect=self.dialect)
    3866
    3867        return expression
    3868
    3869    def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str:
    3870        if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"):
    3871            # The first modifier here will be the one closest to the AggFunc's arg
    3872            mods = sorted(
    3873                expression.find_all(exp.HavingMax, exp.Order, exp.Limit),
    3874                key=lambda x: 0
    3875                if isinstance(x, exp.HavingMax)
    3876                else (1 if isinstance(x, exp.Order) else 2),
    3877            )
    3878
    3879            if mods:
    3880                mod = mods[0]
    3881                this = expression.__class__(this=mod.this.copy())
    3882                this.meta["inline"] = True
    3883                mod.this.replace(this)
    3884                return self.sql(expression.this)
    3885
    3886            agg_func = expression.find(exp.AggFunc)
    3887
    3888            if agg_func:
    3889                return self.sql(agg_func)[:-1] + f" {text})"
    3890
    3891        return f"{self.sql(expression, 'this')} {text}"
    3892
    3893    def _replace_line_breaks(self, string: str) -> str:
    3894        """We don't want to extra indent line breaks so we temporarily replace them with sentinels."""
    3895        if self.pretty:
    3896            return string.replace("\n", self.SENTINEL_LINE_BREAK)
    3897        return string
    3898
    3899    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
    3900        option = self.sql(expression, "this")
    3901
    3902        if expression.expressions:
    3903            upper = option.upper()
    3904
    3905            # Snowflake FILE_FORMAT options are separated by whitespace
    3906            sep = " " if upper == "FILE_FORMAT" else ", "
    3907
    3908            # Databricks copy/format options do not set their list of values with EQ
    3909            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
    3910            values = self.expressions(expression, flat=True, sep=sep)
    3911            return f"{option}{op}({values})"
    3912
    3913        value = self.sql(expression, "expression")
    3914
    3915        if not value:
    3916            return option
    3917
    3918        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
    3919
    3920        return f"{option}{op}{value}"
    3921
    3922    def credentials_sql(self, expression: exp.Credentials) -> str:
    3923        cred_expr = expression.args.get("credentials")
    3924        if isinstance(cred_expr, exp.Literal):
    3925            # Redshift case: CREDENTIALS <string>
    3926            credentials = self.sql(expression, "credentials")
    3927            credentials = f"CREDENTIALS {credentials}" if credentials else ""
    3928        else:
    3929            # Snowflake case: CREDENTIALS = (...)
    3930            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
    3931            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
    3932
    3933        storage = self.sql(expression, "storage")
    3934        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
    3935
    3936        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
    3937        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
    3938
    3939        iam_role = self.sql(expression, "iam_role")
    3940        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
    3941
    3942        region = self.sql(expression, "region")
    3943        region = f" REGION {region}" if region else ""
    3944
    3945        return f"{credentials}{storage}{encryption}{iam_role}{region}"
    3946
    3947    def copy_sql(self, expression: exp.Copy) -> str:
    3948        this = self.sql(expression, "this")
    3949        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
    3950
    3951        credentials = self.sql(expression, "credentials")
    3952        credentials = self.seg(credentials) if credentials else ""
    3953        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
    3954        files = self.expressions(expression, key="files", flat=True)
    3955
    3956        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
    3957        params = self.expressions(
    3958            expression,
    3959            key="params",
    3960            sep=sep,
    3961            new_line=True,
    3962            skip_last=True,
    3963            skip_first=True,
    3964            indent=self.COPY_PARAMS_ARE_WRAPPED,
    3965        )
    3966
    3967        if params:
    3968            if self.COPY_PARAMS_ARE_WRAPPED:
    3969                params = f" WITH ({params})"
    3970            elif not self.pretty:
    3971                params = f" {params}"
    3972
    3973        return f"COPY{this}{kind} {files}{credentials}{params}"
    3974
    3975    def semicolon_sql(self, expression: exp.Semicolon) -> str:
    3976        return ""
    3977
    3978    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
    3979        on_sql = "ON" if expression.args.get("on") else "OFF"
    3980        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
    3981        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
    3982        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    3983        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
    3984
    3985        if filter_col or retention_period:
    3986            on_sql = self.func("ON", filter_col, retention_period)
    3987
    3988        return f"DATA_DELETION={on_sql}"
    3989
    3990    def maskingpolicycolumnconstraint_sql(
    3991        self, expression: exp.MaskingPolicyColumnConstraint
    3992    ) -> str:
    3993        this = self.sql(expression, "this")
    3994        expressions = self.expressions(expression, flat=True)
    3995        expressions = f" USING ({expressions})" if expressions else ""
    3996        return f"MASKING POLICY {this}{expressions}"
    3997
    3998    def gapfill_sql(self, expression: exp.GapFill) -> str:
    3999        this = self.sql(expression, "this")
    4000        this = f"TABLE {this}"
    4001        return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"])
    4002
    4003    def scope_resolution(self, rhs: str, scope_name: str) -> str:
    4004        return self.func("SCOPE_RESOLUTION", scope_name or None, rhs)
    4005
    4006    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
    4007        this = self.sql(expression, "this")
    4008        expr = expression.expression
    4009
    4010        if isinstance(expr, exp.Func):
    4011            # T-SQL's CLR functions are case sensitive
    4012            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
    4013        else:
    4014            expr = self.sql(expression, "expression")
    4015
    4016        return self.scope_resolution(expr, this)
    4017
    4018    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
    4019        if self.PARSE_JSON_NAME is None:
    4020            return self.sql(expression.this)
    4021
    4022        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)
    4023
    4024    def length_sql(self, expression: exp.Length) -> str:
    4025        return self.func("LENGTH", expression.this)
    4026
    4027    def rand_sql(self, expression: exp.Rand) -> str:
    4028        lower = self.sql(expression, "lower")
    4029        upper = self.sql(expression, "upper")
    4030
    4031        if lower and upper:
    4032            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
    4033        return self.func("RAND", expression.this)
    4034
    4035    def strtodate_sql(self, expression: exp.StrToDate) -> str:
    4036        return self.func("STR_TO_DATE", expression.this, expression.args.get("format"))
    4037
    4038    def strtotime_sql(self, expression: exp.StrToTime) -> str:
    4039        return self.func(
    4040            "STR_TO_TIME",
    4041            expression.this,
    4042            expression.args.get("format"),
    4043            expression.args.get("zone"),
    4044        )
    4045
    4046    def changes_sql(self, expression: exp.Changes) -> str:
    4047        information = self.sql(expression, "information")
    4048        information = f"INFORMATION => {information}"
    4049        at_before = self.sql(expression, "at_before")
    4050        at_before = f"{self.seg('')}{at_before}" if at_before else ""
    4051        end = self.sql(expression, "end")
    4052        end = f"{self.seg('')}{end}" if end else ""
    4053
    4054        return f"CHANGES ({information}){at_before}{end}"
    4055
    4056    def pad_sql(self, expression: exp.Pad) -> str:
    4057        prefix = "L" if expression.args.get("is_left") else "R"
    4058
    4059        fill_pattern = self.sql(expression, "fill_pattern") or None
    4060        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
    4061            fill_pattern = "' '"
    4062
    4063        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.JSONPathKey'>, <class 'sqlglot.expressions.JSONPathWildcard'>, <class 'sqlglot.expressions.JSONPathFilter'>, <class 'sqlglot.expressions.JSONPathUnion'>, <class 'sqlglot.expressions.JSONPathSubscript'>, <class 'sqlglot.expressions.JSONPathSelector'>, <class 'sqlglot.expressions.JSONPathSlice'>, <class 'sqlglot.expressions.JSONPathScript'>, <class 'sqlglot.expressions.JSONPathRoot'>, <class 'sqlglot.expressions.JSONPathRecursive'>}
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.NVARCHAR: 'NVARCHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.CHAR: 'CHAR'>, <Type.VARCHAR: 'VARCHAR'>}
EXPRESSIONS_WITHOUT_NESTED_CTES: Set[Type[sqlglot.expressions.Expression]] = set()
SENTINEL_LINE_BREAK = '__SQLGLOT__LB__'
pretty
identify
normalize
pad
unsupported_level
max_unsupported
leading_comma
max_text_width
comments
dialect
normalize_functions
unsupported_messages: List[str]
def generate( self, expression: sqlglot.expressions.Expression, copy: bool = True) -> str: View Source

    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        return f"UNIQUE{this}{index_type}{on_conflict}"

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

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

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

     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        postcreate_props_sql = ""
    1031        if properties_locs.get(exp.Properties.Location.POST_CREATE):
    1032            postcreate_props_sql = self.properties(
    1033                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
    1034                sep=" ",
    1035                prefix=" ",
    1036                wrapped=False,
    1037            )
    1038
    1039        modifiers = "".join((replace, unique, postcreate_props_sql))
    1040
    1041        postexpression_props_sql = ""
    1042        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
    1043            postexpression_props_sql = self.properties(
    1044                exp.Properties(
    1045                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
    1046                ),
    1047                sep=" ",
    1048                prefix=" ",
    1049                wrapped=False,
    1050            )
    1051
    1052        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    1053        no_schema_binding = (
    1054            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
    1055        )
    1056
    1057        clone = self.sql(expression, "clone")
    1058        clone = f" {clone}" if clone else ""
    1059
    1060        expression_sql = f"CREATE{modifiers} {kind}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
    1061        return self.prepend_ctes(expression, expression_sql)

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

    1063    def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str:
    1064        start = self.sql(expression, "start")
    1065        start = f"START WITH {start}" if start else ""
    1066        increment = self.sql(expression, "increment")
    1067        increment = f" INCREMENT BY {increment}" if increment else ""
    1068        minvalue = self.sql(expression, "minvalue")
    1069        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    1070        maxvalue = self.sql(expression, "maxvalue")
    1071        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    1072        owned = self.sql(expression, "owned")
    1073        owned = f" OWNED BY {owned}" if owned else ""
    1074
    1075        cache = expression.args.get("cache")
    1076        if cache is None:
    1077            cache_str = ""
    1078        elif cache is True:
    1079            cache_str = " CACHE"
    1080        else:
    1081            cache_str = f" CACHE {cache}"
    1082
    1083        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1084        options = f" {options}" if options else ""
    1085
    1086        return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()

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

    1088    def clone_sql(self, expression: exp.Clone) -> str:
    1089        this = self.sql(expression, "this")
    1090        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    1091        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
    1092        return f"{shallow}{keyword} {this}"

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

    1094    def describe_sql(self, expression: exp.Describe) -> str:
    1095        style = expression.args.get("style")
    1096        style = f" {style}" if style else ""
    1097        return f"DESCRIBE{style} {self.sql(expression, 'this')}"

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

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

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

    1103    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    1104        with_ = self.sql(expression, "with")
    1105        if with_:
    1106            sql = f"{with_}{self.sep()}{sql}"
    1107        return sql

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

    1109    def with_sql(self, expression: exp.With) -> str:
    1110        sql = self.expressions(expression, flat=True)
    1111        recursive = (
    1112            "RECURSIVE "
    1113            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
    1114            else ""
    1115        )
    1116
    1117        return f"WITH {recursive}{sql}"

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

    1119    def cte_sql(self, expression: exp.CTE) -> str:
    1120        alias = self.sql(expression, "alias")
    1121
    1122        materialized = expression.args.get("materialized")
    1123        if materialized is False:
    1124            materialized = "NOT MATERIALIZED "
    1125        elif materialized:
    1126            materialized = "MATERIALIZED "
    1127
    1128        return f"{alias} AS {materialized or ''}{self.wrap(expression)}"

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

    1130    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    1131        alias = self.sql(expression, "this")
    1132        columns = self.expressions(expression, key="columns", flat=True)
    1133        columns = f"({columns})" if columns else ""
    1134
    1135        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
    1136            columns = ""
    1137            self.unsupported("Named columns are not supported in table alias.")
    1138
    1139        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
    1140            alias = self._next_name()
    1141
    1142        return f"{alias}{columns}"

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

    1144    def bitstring_sql(self, expression: exp.BitString) -> str:
    1145        this = self.sql(expression, "this")
    1146        if self.dialect.BIT_START:
    1147            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    1148        return f"{int(this, 2)}"

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

    1150    def hexstring_sql(self, expression: exp.HexString) -> str:
    1151        this = self.sql(expression, "this")
    1152        if self.dialect.HEX_START:
    1153            return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
    1154        return f"{int(this, 16)}"

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

    1156    def bytestring_sql(self, expression: exp.ByteString) -> str:
    1157        this = self.sql(expression, "this")
    1158        if self.dialect.BYTE_START:
    1159            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    1160        return this

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

    1162    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
    1163        this = self.sql(expression, "this")
    1164        escape = expression.args.get("escape")
    1165
    1166        if self.dialect.UNICODE_START:
    1167            escape_substitute = r"\\\1"
    1168            left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END
    1169        else:
    1170            escape_substitute = r"\\u\1"
    1171            left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END
    1172
    1173        if escape:
    1174            escape_pattern = re.compile(rf"{escape.name}(\d+)")
    1175            escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else ""
    1176        else:
    1177            escape_pattern = ESCAPED_UNICODE_RE
    1178            escape_sql = ""
    1179
    1180        if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE):
    1181            this = escape_pattern.sub(escape_substitute, this)
    1182
    1183        return f"{left_quote}{this}{right_quote}{escape_sql}"

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

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

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

    1189    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    1190        this = self.sql(expression, "this")
    1191        specifier = self.sql(expression, "expression")
    1192        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    1193        return f"{this}{specifier}"

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

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

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

    1232    def directory_sql(self, expression: exp.Directory) -> str:
    1233        local = "LOCAL " if expression.args.get("local") else ""
    1234        row_format = self.sql(expression, "row_format")
    1235        row_format = f" {row_format}" if row_format else ""
    1236        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

    1238    def delete_sql(self, expression: exp.Delete) -> str:
    1239        this = self.sql(expression, "this")
    1240        this = f" FROM {this}" if this else ""
    1241        using = self.sql(expression, "using")
    1242        using = f" USING {using}" if using else ""
    1243        where = self.sql(expression, "where")
    1244        returning = self.sql(expression, "returning")
    1245        limit = self.sql(expression, "limit")
    1246        tables = self.expressions(expression, key="tables")
    1247        tables = f" {tables}" if tables else ""
    1248        if self.RETURNING_END:
    1249            expression_sql = f"{this}{using}{where}{returning}{limit}"
    1250        else:
    1251            expression_sql = f"{returning}{this}{using}{where}{limit}"
    1252        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

    1254    def drop_sql(self, expression: exp.Drop) -> str:
    1255        this = self.sql(expression, "this")
    1256        expressions = self.expressions(expression, flat=True)
    1257        expressions = f" ({expressions})" if expressions else ""
    1258        kind = expression.args["kind"]
    1259        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    1260        on_cluster = self.sql(expression, "cluster")
    1261        on_cluster = f" {on_cluster}" if on_cluster else ""
    1262        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1263        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    1264        cascade = " CASCADE" if expression.args.get("cascade") else ""
    1265        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    1266        purge = " PURGE" if expression.args.get("purge") else ""
    1267        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

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

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

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

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

    1275    def fetch_sql(self, expression: exp.Fetch) -> str:
    1276        direction = expression.args.get("direction")
    1277        direction = f" {direction}" if direction else ""
    1278        count = expression.args.get("count")
    1279        count = f" {count}" if count else ""
    1280        if expression.args.get("percent"):
    1281            count = f"{count} PERCENT"
    1282        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    1283        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"

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

    1285    def filter_sql(self, expression: exp.Filter) -> str:
    1286        if self.AGGREGATE_FILTER_SUPPORTED:
    1287            this = self.sql(expression, "this")
    1288            where = self.sql(expression, "expression").strip()
    1289            return f"{this} FILTER({where})"
    1290
    1291        agg = expression.this
    1292        agg_arg = agg.this
    1293        cond = expression.expression.this
    1294        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1295        return self.sql(agg)

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

    1297    def hint_sql(self, expression: exp.Hint) -> str:
    1298        if not self.QUERY_HINTS:
    1299            self.unsupported("Hints are not supported")
    1300            return ""
    1301
    1302        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

    1304    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
    1305        using = self.sql(expression, "using")
    1306        using = f" USING {using}" if using else ""
    1307        columns = self.expressions(expression, key="columns", flat=True)
    1308        columns = f"({columns})" if columns else ""
    1309        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1310        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1311        where = self.sql(expression, "where")
    1312        include = self.expressions(expression, key="include", flat=True)
    1313        if include:
    1314            include = f" INCLUDE ({include})"
    1315        with_storage = self.expressions(expression, key="with_storage", flat=True)
    1316        with_storage = f" WITH ({with_storage})" if with_storage else ""
    1317        tablespace = self.sql(expression, "tablespace")
    1318        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
    1319        on = self.sql(expression, "on")
    1320        on = f" ON {on}" if on else ""
    1321
    1322        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"

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

    1324    def index_sql(self, expression: exp.Index) -> str:
    1325        unique = "UNIQUE " if expression.args.get("unique") else ""
    1326        primary = "PRIMARY " if expression.args.get("primary") else ""
    1327        amp = "AMP " if expression.args.get("amp") else ""
    1328        name = self.sql(expression, "this")
    1329        name = f"{name} " if name else ""
    1330        table = self.sql(expression, "table")
    1331        table = f"{self.INDEX_ON} {table}" if table else ""
    1332
    1333        index = "INDEX " if not table else ""
    1334
    1335        params = self.sql(expression, "params")
    1336        return f"{unique}{primary}{amp}{index}{name}{table}{params}"

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

    1338    def identifier_sql(self, expression: exp.Identifier) -> str:
    1339        text = expression.name
    1340        lower = text.lower()
    1341        text = lower if self.normalize and not expression.quoted else text
    1342        text = text.replace(self.dialect.IDENTIFIER_END, self._escaped_identifier_end)
    1343        if (
    1344            expression.quoted
    1345            or self.dialect.can_identify(text, self.identify)
    1346            or lower in self.RESERVED_KEYWORDS
    1347            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1348        ):
    1349            text = f"{self.dialect.IDENTIFIER_START}{text}{self.dialect.IDENTIFIER_END}"
    1350        return text

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

    1352    def hex_sql(self, expression: exp.Hex) -> str:
    1353        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1354        if self.dialect.HEX_LOWERCASE:
    1355            text = self.func("LOWER", text)
    1356
    1357        return text

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

    1359    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
    1360        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1361        if not self.dialect.HEX_LOWERCASE:
    1362            text = self.func("LOWER", text)
    1363        return text

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

    1365    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1366        input_format = self.sql(expression, "input_format")
    1367        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1368        output_format = self.sql(expression, "output_format")
    1369        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1370        return self.sep().join((input_format, output_format))

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

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

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

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

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

    1379    def properties_sql(self, expression: exp.Properties) -> str:
    1380        root_properties = []
    1381        with_properties = []
    1382
    1383        for p in expression.expressions:
    1384            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1385            if p_loc == exp.Properties.Location.POST_WITH:
    1386                with_properties.append(p)
    1387            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1388                root_properties.append(p)
    1389
    1390        root_props = self.root_properties(exp.Properties(expressions=root_properties))
    1391        with_props = self.with_properties(exp.Properties(expressions=with_properties))
    1392
    1393        if root_props and with_props and not self.pretty:
    1394            with_props = " " + with_props
    1395
    1396        return root_props + with_props

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

    1398    def root_properties(self, properties: exp.Properties) -> str:
    1399        if properties.expressions:
    1400            return self.expressions(properties, indent=False, sep=" ")
    1401        return ""

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

    1403    def properties(
    1404        self,
    1405        properties: exp.Properties,
    1406        prefix: str = "",
    1407        sep: str = ", ",
    1408        suffix: str = "",
    1409        wrapped: bool = True,
    1410    ) -> str:
    1411        if properties.expressions:
    1412            expressions = self.expressions(properties, sep=sep, indent=False)
    1413            if expressions:
    1414                expressions = self.wrap(expressions) if wrapped else expressions
    1415                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1416        return ""

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

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

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

    1421    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1422        properties_locs = defaultdict(list)
    1423        for p in properties.expressions:
    1424            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1425            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1426                properties_locs[p_loc].append(p)
    1427            else:
    1428                self.unsupported(f"Unsupported property {p.key}")
    1429
    1430        return properties_locs

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

    1432    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1433        if isinstance(expression.this, exp.Dot):
    1434            return self.sql(expression, "this")
    1435        return f"'{expression.name}'" if string_key else expression.name

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

    1437    def property_sql(self, expression: exp.Property) -> str:
    1438        property_cls = expression.__class__
    1439        if property_cls == exp.Property:
    1440            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1441
    1442        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1443        if not property_name:
    1444            self.unsupported(f"Unsupported property {expression.key}")
    1445
    1446        return f"{property_name}={self.sql(expression, 'this')}"

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

    1448    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1449        if self.SUPPORTS_CREATE_TABLE_LIKE:
    1450            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1451            options = f" {options}" if options else ""
    1452
    1453            like = f"LIKE {self.sql(expression, 'this')}{options}"
    1454            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
    1455                like = f"({like})"
    1456
    1457            return like
    1458
    1459        if expression.expressions:
    1460            self.unsupported("Transpilation of LIKE property options is unsupported")
    1461
    1462        select = exp.select("*").from_(expression.this).limit(0)
    1463        return f"AS {self.sql(select)}"

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

    1465    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1466        no = "NO " if expression.args.get("no") else ""
    1467        protection = " PROTECTION" if expression.args.get("protection") else ""
    1468        return f"{no}FALLBACK{protection}"

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

    1470    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1471        no = "NO " if expression.args.get("no") else ""
    1472        local = expression.args.get("local")
    1473        local = f"{local} " if local else ""
    1474        dual = "DUAL " if expression.args.get("dual") else ""
    1475        before = "BEFORE " if expression.args.get("before") else ""
    1476        after = "AFTER " if expression.args.get("after") else ""
    1477        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1479    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1480        freespace = self.sql(expression, "this")
    1481        percent = " PERCENT" if expression.args.get("percent") else ""
    1482        return f"FREESPACE={freespace}{percent}"

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

    1484    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1485        if expression.args.get("default"):
    1486            property = "DEFAULT"
    1487        elif expression.args.get("on"):
    1488            property = "ON"
    1489        else:
    1490            property = "OFF"
    1491        return f"CHECKSUM={property}"

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

    1493    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1494        if expression.args.get("no"):
    1495            return "NO MERGEBLOCKRATIO"
    1496        if expression.args.get("default"):
    1497            return "DEFAULT MERGEBLOCKRATIO"
    1498
    1499        percent = " PERCENT" if expression.args.get("percent") else ""
    1500        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1502    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1503        default = expression.args.get("default")
    1504        minimum = expression.args.get("minimum")
    1505        maximum = expression.args.get("maximum")
    1506        if default or minimum or maximum:
    1507            if default:
    1508                prop = "DEFAULT"
    1509            elif minimum:
    1510                prop = "MINIMUM"
    1511            else:
    1512                prop = "MAXIMUM"
    1513            return f"{prop} DATABLOCKSIZE"
    1514        units = expression.args.get("units")
    1515        units = f" {units}" if units else ""
    1516        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1518    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1519        autotemp = expression.args.get("autotemp")
    1520        always = expression.args.get("always")
    1521        default = expression.args.get("default")
    1522        manual = expression.args.get("manual")
    1523        never = expression.args.get("never")
    1524
    1525        if autotemp is not None:
    1526            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1527        elif always:
    1528            prop = "ALWAYS"
    1529        elif default:
    1530            prop = "DEFAULT"
    1531        elif manual:
    1532            prop = "MANUAL"
    1533        elif never:
    1534            prop = "NEVER"
    1535        return f"BLOCKCOMPRESSION={prop}"

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

    1537    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1538        no = expression.args.get("no")
    1539        no = " NO" if no else ""
    1540        concurrent = expression.args.get("concurrent")
    1541        concurrent = " CONCURRENT" if concurrent else ""
    1542        target = self.sql(expression, "target")
    1543        target = f" {target}" if target else ""
    1544        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"

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

    1546    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1547        if isinstance(expression.this, list):
    1548            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1549        if expression.this:
    1550            modulus = self.sql(expression, "this")
    1551            remainder = self.sql(expression, "expression")
    1552            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1553
    1554        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1555        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1556        return f"FROM ({from_expressions}) TO ({to_expressions})"

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

    1558    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1559        this = self.sql(expression, "this")
    1560
    1561        for_values_or_default = expression.expression
    1562        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1563            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1564        else:
    1565            for_values_or_default = " DEFAULT"
    1566
    1567        return f"PARTITION OF {this}{for_values_or_default}"

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

    1569    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1570        kind = expression.args.get("kind")
    1571        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1572        for_or_in = expression.args.get("for_or_in")
    1573        for_or_in = f" {for_or_in}" if for_or_in else ""
    1574        lock_type = expression.args.get("lock_type")
    1575        override = " OVERRIDE" if expression.args.get("override") else ""
    1576        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"

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

    1578    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1579        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1580        statistics = expression.args.get("statistics")
    1581        statistics_sql = ""
    1582        if statistics is not None:
    1583            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1584        return f"{data_sql}{statistics_sql}"

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

    1586    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1587        this = self.sql(expression, "this")
    1588        this = f"HISTORY_TABLE={this}" if this else ""
    1589        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
    1590        data_consistency = (
    1591            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
    1592        )
    1593        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    1594        retention_period = (
    1595            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
    1596        )
    1597
    1598        if this:
    1599            on_sql = self.func("ON", this, data_consistency, retention_period)
    1600        else:
    1601            on_sql = "ON" if expression.args.get("on") else "OFF"
    1602
    1603        sql = f"SYSTEM_VERSIONING={on_sql}"
    1604
    1605        return f"WITH({sql})" if expression.args.get("with") else sql

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

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

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

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

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

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

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

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

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

    1652    def kill_sql(self, expression: exp.Kill) -> str:
    1653        kind = self.sql(expression, "kind")
    1654        kind = f" {kind}" if kind else ""
    1655        this = self.sql(expression, "this")
    1656        this = f" {this}" if this else ""
    1657        return f"KILL{kind}{this}"

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

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

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

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

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

    1665    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1666        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1667
    1668        constraint = self.sql(expression, "constraint")
    1669        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
    1670
    1671        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
    1672        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
    1673        action = self.sql(expression, "action")
    1674
    1675        expressions = self.expressions(expression, flat=True)
    1676        if expressions:
    1677            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1678            expressions = f" {set_keyword}{expressions}"
    1679
    1680        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}"

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

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

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

    1685    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1686        fields = self.sql(expression, "fields")
    1687        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1688        escaped = self.sql(expression, "escaped")
    1689        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1690        items = self.sql(expression, "collection_items")
    1691        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1692        keys = self.sql(expression, "map_keys")
    1693        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1694        lines = self.sql(expression, "lines")
    1695        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1696        null = self.sql(expression, "null")
    1697        null = f" NULL DEFINED AS {null}" if null else ""
    1698        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1703    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1704        this = f"{self.sql(expression, 'this')} INDEX"
    1705        target = self.sql(expression, "target")
    1706        target = f" FOR {target}" if target else ""
    1707        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1709    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1710        this = self.sql(expression, "this")
    1711        kind = self.sql(expression, "kind")
    1712        expr = self.sql(expression, "expression")
    1713        return f"{this} ({kind} => {expr})"

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

    1715    def table_parts(self, expression: exp.Table) -> str:
    1716        return ".".join(
    1717            self.sql(part)
    1718            for part in (
    1719                expression.args.get("catalog"),
    1720                expression.args.get("db"),
    1721                expression.args.get("this"),
    1722            )
    1723            if part is not None
    1724        )

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

    1726    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1727        table = self.table_parts(expression)
    1728        only = "ONLY " if expression.args.get("only") else ""
    1729        partition = self.sql(expression, "partition")
    1730        partition = f" {partition}" if partition else ""
    1731        version = self.sql(expression, "version")
    1732        version = f" {version}" if version else ""
    1733        alias = self.sql(expression, "alias")
    1734        alias = f"{sep}{alias}" if alias else ""
    1735        hints = self.expressions(expression, key="hints", sep=" ")
    1736        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1737        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1738        pivots = f" {pivots}" if pivots else ""
    1739        joins = self.indent(
    1740            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    1741        )
    1742        laterals = self.expressions(expression, key="laterals", sep="")
    1743
    1744        file_format = self.sql(expression, "format")
    1745        if file_format:
    1746            pattern = self.sql(expression, "pattern")
    1747            pattern = f", PATTERN => {pattern}" if pattern else ""
    1748            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    1749
    1750        ordinality = expression.args.get("ordinality") or ""
    1751        if ordinality:
    1752            ordinality = f" WITH ORDINALITY{alias}"
    1753            alias = ""
    1754
    1755        when = self.sql(expression, "when")
    1756        if when:
    1757            table = f"{table} {when}"
    1758
    1759        changes = self.sql(expression, "changes")
    1760        changes = f" {changes}" if changes else ""
    1761
    1762        rows_from = self.expressions(expression, key="rows_from")
    1763        if rows_from:
    1764            table = f"ROWS FROM {self.wrap(rows_from)}"
    1765
    1766        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

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

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

    1809    def pivot_sql(self, expression: exp.Pivot) -> str:
    1810        expressions = self.expressions(expression, flat=True)
    1811
    1812        if expression.this:
    1813            this = self.sql(expression, "this")
    1814            if not expressions:
    1815                return f"UNPIVOT {this}"
    1816
    1817            on = f"{self.seg('ON')} {expressions}"
    1818            using = self.expressions(expression, key="using", flat=True)
    1819            using = f"{self.seg('USING')} {using}" if using else ""
    1820            group = self.sql(expression, "group")
    1821            return f"PIVOT {this}{on}{using}{group}"
    1822
    1823        alias = self.sql(expression, "alias")
    1824        alias = f" AS {alias}" if alias else ""
    1825        direction = "UNPIVOT" if expression.unpivot else "PIVOT"
    1826        field = self.sql(expression, "field")
    1827        include_nulls = expression.args.get("include_nulls")
    1828        if include_nulls is not None:
    1829            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    1830        else:
    1831            nulls = ""
    1832        return f"{direction}{nulls}({expressions} FOR {field}){alias}"

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

    1834    def version_sql(self, expression: exp.Version) -> str:
    1835        this = f"FOR {expression.name}"
    1836        kind = expression.text("kind")
    1837        expr = self.sql(expression, "expression")
    1838        return f"{this} {kind} {expr}"

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

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

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

    1843    def update_sql(self, expression: exp.Update) -> str:
    1844        this = self.sql(expression, "this")
    1845        set_sql = self.expressions(expression, flat=True)
    1846        from_sql = self.sql(expression, "from")
    1847        where_sql = self.sql(expression, "where")
    1848        returning = self.sql(expression, "returning")
    1849        order = self.sql(expression, "order")
    1850        limit = self.sql(expression, "limit")
    1851        if self.RETURNING_END:
    1852            expression_sql = f"{from_sql}{where_sql}{returning}"
    1853        else:
    1854            expression_sql = f"{returning}{from_sql}{where_sql}"
    1855        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    1856        return self.prepend_ctes(expression, sql)

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

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

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

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

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

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

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

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

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

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

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

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

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

    1958    def connect_sql(self, expression: exp.Connect) -> str:
    1959        start = self.sql(expression, "start")
    1960        start = self.seg(f"START WITH {start}") if start else ""
    1961        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
    1962        connect = self.sql(expression, "connect")
    1963        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
    1964        return start + connect

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

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

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

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

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

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

    2020    def lateral_op(self, expression: exp.Lateral) -> str:
    2021        cross_apply = expression.args.get("cross_apply")
    2022
    2023        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    2024        if cross_apply is True:
    2025            op = "INNER JOIN "
    2026        elif cross_apply is False:
    2027            op = "LEFT JOIN "
    2028        else:
    2029            op = ""
    2030
    2031        return f"{op}LATERAL"

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

    2033    def lateral_sql(self, expression: exp.Lateral) -> str:
    2034        this = self.sql(expression, "this")
    2035
    2036        if expression.args.get("view"):
    2037            alias = expression.args["alias"]
    2038            columns = self.expressions(alias, key="columns", flat=True)
    2039            table = f" {alias.name}" if alias.name else ""
    2040            columns = f" AS {columns}" if columns else ""
    2041            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    2042            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    2043
    2044        alias = self.sql(expression, "alias")
    2045        alias = f" AS {alias}" if alias else ""
    2046        return f"{self.lateral_op(expression)} {this}{alias}"

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

    2048    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    2049        this = self.sql(expression, "this")
    2050
    2051        args = [
    2052            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    2053            for e in (expression.args.get(k) for k in ("offset", "expression"))
    2054            if e
    2055        ]
    2056
    2057        args_sql = ", ".join(self.sql(e) for e in args)
    2058        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
    2059        expressions = self.expressions(expression, flat=True)
    2060        expressions = f" BY {expressions}" if expressions else ""
    2061
    2062        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}"

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

    2064    def offset_sql(self, expression: exp.Offset) -> str:
    2065        this = self.sql(expression, "this")
    2066        value = expression.expression
    2067        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    2068        expressions = self.expressions(expression, flat=True)
    2069        expressions = f" BY {expressions}" if expressions else ""
    2070        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"

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

    2072    def setitem_sql(self, expression: exp.SetItem) -> str:
    2073        kind = self.sql(expression, "kind")
    2074        kind = f"{kind} " if kind else ""
    2075        this = self.sql(expression, "this")
    2076        expressions = self.expressions(expression)
    2077        collate = self.sql(expression, "collate")
    2078        collate = f" COLLATE {collate}" if collate else ""
    2079        global_ = "GLOBAL " if expression.args.get("global") else ""
    2080        return f"{global_}{kind}{this}{expressions}{collate}"

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

    2082    def set_sql(self, expression: exp.Set) -> str:
    2083        expressions = (
    2084            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    2085        )
    2086        tag = " TAG" if expression.args.get("tag") else ""
    2087        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"

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

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

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

    2092    def lock_sql(self, expression: exp.Lock) -> str:
    2093        if not self.LOCKING_READS_SUPPORTED:
    2094            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    2095            return ""
    2096
    2097        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    2098        expressions = self.expressions(expression, flat=True)
    2099        expressions = f" OF {expressions}" if expressions else ""
    2100        wait = expression.args.get("wait")
    2101
    2102        if wait is not None:
    2103            if isinstance(wait, exp.Literal):
    2104                wait = f" WAIT {self.sql(wait)}"
    2105            else:
    2106                wait = " NOWAIT" if wait else " SKIP LOCKED"
    2107
    2108        return f"{lock_type}{expressions}{wait or ''}"

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

    2110    def literal_sql(self, expression: exp.Literal) -> str:
    2111        text = expression.this or ""
    2112        if expression.is_string:
    2113            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    2114        return text

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

    2116    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
    2117        if self.dialect.ESCAPED_SEQUENCES:
    2118            to_escaped = self.dialect.ESCAPED_SEQUENCES
    2119            text = "".join(
    2120                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
    2121            )
    2122
    2123        return self._replace_line_breaks(text).replace(
    2124            self.dialect.QUOTE_END, self._escaped_quote_end
    2125        )

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

    2127    def loaddata_sql(self, expression: exp.LoadData) -> str:
    2128        local = " LOCAL" if expression.args.get("local") else ""
    2129        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    2130        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    2131        this = f" INTO TABLE {self.sql(expression, 'this')}"
    2132        partition = self.sql(expression, "partition")
    2133        partition = f" {partition}" if partition else ""
    2134        input_format = self.sql(expression, "input_format")
    2135        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    2136        serde = self.sql(expression, "serde")
    2137        serde = f" SERDE {serde}" if serde else ""
    2138        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    2140    def null_sql(self, *_) -> str:
    2141        return "NULL"

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

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

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

    2146    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2147        this = self.sql(expression, "this")
    2148        this = f"{this} " if this else this
    2149        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2150        order = self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat)  # type: ignore
    2151        interpolated_values = [
    2152            f"{self.sql(named_expression, 'alias')} AS {self.sql(named_expression, 'this')}"
    2153            for named_expression in expression.args.get("interpolate") or []
    2154        ]
    2155        interpolate = (
    2156            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    2157        )
    2158        return f"{order}{interpolate}"

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

    2160    def withfill_sql(self, expression: exp.WithFill) -> str:
    2161        from_sql = self.sql(expression, "from")
    2162        from_sql = f" FROM {from_sql}" if from_sql else ""
    2163        to_sql = self.sql(expression, "to")
    2164        to_sql = f" TO {to_sql}" if to_sql else ""
    2165        step_sql = self.sql(expression, "step")
    2166        step_sql = f" STEP {step_sql}" if step_sql else ""
    2167        return f"WITH FILL{from_sql}{to_sql}{step_sql}"

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

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

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

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

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

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

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

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

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

    2226    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
    2227        window_frame = self.sql(expression, "window_frame")
    2228        window_frame = f"{window_frame} " if window_frame else ""
    2229
    2230        this = self.sql(expression, "this")
    2231
    2232        return f"{window_frame}{this}"

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

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

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

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

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

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

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

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

    2299    def offset_limit_modifiers(
    2300        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2301    ) -> t.List[str]:
    2302        return [
    2303            self.sql(expression, "offset") if fetch else self.sql(limit),
    2304            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2305        ]

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

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

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

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

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

    2376    def schema_sql(self, expression: exp.Schema) -> str:
    2377        this = self.sql(expression, "this")
    2378        sql = self.schema_columns_sql(expression)
    2379        return f"{this} {sql}" if this and sql else this or sql

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

    2381    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2382        if expression.expressions:
    2383            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2384        return ""

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

    2386    def star_sql(self, expression: exp.Star) -> str:
    2387        except_ = self.expressions(expression, key="except", flat=True)
    2388        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
    2389        replace = self.expressions(expression, key="replace", flat=True)
    2390        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
    2391        rename = self.expressions(expression, key="rename", flat=True)
    2392        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
    2393        return f"*{except_}{replace}{rename}"

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

    2395    def parameter_sql(self, expression: exp.Parameter) -> str:
    2396        this = self.sql(expression, "this")
    2397        return f"{self.PARAMETER_TOKEN}{this}"

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

    2399    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2400        this = self.sql(expression, "this")
    2401        kind = expression.text("kind")
    2402        if kind:
    2403            kind = f"{kind}."
    2404        return f"@@{kind}{this}"

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

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

    2409    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2410        alias = self.sql(expression, "alias")
    2411        alias = f"{sep}{alias}" if alias else ""
    2412
    2413        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    2414        pivots = f" {pivots}" if pivots else ""
    2415
    2416        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2417        return self.prepend_ctes(expression, sql)

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

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

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

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

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

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

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

    2463    def union_op(self, expression: exp.SetOperation) -> str:
    2464        kind = " DISTINCT" if self.EXPLICIT_SET_OP else ""
    2465        kind = kind if expression.args.get("distinct") else " ALL"
    2466        by_name = " BY NAME" if expression.args.get("by_name") else ""
    2467        return f"UNION{kind}{by_name}"

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

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

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

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

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

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

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

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

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

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

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

    2532    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2533        kind = self.sql(expression, "kind")
    2534        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2535        end = (
    2536            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2537            or "CURRENT ROW"
    2538        )
    2539        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    2546    def between_sql(self, expression: exp.Between) -> str:
    2547        this = self.sql(expression, "this")
    2548        low = self.sql(expression, "low")
    2549        high = self.sql(expression, "high")
    2550        return f"{this} BETWEEN {low} AND {high}"

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

    2552    def bracket_offset_expressions(self, expression: exp.Bracket) -> t.List[exp.Expression]:
    2553        return apply_index_offset(
    2554            expression.this,
    2555            expression.expressions,
    2556            self.dialect.INDEX_OFFSET - expression.args.get("offset", 0),
    2557        )

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

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

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

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

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

    2567    def any_sql(self, expression: exp.Any) -> str:
    2568        this = self.sql(expression, "this")
    2569        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
    2570            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2571                this = self.wrap(this)
    2572            return f"ANY{this}"
    2573        return f"ANY {this}"

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

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

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

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

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

    2598    def constraint_sql(self, expression: exp.Constraint) -> str:
    2599        this = self.sql(expression, "this")
    2600        expressions = self.expressions(expression, flat=True)
    2601        return f"CONSTRAINT {this} {expressions}"

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

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

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

    2608    def extract_sql(self, expression: exp.Extract) -> str:
    2609        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2610        expression_sql = self.sql(expression, "expression")
    2611        return f"EXTRACT({this} FROM {expression_sql})"

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

    2613    def trim_sql(self, expression: exp.Trim) -> str:
    2614        trim_type = self.sql(expression, "position")
    2615
    2616        if trim_type == "LEADING":
    2617            return self.func("LTRIM", expression.this)
    2618        elif trim_type == "TRAILING":
    2619            return self.func("RTRIM", expression.this)
    2620        else:
    2621            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

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

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

    2636    def concat_sql(self, expression: exp.Concat) -> str:
    2637        expressions = self.convert_concat_args(expression)
    2638
    2639        # Some dialects don't allow a single-argument CONCAT call
    2640        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2641            return self.sql(expressions[0])
    2642
    2643        return self.func("CONCAT", *expressions)

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

    2645    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2646        return self.func(
    2647            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2648        )

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

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

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

    2654    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2655        expressions = self.expressions(expression, flat=True)
    2656        reference = self.sql(expression, "reference")
    2657        reference = f" {reference}" if reference else ""
    2658        delete = self.sql(expression, "delete")
    2659        delete = f" ON DELETE {delete}" if delete else ""
    2660        update = self.sql(expression, "update")
    2661        update = f" ON UPDATE {update}" if update else ""
    2662        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"

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

    2664    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2665        expressions = self.expressions(expression, flat=True)
    2666        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2667        options = f" {options}" if options else ""
    2668        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

    2681    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
    2682        path = self.expressions(expression, sep="", flat=True).lstrip(".")
    2683        if self.QUOTE_JSON_PATH:
    2684            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
    2685
    2686        return path

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

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

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

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

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

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

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

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

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

    2736    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2737        null_handling = expression.args.get("null_handling")
    2738        null_handling = f" {null_handling}" if null_handling else ""
    2739        return_type = self.sql(expression, "return_type")
    2740        return_type = f" RETURNING {return_type}" if return_type else ""
    2741        strict = " STRICT" if expression.args.get("strict") else ""
    2742        return self.func(
    2743            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2744        )

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

    2746    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2747        this = self.sql(expression, "this")
    2748        order = self.sql(expression, "order")
    2749        null_handling = expression.args.get("null_handling")
    2750        null_handling = f" {null_handling}" if null_handling else ""
    2751        return_type = self.sql(expression, "return_type")
    2752        return_type = f" RETURNING {return_type}" if return_type else ""
    2753        strict = " STRICT" if expression.args.get("strict") else ""
    2754        return self.func(
    2755            "JSON_ARRAYAGG",
    2756            this,
    2757            suffix=f"{order}{null_handling}{return_type}{strict})",
    2758        )

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

    2760    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2761        path = self.sql(expression, "path")
    2762        path = f" PATH {path}" if path else ""
    2763        nested_schema = self.sql(expression, "nested_schema")
    2764
    2765        if nested_schema:
    2766            return f"NESTED{path} {nested_schema}"
    2767
    2768        this = self.sql(expression, "this")
    2769        kind = self.sql(expression, "kind")
    2770        kind = f" {kind}" if kind else ""
    2771        return f"{this}{kind}{path}"

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

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

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

    2776    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    2777        this = self.sql(expression, "this")
    2778        path = self.sql(expression, "path")
    2779        path = f", {path}" if path else ""
    2780        error_handling = expression.args.get("error_handling")
    2781        error_handling = f" {error_handling}" if error_handling else ""
    2782        empty_handling = expression.args.get("empty_handling")
    2783        empty_handling = f" {empty_handling}" if empty_handling else ""
    2784        schema = self.sql(expression, "schema")
    2785        return self.func(
    2786            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    2787        )

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

    2789    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    2790        this = self.sql(expression, "this")
    2791        kind = self.sql(expression, "kind")
    2792        path = self.sql(expression, "path")
    2793        path = f" {path}" if path else ""
    2794        as_json = " AS JSON" if expression.args.get("as_json") else ""
    2795        return f"{this} {kind}{path}{as_json}"

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

    2797    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    2798        this = self.sql(expression, "this")
    2799        path = self.sql(expression, "path")
    2800        path = f", {path}" if path else ""
    2801        expressions = self.expressions(expression)
    2802        with_ = (
    2803            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2804            if expressions
    2805            else ""
    2806        )
    2807        return f"OPENJSON({this}{path}){with_}"

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

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

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

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

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

    2829    def interval_sql(self, expression: exp.Interval) -> str:
    2830        unit = self.sql(expression, "unit")
    2831        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    2832            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    2833        unit = f" {unit}" if unit else ""
    2834
    2835        if self.SINGLE_STRING_INTERVAL:
    2836            this = expression.this.name if expression.this else ""
    2837            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    2838
    2839        this = self.sql(expression, "this")
    2840        if this:
    2841            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    2842            this = f" {this}" if unwrapped else f" ({this})"
    2843
    2844        return f"INTERVAL{this}{unit}"

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

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

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

    2849    def reference_sql(self, expression: exp.Reference) -> str:
    2850        this = self.sql(expression, "this")
    2851        expressions = self.expressions(expression, flat=True)
    2852        expressions = f"({expressions})" if expressions else ""
    2853        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2854        options = f" {options}" if options else ""
    2855        return f"REFERENCES {this}{expressions}{options}"

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

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

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

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

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

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

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

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

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

    2873    def alias_sql(self, expression: exp.Alias) -> str:
    2874        alias = self.sql(expression, "alias")
    2875        alias = f" AS {alias}" if alias else ""
    2876        return f"{self.sql(expression, 'this')}{alias}"

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

    2878    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    2879        alias = expression.args["alias"]
    2880        identifier_alias = isinstance(alias, exp.Identifier)
    2881
    2882        if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2883            alias.replace(exp.Literal.string(alias.output_name))
    2884        elif not identifier_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2885            alias.replace(exp.to_identifier(alias.output_name))
    2886
    2887        return self.alias_sql(expression)

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

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

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

    2892    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    2893        this = self.sql(expression, "this")
    2894        index = self.sql(expression, "expression")
    2895        return f"{this} AT {index}"

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

    2897    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    2898        this = self.sql(expression, "this")
    2899        zone = self.sql(expression, "zone")
    2900        return f"{this} AT TIME ZONE {zone}"

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

    2902    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    2903        this = self.sql(expression, "this")
    2904        zone = self.sql(expression, "zone")
    2905        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"

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

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

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

    2910    def and_sql(
    2911        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
    2912    ) -> str:
    2913        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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2979    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    2980        format_sql = self.sql(expression, "format")
    2981        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    2982        to_sql = self.sql(expression, "to")
    2983        to_sql = f" {to_sql}" if to_sql else ""
    2984        action = self.sql(expression, "action")
    2985        action = f" {action}" if action else ""
    2986        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

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

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

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

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

    2995    def collate_sql(self, expression: exp.Collate) -> str:
    2996        if self.COLLATE_IS_FUNC:
    2997            return self.function_fallback_sql(expression)
    2998        return self.binary(expression, "COLLATE")

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

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

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

    3003    def comment_sql(self, expression: exp.Comment) -> str:
    3004        this = self.sql(expression, "this")
    3005        kind = expression.args["kind"]
    3006        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    3007        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    3008        expression_sql = self.sql(expression, "expression")
    3009        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"

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

    3011    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    3012        this = self.sql(expression, "this")
    3013        delete = " DELETE" if expression.args.get("delete") else ""
    3014        recompress = self.sql(expression, "recompress")
    3015        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    3016        to_disk = self.sql(expression, "to_disk")
    3017        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    3018        to_volume = self.sql(expression, "to_volume")
    3019        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    3020        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    3022    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    3023        where = self.sql(expression, "where")
    3024        group = self.sql(expression, "group")
    3025        aggregates = self.expressions(expression, key="aggregates")
    3026        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    3027
    3028        if not (where or group or aggregates) and len(expression.expressions) == 1:
    3029            return f"TTL {self.expressions(expression, flat=True)}"
    3030
    3031        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    3036    def commit_sql(self, expression: exp.Commit) -> str:
    3037        chain = expression.args.get("chain")
    3038        if chain is not None:
    3039            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    3040
    3041        return f"COMMIT{chain or ''}"

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

    3043    def rollback_sql(self, expression: exp.Rollback) -> str:
    3044        savepoint = expression.args.get("savepoint")
    3045        savepoint = f" TO {savepoint}" if savepoint else ""
    3046        return f"ROLLBACK{savepoint}"

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

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

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

    3079    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
    3080        this = self.sql(expression, "this")
    3081        if not isinstance(expression.this, exp.Var):
    3082            this = f"KEY DISTKEY {this}"
    3083        return f"ALTER DISTSTYLE {this}"

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

    3085    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
    3086        compound = " COMPOUND" if expression.args.get("compound") else ""
    3087        this = self.sql(expression, "this")
    3088        expressions = self.expressions(expression, flat=True)
    3089        expressions = f"({expressions})" if expressions else ""
    3090        return f"ALTER{compound} SORTKEY {this or expressions}"

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

    3092    def renametable_sql(self, expression: exp.RenameTable) -> str:
    3093        if not self.RENAME_TABLE_WITH_DB:
    3094            # Remove db from tables
    3095            expression = expression.transform(
    3096                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    3097            ).assert_is(exp.RenameTable)
    3098        this = self.sql(expression, "this")
    3099        return f"RENAME TO {this}"

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

    3101    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    3102        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3103        old_column = self.sql(expression, "this")
    3104        new_column = self.sql(expression, "to")
    3105        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"

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

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

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

    3111    def altertable_sql(self, expression: exp.AlterTable) -> str:
    3112        actions = expression.args["actions"]
    3113
    3114        if isinstance(actions[0], exp.ColumnDef):
    3115            actions = self.add_column_sql(expression)
    3116        elif isinstance(actions[0], exp.Schema):
    3117            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    3118        elif isinstance(actions[0], exp.Delete):
    3119            actions = self.expressions(expression, key="actions", flat=True)
    3120        else:
    3121            actions = self.expressions(expression, key="actions", flat=True)
    3122
    3123        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3124        on_cluster = self.sql(expression, "cluster")
    3125        on_cluster = f" {on_cluster}" if on_cluster else ""
    3126        only = " ONLY" if expression.args.get("only") else ""
    3127        options = self.expressions(expression, key="options")
    3128        options = f", {options}" if options else ""
    3129        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

    3131    def add_column_sql(self, expression: exp.AlterTable) -> str:
    3132        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    3133            return self.expressions(
    3134                expression,
    3135                key="actions",
    3136                prefix="ADD COLUMN ",
    3137            )
    3138        return f"ADD {self.expressions(expression, key='actions', flat=True)}"

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

    3140    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    3141        expressions = self.expressions(expression)
    3142        exists = " IF EXISTS " if expression.args.get("exists") else " "
    3143        return f"DROP{exists}{expressions}"

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

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

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

    3148    def distinct_sql(self, expression: exp.Distinct) -> str:
    3149        this = self.expressions(expression, flat=True)
    3150
    3151        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    3152            case = exp.case()
    3153            for arg in expression.expressions:
    3154                case = case.when(arg.is_(exp.null()), exp.null())
    3155            this = self.sql(case.else_(f"({this})"))
    3156
    3157        this = f" {this}" if this else ""
    3158
    3159        on = self.sql(expression, "on")
    3160        on = f" ON {on}" if on else ""
    3161        return f"DISTINCT{this}{on}"

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

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

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

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

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

    3169    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    3170        this_sql = self.sql(expression, "this")
    3171        expression_sql = self.sql(expression, "expression")
    3172        kind = "MAX" if expression.args.get("max") else "MIN"
    3173        return f"{this_sql} HAVING {kind} {expression_sql}"

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

    3175    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    3176        return self.sql(
    3177            exp.Cast(
    3178                this=exp.Div(this=expression.this, expression=expression.expression),
    3179                to=exp.DataType(this=exp.DataType.Type.INT),
    3180            )
    3181        )

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

    3183    def dpipe_sql(self, expression: exp.DPipe) -> str:
    3184        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    3185            return self.func(
    3186                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
    3187            )
    3188        return self.binary(expression, "||")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3244    def is_sql(self, expression: exp.Is) -> str:
    3245        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3246            return self.sql(
    3247                expression.this if expression.expression.this else exp.not_(expression.this)
    3248            )
    3249        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3290    def try_sql(self, expression: exp.Try) -> str:
    3291        if not self.TRY_SUPPORTED:
    3292            self.unsupported("Unsupported TRY function")
    3293            return self.sql(expression, "this")
    3294
    3295        return self.func("TRY", expression.this)

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

    3297    def log_sql(self, expression: exp.Log) -> str:
    3298        this = expression.this
    3299        expr = expression.expression
    3300
    3301        if self.dialect.LOG_BASE_FIRST is False:
    3302            this, expr = expr, this
    3303        elif self.dialect.LOG_BASE_FIRST is None and expr:
    3304            if this.name in ("2", "10"):
    3305                return self.func(f"LOG{this.name}", expr)
    3306
    3307            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
    3308
    3309        return self.func("LOG", this, expr)

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

    3311    def use_sql(self, expression: exp.Use) -> str:
    3312        kind = self.sql(expression, "kind")
    3313        kind = f" {kind}" if kind else ""
    3314        this = self.sql(expression, "this")
    3315        this = f" {this}" if this else ""
    3316        return f"USE{kind}{this}"

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

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

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

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

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

    3341    def func(
    3342        self,
    3343        name: str,
    3344        *args: t.Optional[exp.Expression | str],
    3345        prefix: str = "(",
    3346        suffix: str = ")",
    3347    ) -> str:
    3348        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

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

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

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

    3359    def format_time(
    3360        self,
    3361        expression: exp.Expression,
    3362        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
    3363        inverse_time_trie: t.Optional[t.Dict] = None,
    3364    ) -> t.Optional[str]:
    3365        return format_time(
    3366            self.sql(expression, "format"),
    3367            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
    3368            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
    3369        )

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

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

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

    3430    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3431        flat = flat or isinstance(expression.parent, exp.Properties)
    3432        expressions_sql = self.expressions(expression, flat=flat)
    3433        if flat:
    3434            return f"{op} {expressions_sql}"
    3435        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    3437    def naked_property(self, expression: exp.Property) -> str:
    3438        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3439        if not property_name:
    3440            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3441        return f"{property_name} {self.sql(expression, 'this')}"

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

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

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

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

    3449    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3450        this = self.sql(expression, "this")
    3451        expressions = self.no_identify(self.expressions, expression)
    3452        expressions = (
    3453            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3454        )
    3455        return f"{this}{expressions}"

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

    3457    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3458        this = self.sql(expression, "this")
    3459        expressions = self.expressions(expression, flat=True)
    3460        return f"{this}({expressions})"

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

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

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

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

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

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

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

    3505    def tochar_sql(self, expression: exp.ToChar) -> str:
    3506        if expression.args.get("format"):
    3507            self.unsupported("Format argument unsupported for TO_CHAR/TO_VARCHAR function")
    3508
    3509        return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT))

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

    3511    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3512        if not self.SUPPORTS_TO_NUMBER:
    3513            self.unsupported("Unsupported TO_NUMBER function")
    3514            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3515
    3516        fmt = expression.args.get("format")
    3517        if not fmt:
    3518            self.unsupported("Conversion format is required for TO_NUMBER")
    3519            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3520
    3521        return self.func("TO_NUMBER", expression.this, fmt)

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

    3523    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3524        this = self.sql(expression, "this")
    3525        kind = self.sql(expression, "kind")
    3526        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3527        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3528        return f"{this}({kind}{args})"

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

    3530    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3531        this = self.sql(expression, "this")
    3532        max = self.sql(expression, "max")
    3533        min = self.sql(expression, "min")
    3534        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

    3542    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3543        expressions = self.expressions(expression, key="expressions", flat=True)
    3544        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3545        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3546        buckets = self.sql(expression, "buckets")
    3547        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    3549    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3550        this = self.sql(expression, "this")
    3551        having = self.sql(expression, "having")
    3552
    3553        if having:
    3554            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3555
    3556        return self.func("ANY_VALUE", this)

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

    3558    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3559        transform = self.func("TRANSFORM", *expression.expressions)
    3560        row_format_before = self.sql(expression, "row_format_before")
    3561        row_format_before = f" {row_format_before}" if row_format_before else ""
    3562        record_writer = self.sql(expression, "record_writer")
    3563        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3564        using = f" USING {self.sql(expression, 'command_script')}"
    3565        schema = self.sql(expression, "schema")
    3566        schema = f" AS {schema}" if schema else ""
    3567        row_format_after = self.sql(expression, "row_format_after")
    3568        row_format_after = f" {row_format_after}" if row_format_after else ""
    3569        record_reader = self.sql(expression, "record_reader")
    3570        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3571        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

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

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

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

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

    3609    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3610        kind = self.sql(expression, "kind")
    3611        kind = f"{kind} INDEX" if kind else "INDEX"
    3612        this = self.sql(expression, "this")
    3613        this = f" {this}" if this else ""
    3614        index_type = self.sql(expression, "index_type")
    3615        index_type = f" USING {index_type}" if index_type else ""
    3616        expressions = self.expressions(expression, flat=True)
    3617        expressions = f" ({expressions})" if expressions else ""
    3618        options = self.expressions(expression, key="options", sep=" ")
    3619        options = f" {options}" if options else ""
    3620        return f"{kind}{this}{index_type}{expressions}{options}"

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

    3622    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3623        if self.NVL2_SUPPORTED:
    3624            return self.function_fallback_sql(expression)
    3625
    3626        case = exp.Case().when(
    3627            expression.this.is_(exp.null()).not_(copy=False),
    3628            expression.args["true"],
    3629            copy=False,
    3630        )
    3631        else_cond = expression.args.get("false")
    3632        if else_cond:
    3633            case.else_(else_cond, copy=False)
    3634
    3635        return self.sql(case)

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

    3637    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3638        this = self.sql(expression, "this")
    3639        expr = self.sql(expression, "expression")
    3640        iterator = self.sql(expression, "iterator")
    3641        condition = self.sql(expression, "condition")
    3642        condition = f" IF {condition}" if condition else ""
    3643        return f"{this} FOR {expr} IN {iterator}{condition}"

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

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

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

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

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

    3651    def predict_sql(self, expression: exp.Predict) -> str:
    3652        model = self.sql(expression, "this")
    3653        model = f"MODEL {model}"
    3654        table = self.sql(expression, "expression")
    3655        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    3656        parameters = self.sql(expression, "params_struct")
    3657        return self.func("PREDICT", model, table, parameters or None)

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

    3659    def forin_sql(self, expression: exp.ForIn) -> str:
    3660        this = self.sql(expression, "this")
    3661        expression_sql = self.sql(expression, "expression")
    3662        return f"FOR {this} DO {expression_sql}"

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

    3664    def refresh_sql(self, expression: exp.Refresh) -> str:
    3665        this = self.sql(expression, "this")
    3666        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    3667        return f"REFRESH {table}{this}"

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

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

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

    3672    def toarray_sql(self, expression: exp.ToArray) -> str:
    3673        arg = expression.this
    3674        if not arg.type:
    3675            from sqlglot.optimizer.annotate_types import annotate_types
    3676
    3677            arg = annotate_types(arg)
    3678
    3679        if arg.is_type(exp.DataType.Type.ARRAY):
    3680            return self.sql(arg)
    3681
    3682        cond_for_null = arg.is_(exp.null())
    3683        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

    3685    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    3686        this = expression.this
    3687        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    3688            return self.sql(this)
    3689
    3690        return self.sql(exp.cast(this, exp.DataType.Type.TIME))

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

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

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

    3699    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    3700        this = expression.this
    3701        time_format = self.format_time(expression)
    3702
    3703        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    3704            return self.sql(
    3705                exp.cast(
    3706                    exp.StrToTime(this=this, format=expression.args["format"]),
    3707                    exp.DataType.Type.DATE,
    3708                )
    3709            )
    3710
    3711        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    3712            return self.sql(this)
    3713
    3714        return self.sql(exp.cast(this, exp.DataType.Type.DATE))

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

    3716    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    3717        return self.sql(
    3718            exp.func(
    3719                "DATEDIFF",
    3720                expression.this,
    3721                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
    3722                "day",
    3723            )
    3724        )

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

    3726    def lastday_sql(self, expression: exp.LastDay) -> str:
    3727        if self.LAST_DAY_SUPPORTS_DATE_PART:
    3728            return self.function_fallback_sql(expression)
    3729
    3730        unit = expression.text("unit")
    3731        if unit and unit != "MONTH":
    3732            self.unsupported("Date parts are not supported in LAST_DAY.")
    3733
    3734        return self.func("LAST_DAY", expression.this)

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

    3736    def dateadd_sql(self, expression: exp.DateAdd) -> str:
    3737        from sqlglot.dialects.dialect import unit_to_str
    3738
    3739        return self.func(
    3740            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
    3741        )

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

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

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

    3758    def generateseries_sql(self, expression: exp.GenerateSeries) -> str:
    3759        expression.set("is_end_exclusive", None)
    3760        return self.function_fallback_sql(expression)

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

    3762    def struct_sql(self, expression: exp.Struct) -> str:
    3763        expression.set(
    3764            "expressions",
    3765            [
    3766                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    3767                if isinstance(e, exp.PropertyEQ)
    3768                else e
    3769                for e in expression.expressions
    3770            ],
    3771        )
    3772
    3773        return self.function_fallback_sql(expression)

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

    3775    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    3776        low = self.sql(expression, "this")
    3777        high = self.sql(expression, "expression")
    3778
    3779        return f"{low} TO {high}"

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

    3781    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    3782        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    3783        tables = f" {self.expressions(expression)}"
    3784
    3785        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3786
    3787        on_cluster = self.sql(expression, "cluster")
    3788        on_cluster = f" {on_cluster}" if on_cluster else ""
    3789
    3790        identity = self.sql(expression, "identity")
    3791        identity = f" {identity} IDENTITY" if identity else ""
    3792
    3793        option = self.sql(expression, "option")
    3794        option = f" {option}" if option else ""
    3795
    3796        partition = self.sql(expression, "partition")
    3797        partition = f" {partition}" if partition else ""
    3798
    3799        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"

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

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

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

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

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

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

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

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

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

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

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

    3978    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
    3979        on_sql = "ON" if expression.args.get("on") else "OFF"
    3980        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
    3981        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
    3982        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    3983        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
    3984
    3985        if filter_col or retention_period:
    3986            on_sql = self.func("ON", filter_col, retention_period)
    3987
    3988        return f"DATA_DELETION={on_sql}"

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

    3990    def maskingpolicycolumnconstraint_sql(
    3991        self, expression: exp.MaskingPolicyColumnConstraint
    3992    ) -> str:
    3993        this = self.sql(expression, "this")
    3994        expressions = self.expressions(expression, flat=True)
    3995        expressions = f" USING ({expressions})" if expressions else ""
    3996        return f"MASKING POLICY {this}{expressions}"

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

    3998    def gapfill_sql(self, expression: exp.GapFill) -> str:
    3999        this = self.sql(expression, "this")
    4000        this = f"TABLE {this}"
    4001        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

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

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

    4006    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
    4007        this = self.sql(expression, "this")
    4008        expr = expression.expression
    4009
    4010        if isinstance(expr, exp.Func):
    4011            # T-SQL's CLR functions are case sensitive
    4012            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
    4013        else:
    4014            expr = self.sql(expression, "expression")
    4015
    4016        return self.scope_resolution(expr, this)

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

    4018    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
    4019        if self.PARSE_JSON_NAME is None:
    4020            return self.sql(expression.this)
    4021
    4022        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)

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

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

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

    4027    def rand_sql(self, expression: exp.Rand) -> str:
    4028        lower = self.sql(expression, "lower")
    4029        upper = self.sql(expression, "upper")
    4030
    4031        if lower and upper:
    4032            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
    4033        return self.func("RAND", expression.this)

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

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

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

    4038    def strtotime_sql(self, expression: exp.StrToTime) -> str:
    4039        return self.func(
    4040            "STR_TO_TIME",
    4041            expression.this,
    4042            expression.args.get("format"),
    4043            expression.args.get("zone"),
    4044        )

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

    4046    def changes_sql(self, expression: exp.Changes) -> str:
    4047        information = self.sql(expression, "information")
    4048        information = f"INFORMATION => {information}"
    4049        at_before = self.sql(expression, "at_before")
    4050        at_before = f"{self.seg('')}{at_before}" if at_before else ""
    4051        end = self.sql(expression, "end")
    4052        end = f"{self.seg('')}{end}" if end else ""
    4053
    4054        return f"CHANGES ({information}){at_before}{end}"

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

    4056    def pad_sql(self, expression: exp.Pad) -> str:
    4057        prefix = "L" if expression.args.get("is_left") else "R"
    4058
    4059        fill_pattern = self.sql(expression, "fill_pattern") or None
    4060        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
    4061            fill_pattern = "' '"
    4062
    4063        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)