sqlglot.generator API documentation

Edit on GitHub

# sqlglot.generator

View Source

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

logger = <Logger sqlglot (WARNING)>
class Generator: View Source

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

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

###### Arguments:

- pretty: Whether or not 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 or not to normalize identifiers to lowercase. Default: False.
- pad: Determines the pad size in a formatted string. Default: 2.
- indent: Determines the indentation size in a formatted string. Default: 2.
- normalize_functions: Whether or not to normalize all 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: Determines whether or not 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 or not 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) View Source

    420    def __init__(
    421        self,
    422        pretty: t.Optional[bool] = None,
    423        identify: str | bool = False,
    424        normalize: bool = False,
    425        pad: int = 2,
    426        indent: int = 2,
    427        normalize_functions: t.Optional[str | bool] = None,
    428        unsupported_level: ErrorLevel = ErrorLevel.WARN,
    429        max_unsupported: int = 3,
    430        leading_comma: bool = False,
    431        max_text_width: int = 80,
    432        comments: bool = True,
    433    ):
    434        import sqlglot
    435
    436        self.pretty = pretty if pretty is not None else sqlglot.pretty
    437        self.identify = identify
    438        self.normalize = normalize
    439        self.pad = pad
    440        self._indent = indent
    441        self.unsupported_level = unsupported_level
    442        self.max_unsupported = max_unsupported
    443        self.leading_comma = leading_comma
    444        self.max_text_width = max_text_width
    445        self.comments = comments
    446
    447        # This is both a Dialect property and a Generator argument, so we prioritize the latter
    448        self.normalize_functions = (
    449            self.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
    450        )
    451
    452        self.unsupported_messages: t.List[str] = []
    453        self._escaped_quote_end: str = self.TOKENIZER_CLASS.STRING_ESCAPES[0] + self.QUOTE_END
    454        self._escaped_identifier_end: str = (
    455            self.TOKENIZER_CLASS.IDENTIFIER_ESCAPES[0] + self.IDENTIFIER_END
    456        )

TRANSFORMS = {<class 'sqlglot.expressions.DateAdd'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TsOrDsAdd'>: <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.CheckColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>}
LOG_BASE_FIRST = True
NULL_ORDERING_SUPPORTED = True
LOCKING_READS_SUPPORTED = False
EXPLICIT_UNION = False
WRAP_DERIVED_VALUES = True
CREATE_FUNCTION_RETURN_AS = True
MATCHED_BY_SOURCE = True
SINGLE_STRING_INTERVAL = False
INTERVAL_ALLOWS_PLURAL_FORM = True
TABLESAMPLE_WITH_METHOD = True
TABLESAMPLE_SIZE_IS_PERCENT = False
LIMIT_FETCH = 'ALL'
LIMIT_ONLY_LITERALS = False
RENAME_TABLE_WITH_DB = True
GROUPINGS_SEP = ','
INDEX_ON = 'ON'
JOIN_HINTS = True
TABLE_HINTS = True
QUERY_HINTS = True
QUERY_HINT_SEP = ', '
IS_BOOL_ALLOWED = True
DUPLICATE_KEY_UPDATE_WITH_SET = True
LIMIT_IS_TOP = False
RETURNING_END = True
COLUMN_JOIN_MARKS_SUPPORTED = False
EXTRACT_ALLOWS_QUOTES = True
TZ_TO_WITH_TIME_ZONE = False
NVL2_SUPPORTED = True
SELECT_KINDS: Tuple[str, ...] = ('STRUCT', 'VALUE')
VALUES_AS_TABLE = True
ALTER_TABLE_ADD_COLUMN_KEYWORD = True
UNNEST_WITH_ORDINALITY = True
AGGREGATE_FILTER_SUPPORTED = True
SEMI_ANTI_JOIN_WITH_SIDE = True
SUPPORTS_PARAMETERS = True
COMPUTED_COLUMN_WITH_TYPE = True
SUPPORTS_TABLE_COPY = True
TABLESAMPLE_REQUIRES_PARENS = True
COLLATE_IS_FUNC = False
DATA_TYPE_SPECIFIERS_ALLOWED = False
SUPPORTS_NESTED_CTES = True
CTE_RECURSIVE_KEYWORD_REQUIRED = True
TYPE_MAPPING = {<Type.NCHAR: 'NCHAR'>: 'CHAR', <Type.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <Type.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <Type.LONGTEXT: 'LONGTEXT'>: 'TEXT', <Type.TINYTEXT: 'TINYTEXT'>: 'TEXT', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <Type.LONGBLOB: 'LONGBLOB'>: 'BLOB', <Type.TINYBLOB: 'TINYBLOB'>: 'BLOB', <Type.INET: 'INET'>: 'INET'}
STAR_MAPPING = {'except': 'EXCEPT', 'replace': 'REPLACE'}
TIME_PART_SINGULARS = {'microseconds': 'microsecond', 'seconds': 'second', 'minutes': 'minute', 'hours': 'hour', 'days': 'day', 'weeks': 'week', 'months': 'month', 'quarters': 'quarter', 'years': 'year'}
TOKEN_MAPPING: Dict[sqlglot.tokens.TokenType, str] = {}
STRUCT_DELIMITER = ('<', '>')
PARAMETER_TOKEN = '@'
PROPERTIES_LOCATION = {<class 'sqlglot.expressions.AlgorithmProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.AutoIncrementProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BlockCompressionProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CharacterSetProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ChecksumProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CollateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Cluster'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ClusteredByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DataBlocksizeProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.DefinerProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DictRange'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistStyleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EngineProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExternalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.FallbackProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.FileFormatProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.FreespaceProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.HeapProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.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.LockingProperty'>: <Location.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.LogProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.MaterializedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeBlockRatioProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.OnProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OnCommitProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.Order'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OutputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PartitionedByProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.PartitionedOfProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ReturnsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatDelimitedProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatSerdeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SampleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SchemaCommentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SerdeProperties'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Set'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SettingsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SetProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SortKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StabilityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TemporaryProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ToTableProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TransientProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.TransformModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.MergeTreeTTL'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>}
RESERVED_KEYWORDS: Set[str] = set()
WITH_SEPARATED_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Create'>, <class 'sqlglot.expressions.Delete'>, <class 'sqlglot.expressions.Drop'>, <class 'sqlglot.expressions.From'>, <class 'sqlglot.expressions.Insert'>, <class 'sqlglot.expressions.Join'>, <class 'sqlglot.expressions.Select'>, <class 'sqlglot.expressions.Update'>, <class 'sqlglot.expressions.Where'>, <class 'sqlglot.expressions.With'>)
EXCLUDE_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Binary'>, <class 'sqlglot.expressions.Union'>)
UNWRAPPED_INTERVAL_VALUES: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Column'>, <class 'sqlglot.expressions.Literal'>, <class 'sqlglot.expressions.Neg'>, <class 'sqlglot.expressions.Paren'>)
SENTINEL_LINE_BREAK = '__SQLGLOT__LB__'
INVERSE_TIME_MAPPING: Dict[str, str] = {}
INVERSE_TIME_TRIE: Dict = {}
INVERSE_ESCAPE_SEQUENCES: Dict[str, str] = {}
INDEX_OFFSET = 0
UNNEST_COLUMN_ONLY = False
ALIAS_POST_TABLESAMPLE = False
IDENTIFIERS_CAN_START_WITH_DIGIT = False
STRICT_STRING_CONCAT = False
NORMALIZE_FUNCTIONS: bool | str = 'upper'
NULL_ORDERING = 'nulls_are_small'
@classmethod
def can_identify(text: str, identify: str | bool = 'safe') -> bool: View Source

    279    @classmethod
    280    def can_identify(cls, text: str, identify: str | bool = "safe") -> bool:
    281        """Checks if text can be identified given an identify option.
    282
    283        Args:
    284            text: The text to check.
    285            identify:
    286                "always" or `True`: Always returns true.
    287                "safe": True if the identifier is case-insensitive.
    288
    289        Returns:
    290            Whether or not the given text can be identified.
    291        """
    292        if identify is True or identify == "always":
    293            return True
    294
    295        if identify == "safe":
    296            return not cls.case_sensitive(text)
    297
    298        return False

Checks if text can be identified given an identify option.

###### Arguments:

- text: The text to check.
- identify: "always" or `True`: Always returns true. "safe": True if the identifier is case-insensitive.

###### Returns:

> Whether or not the given text can be identified.

QUOTE_START = "'"
QUOTE_END = "'"
IDENTIFIER_START = '"'
IDENTIFIER_END = '"'
TOKENIZER_CLASS = <class 'sqlglot.tokens.Tokenizer'>
BIT_START: Optional[str] = None
BIT_END: Optional[str] = None
HEX_START: Optional[str] = None
HEX_END: Optional[str] = None
BYTE_START: Optional[str] = None
BYTE_END: Optional[str] = None
pretty
identify
normalize
pad
unsupported_level
max_unsupported
leading_comma
max_text_width
comments
normalize_functions
unsupported_messages: List[str]
def generate( self, expression: sqlglot.expressions.Expression, copy: bool = True) -> str: View Source

    458    def generate(self, expression: exp.Expression, copy: bool = True) -> str:
    459        """
    460        Generates the SQL string corresponding to the given syntax tree.
    461
    462        Args:
    463            expression: The syntax tree.
    464            copy: Whether or not to copy the expression. The generator performs mutations so
    465                it is safer to copy.
    466
    467        Returns:
    468            The SQL string corresponding to `expression`.
    469        """
    470        if copy:
    471            expression = expression.copy()
    472
    473        # Some dialects only support CTEs at the top level expression, so we need to bubble up nested
    474        # CTEs to that level in order to produce a syntactically valid expression. This transformation
    475        # happens here to minimize code duplication, since many expressions support CTEs.
    476        if (
    477            not self.SUPPORTS_NESTED_CTES
    478            and isinstance(expression, exp.Expression)
    479            and not expression.parent
    480            and "with" in expression.arg_types
    481            and any(node.parent is not expression for node in expression.find_all(exp.With))
    482        ):
    483            from sqlglot.transforms import move_ctes_to_top_level
    484
    485            expression = move_ctes_to_top_level(expression)
    486
    487        self.unsupported_messages = []
    488        sql = self.sql(expression).strip()
    489
    490        if self.unsupported_level == ErrorLevel.IGNORE:
    491            return sql
    492
    493        if self.unsupported_level == ErrorLevel.WARN:
    494            for msg in self.unsupported_messages:
    495                logger.warning(msg)
    496        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
    497            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
    498
    499        if self.pretty:
    500            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
    501        return sql

Generates the SQL string corresponding to the given syntax tree.

###### Arguments:

- expression: The syntax tree.
- copy: Whether or not to copy the expression. The generator performs mutations so it is safer to copy.

###### Returns:

> The SQL string corresponding to `expression`.

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

    503    def unsupported(self, message: str) -> None:
    504        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    505            raise UnsupportedError(message)
    506        self.unsupported_messages.append(message)

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

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

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

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

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

    514    def pad_comment(self, comment: str) -> str:
    515        comment = " " + comment if comment[0].strip() else comment
    516        comment = comment + " " if comment[-1].strip() else comment
    517        return comment

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

    519    def maybe_comment(
    520        self,
    521        sql: str,
    522        expression: t.Optional[exp.Expression] = None,
    523        comments: t.Optional[t.List[str]] = None,
    524    ) -> str:
    525        comments = (
    526            ((expression and expression.comments) if comments is None else comments)  # type: ignore
    527            if self.comments
    528            else None
    529        )
    530
    531        if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
    532            return sql
    533
    534        comments_sql = " ".join(
    535            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
    536        )
    537
    538        if not comments_sql:
    539            return sql
    540
    541        if isinstance(expression, self.WITH_SEPARATED_COMMENTS):
    542            return (
    543                f"{self.sep()}{comments_sql}{sql}"
    544                if sql[0].isspace()
    545                else f"{comments_sql}{self.sep()}{sql}"
    546            )
    547
    548        return f"{sql} {comments_sql}"

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

    550    def wrap(self, expression: exp.Expression | str) -> str:
    551        this_sql = self.indent(
    552            self.sql(expression)
    553            if isinstance(expression, (exp.Select, exp.Union))
    554            else self.sql(expression, "this"),
    555            level=1,
    556            pad=0,
    557        )
    558        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"

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

    560    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    561        original = self.identify
    562        self.identify = False
    563        result = func(*args, **kwargs)
    564        self.identify = original
    565        return result

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

    567    def normalize_func(self, name: str) -> str:
    568        if self.normalize_functions == "upper" or self.normalize_functions is True:
    569            return name.upper()
    570        if self.normalize_functions == "lower":
    571            return name.lower()
    572        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

    574    def indent(
    575        self,
    576        sql: str,
    577        level: int = 0,
    578        pad: t.Optional[int] = None,
    579        skip_first: bool = False,
    580        skip_last: bool = False,
    581    ) -> str:
    582        if not self.pretty:
    583            return sql
    584
    585        pad = self.pad if pad is None else pad
    586        lines = sql.split("\n")
    587
    588        return "\n".join(
    589            line
    590            if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
    591            else f"{' ' * (level * self._indent + pad)}{line}"
    592            for i, line in enumerate(lines)
    593        )

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

    595    def sql(
    596        self,
    597        expression: t.Optional[str | exp.Expression],
    598        key: t.Optional[str] = None,
    599        comment: bool = True,
    600    ) -> str:
    601        if not expression:
    602            return ""
    603
    604        if isinstance(expression, str):
    605            return expression
    606
    607        if key:
    608            value = expression.args.get(key)
    609            if value:
    610                return self.sql(value)
    611            return ""
    612
    613        transform = self.TRANSFORMS.get(expression.__class__)
    614
    615        if callable(transform):
    616            sql = transform(self, expression)
    617        elif transform:
    618            sql = transform
    619        elif isinstance(expression, exp.Expression):
    620            exp_handler_name = f"{expression.key}_sql"
    621
    622            if hasattr(self, exp_handler_name):
    623                sql = getattr(self, exp_handler_name)(expression)
    624            elif isinstance(expression, exp.Func):
    625                sql = self.function_fallback_sql(expression)
    626            elif isinstance(expression, exp.Property):
    627                sql = self.property_sql(expression)
    628            else:
    629                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
    630        else:
    631            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
    632
    633        return self.maybe_comment(sql, expression) if self.comments and comment else sql

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

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

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

    640    def cache_sql(self, expression: exp.Cache) -> str:
    641        lazy = " LAZY" if expression.args.get("lazy") else ""
    642        table = self.sql(expression, "this")
    643        options = expression.args.get("options")
    644        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
    645        sql = self.sql(expression, "expression")
    646        sql = f" AS{self.sep()}{sql}" if sql else ""
    647        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
    648        return self.prepend_ctes(expression, sql)

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

    650    def characterset_sql(self, expression: exp.CharacterSet) -> str:
    651        if isinstance(expression.parent, exp.Cast):
    652            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
    653        default = "DEFAULT " if expression.args.get("default") else ""
    654        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"

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

    656    def column_sql(self, expression: exp.Column) -> str:
    657        join_mark = " (+)" if expression.args.get("join_mark") else ""
    658
    659        if join_mark and not self.COLUMN_JOIN_MARKS_SUPPORTED:
    660            join_mark = ""
    661            self.unsupported("Outer join syntax using the (+) operator is not supported.")
    662
    663        column = ".".join(
    664            self.sql(part)
    665            for part in (
    666                expression.args.get("catalog"),
    667                expression.args.get("db"),
    668                expression.args.get("table"),
    669                expression.args.get("this"),
    670            )
    671            if part
    672        )
    673
    674        return f"{column}{join_mark}"

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

    676    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    677        this = self.sql(expression, "this")
    678        this = f" {this}" if this else ""
    679        position = self.sql(expression, "position")
    680        return f"{position}{this}"

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

    682    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
    683        column = self.sql(expression, "this")
    684        kind = self.sql(expression, "kind")
    685        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
    686        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
    687        kind = f"{sep}{kind}" if kind else ""
    688        constraints = f" {constraints}" if constraints else ""
    689        position = self.sql(expression, "position")
    690        position = f" {position}" if position else ""
    691
    692        if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:
    693            kind = ""
    694
    695        return f"{exists}{column}{kind}{constraints}{position}"

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

    697    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    698        this = self.sql(expression, "this")
    699        kind_sql = self.sql(expression, "kind").strip()
    700        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

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

    702    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
    703        this = self.sql(expression, "this")
    704        if expression.args.get("not_null"):
    705            persisted = " PERSISTED NOT NULL"
    706        elif expression.args.get("persisted"):
    707            persisted = " PERSISTED"
    708        else:
    709            persisted = ""
    710        return f"AS {this}{persisted}"

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

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

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

    715    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
    716        if isinstance(expression.this, list):
    717            this = self.wrap(self.expressions(expression, key="this", flat=True))
    718        else:
    719            this = self.sql(expression, "this")
    720
    721        return f"COMPRESS {this}"

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

    723    def generatedasidentitycolumnconstraint_sql(
    724        self, expression: exp.GeneratedAsIdentityColumnConstraint
    725    ) -> str:
    726        this = ""
    727        if expression.this is not None:
    728            on_null = " ON NULL" if expression.args.get("on_null") else ""
    729            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
    730
    731        start = expression.args.get("start")
    732        start = f"START WITH {start}" if start else ""
    733        increment = expression.args.get("increment")
    734        increment = f" INCREMENT BY {increment}" if increment else ""
    735        minvalue = expression.args.get("minvalue")
    736        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    737        maxvalue = expression.args.get("maxvalue")
    738        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    739        cycle = expression.args.get("cycle")
    740        cycle_sql = ""
    741
    742        if cycle is not None:
    743            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
    744            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
    745
    746        sequence_opts = ""
    747        if start or increment or cycle_sql:
    748            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
    749            sequence_opts = f" ({sequence_opts.strip()})"
    750
    751        expr = self.sql(expression, "expression")
    752        expr = f"({expr})" if expr else "IDENTITY"
    753
    754        return f"GENERATED{this} AS {expr}{sequence_opts}"

def notnullcolumnconstraint_sql(self, expression: sqlglot.expressions.NotNullColumnConstraint) -> str: View Source

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

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

    759    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    760        desc = expression.args.get("desc")
    761        if desc is not None:
    762            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    763        return f"PRIMARY KEY"

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

    765    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    766        this = self.sql(expression, "this")
    767        this = f" {this}" if this else ""
    768        index_type = expression.args.get("index_type")
    769        index_type = f" USING {index_type}" if index_type else ""
    770        return f"UNIQUE{this}{index_type}"

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

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

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

    775    def create_sql(self, expression: exp.Create) -> str:
    776        kind = self.sql(expression, "kind").upper()
    777        properties = expression.args.get("properties")
    778        properties_locs = self.locate_properties(properties) if properties else defaultdict()
    779
    780        this = self.createable_sql(expression, properties_locs)
    781
    782        properties_sql = ""
    783        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
    784            exp.Properties.Location.POST_WITH
    785        ):
    786            properties_sql = self.sql(
    787                exp.Properties(
    788                    expressions=[
    789                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
    790                        *properties_locs[exp.Properties.Location.POST_WITH],
    791                    ]
    792                )
    793            )
    794
    795        begin = " BEGIN" if expression.args.get("begin") else ""
    796        end = " END" if expression.args.get("end") else ""
    797
    798        expression_sql = self.sql(expression, "expression")
    799        if expression_sql:
    800            expression_sql = f"{begin}{self.sep()}{expression_sql}{end}"
    801
    802            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
    803                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
    804                    postalias_props_sql = self.properties(
    805                        exp.Properties(
    806                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
    807                        ),
    808                        wrapped=False,
    809                    )
    810                    expression_sql = f" AS {postalias_props_sql}{expression_sql}"
    811                else:
    812                    expression_sql = f" AS{expression_sql}"
    813
    814        postindex_props_sql = ""
    815        if properties_locs.get(exp.Properties.Location.POST_INDEX):
    816            postindex_props_sql = self.properties(
    817                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
    818                wrapped=False,
    819                prefix=" ",
    820            )
    821
    822        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
    823        indexes = f" {indexes}" if indexes else ""
    824        index_sql = indexes + postindex_props_sql
    825
    826        replace = " OR REPLACE" if expression.args.get("replace") else ""
    827        unique = " UNIQUE" if expression.args.get("unique") else ""
    828
    829        postcreate_props_sql = ""
    830        if properties_locs.get(exp.Properties.Location.POST_CREATE):
    831            postcreate_props_sql = self.properties(
    832                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
    833                sep=" ",
    834                prefix=" ",
    835                wrapped=False,
    836            )
    837
    838        modifiers = "".join((replace, unique, postcreate_props_sql))
    839
    840        postexpression_props_sql = ""
    841        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
    842            postexpression_props_sql = self.properties(
    843                exp.Properties(
    844                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
    845                ),
    846                sep=" ",
    847                prefix=" ",
    848                wrapped=False,
    849            )
    850
    851        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    852        no_schema_binding = (
    853            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
    854        )
    855
    856        clone = self.sql(expression, "clone")
    857        clone = f" {clone}" if clone else ""
    858
    859        expression_sql = f"CREATE{modifiers} {kind}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
    860        return self.prepend_ctes(expression, expression_sql)

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

    862    def clone_sql(self, expression: exp.Clone) -> str:
    863        this = self.sql(expression, "this")
    864        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    865        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
    866        this = f"{shallow}{keyword} {this}"
    867        when = self.sql(expression, "when")
    868
    869        if when:
    870            kind = self.sql(expression, "kind")
    871            expr = self.sql(expression, "expression")
    872            return f"{this} {when} ({kind} => {expr})"
    873
    874        return this

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

    876    def describe_sql(self, expression: exp.Describe) -> str:
    877        return f"DESCRIBE {self.sql(expression, 'this')}"

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

    879    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    880        with_ = self.sql(expression, "with")
    881        if with_:
    882            sql = f"{with_}{self.sep()}{sql}"
    883        return sql

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

    885    def with_sql(self, expression: exp.With) -> str:
    886        sql = self.expressions(expression, flat=True)
    887        recursive = (
    888            "RECURSIVE "
    889            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
    890            else ""
    891        )
    892
    893        return f"WITH {recursive}{sql}"

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

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

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

    899    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    900        alias = self.sql(expression, "this")
    901        columns = self.expressions(expression, key="columns", flat=True)
    902        columns = f"({columns})" if columns else ""
    903
    904        if not alias and not self.UNNEST_COLUMN_ONLY:
    905            alias = "_t"
    906
    907        return f"{alias}{columns}"

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

    909    def bitstring_sql(self, expression: exp.BitString) -> str:
    910        this = self.sql(expression, "this")
    911        if self.BIT_START:
    912            return f"{self.BIT_START}{this}{self.BIT_END}"
    913        return f"{int(this, 2)}"

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

    915    def hexstring_sql(self, expression: exp.HexString) -> str:
    916        this = self.sql(expression, "this")
    917        if self.HEX_START:
    918            return f"{self.HEX_START}{this}{self.HEX_END}"
    919        return f"{int(this, 16)}"

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

    921    def bytestring_sql(self, expression: exp.ByteString) -> str:
    922        this = self.sql(expression, "this")
    923        if self.BYTE_START:
    924            return f"{self.BYTE_START}{this}{self.BYTE_END}"
    925        return this

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

    927    def rawstring_sql(self, expression: exp.RawString) -> str:
    928        string = self.escape_str(expression.this.replace("\\", "\\\\"))
    929        return f"{self.QUOTE_START}{string}{self.QUOTE_END}"

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

    931    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    932        this = self.sql(expression, "this")
    933        specifier = self.sql(expression, "expression")
    934        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    935        return f"{this}{specifier}"

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

    937    def datatype_sql(self, expression: exp.DataType) -> str:
    938        type_value = expression.this
    939
    940        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
    941            type_sql = self.sql(expression, "kind")
    942        else:
    943            type_sql = (
    944                self.TYPE_MAPPING.get(type_value, type_value.value)
    945                if isinstance(type_value, exp.DataType.Type)
    946                else type_value
    947            )
    948
    949        nested = ""
    950        interior = self.expressions(expression, flat=True)
    951        values = ""
    952
    953        if interior:
    954            if expression.args.get("nested"):
    955                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    956                if expression.args.get("values") is not None:
    957                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    958                    values = self.expressions(expression, key="values", flat=True)
    959                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    960            elif type_value == exp.DataType.Type.INTERVAL:
    961                nested = f" {interior}"
    962            else:
    963                nested = f"({interior})"
    964
    965        type_sql = f"{type_sql}{nested}{values}"
    966        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
    967            exp.DataType.Type.TIMETZ,
    968            exp.DataType.Type.TIMESTAMPTZ,
    969        ):
    970            type_sql = f"{type_sql} WITH TIME ZONE"
    971
    972        return type_sql

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

    974    def directory_sql(self, expression: exp.Directory) -> str:
    975        local = "LOCAL " if expression.args.get("local") else ""
    976        row_format = self.sql(expression, "row_format")
    977        row_format = f" {row_format}" if row_format else ""
    978        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

    980    def delete_sql(self, expression: exp.Delete) -> str:
    981        this = self.sql(expression, "this")
    982        this = f" FROM {this}" if this else ""
    983        using = self.sql(expression, "using")
    984        using = f" USING {using}" if using else ""
    985        where = self.sql(expression, "where")
    986        returning = self.sql(expression, "returning")
    987        limit = self.sql(expression, "limit")
    988        tables = self.expressions(expression, key="tables")
    989        tables = f" {tables}" if tables else ""
    990        if self.RETURNING_END:
    991            expression_sql = f"{this}{using}{where}{returning}{limit}"
    992        else:
    993            expression_sql = f"{returning}{this}{using}{where}{limit}"
    994        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

     996    def drop_sql(self, expression: exp.Drop) -> str:
     997        this = self.sql(expression, "this")
     998        kind = expression.args["kind"]
     999        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    1000        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1001        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    1002        cascade = " CASCADE" if expression.args.get("cascade") else ""
    1003        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    1004        purge = " PURGE" if expression.args.get("purge") else ""
    1005        return (
    1006            f"DROP{temporary}{materialized} {kind}{exists_sql}{this}{cascade}{constraints}{purge}"
    1007        )

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

    1009    def except_sql(self, expression: exp.Except) -> str:
    1010        return self.prepend_ctes(
    1011            expression,
    1012            self.set_operation(expression, self.except_op(expression)),
    1013        )

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

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

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

    1018    def fetch_sql(self, expression: exp.Fetch) -> str:
    1019        direction = expression.args.get("direction")
    1020        direction = f" {direction.upper()}" if direction else ""
    1021        count = expression.args.get("count")
    1022        count = f" {count}" if count else ""
    1023        if expression.args.get("percent"):
    1024            count = f"{count} PERCENT"
    1025        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    1026        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"

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

    1028    def filter_sql(self, expression: exp.Filter) -> str:
    1029        if self.AGGREGATE_FILTER_SUPPORTED:
    1030            this = self.sql(expression, "this")
    1031            where = self.sql(expression, "expression").strip()
    1032            return f"{this} FILTER({where})"
    1033
    1034        agg = expression.this
    1035        agg_arg = agg.this
    1036        cond = expression.expression.this
    1037        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1038        return self.sql(agg)

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

    1040    def hint_sql(self, expression: exp.Hint) -> str:
    1041        if not self.QUERY_HINTS:
    1042            self.unsupported("Hints are not supported")
    1043            return ""
    1044
    1045        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

    1047    def index_sql(self, expression: exp.Index) -> str:
    1048        unique = "UNIQUE " if expression.args.get("unique") else ""
    1049        primary = "PRIMARY " if expression.args.get("primary") else ""
    1050        amp = "AMP " if expression.args.get("amp") else ""
    1051        name = self.sql(expression, "this")
    1052        name = f"{name} " if name else ""
    1053        table = self.sql(expression, "table")
    1054        table = f"{self.INDEX_ON} {table}" if table else ""
    1055        using = self.sql(expression, "using")
    1056        using = f" USING {using}" if using else ""
    1057        index = "INDEX " if not table else ""
    1058        columns = self.expressions(expression, key="columns", flat=True)
    1059        columns = f"({columns})" if columns else ""
    1060        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1061        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1062        where = self.sql(expression, "where")
    1063        return f"{unique}{primary}{amp}{index}{name}{table}{using}{columns}{partition_by}{where}"

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

    1065    def identifier_sql(self, expression: exp.Identifier) -> str:
    1066        text = expression.name
    1067        lower = text.lower()
    1068        text = lower if self.normalize and not expression.quoted else text
    1069        text = text.replace(self.IDENTIFIER_END, self._escaped_identifier_end)
    1070        if (
    1071            expression.quoted
    1072            or self.can_identify(text, self.identify)
    1073            or lower in self.RESERVED_KEYWORDS
    1074            or (not self.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1075        ):
    1076            text = f"{self.IDENTIFIER_START}{text}{self.IDENTIFIER_END}"
    1077        return text

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

    1079    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1080        input_format = self.sql(expression, "input_format")
    1081        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1082        output_format = self.sql(expression, "output_format")
    1083        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1084        return self.sep().join((input_format, output_format))

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

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

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

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

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

    1093    def properties_sql(self, expression: exp.Properties) -> str:
    1094        root_properties = []
    1095        with_properties = []
    1096
    1097        for p in expression.expressions:
    1098            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1099            if p_loc == exp.Properties.Location.POST_WITH:
    1100                with_properties.append(p)
    1101            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1102                root_properties.append(p)
    1103
    1104        return self.root_properties(
    1105            exp.Properties(expressions=root_properties)
    1106        ) + self.with_properties(exp.Properties(expressions=with_properties))

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

    1108    def root_properties(self, properties: exp.Properties) -> str:
    1109        if properties.expressions:
    1110            return self.sep() + self.expressions(properties, indent=False, sep=" ")
    1111        return ""

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

    1113    def properties(
    1114        self,
    1115        properties: exp.Properties,
    1116        prefix: str = "",
    1117        sep: str = ", ",
    1118        suffix: str = "",
    1119        wrapped: bool = True,
    1120    ) -> str:
    1121        if properties.expressions:
    1122            expressions = self.expressions(properties, sep=sep, indent=False)
    1123            if expressions:
    1124                expressions = self.wrap(expressions) if wrapped else expressions
    1125                return f"{prefix}{' ' if prefix and prefix != ' ' else ''}{expressions}{suffix}"
    1126        return ""

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

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

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

    1131    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1132        properties_locs = defaultdict(list)
    1133        for p in properties.expressions:
    1134            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1135            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1136                properties_locs[p_loc].append(p)
    1137            else:
    1138                self.unsupported(f"Unsupported property {p.key}")
    1139
    1140        return properties_locs

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

    1142    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1143        if isinstance(expression.this, exp.Dot):
    1144            return self.sql(expression, "this")
    1145        return f"'{expression.name}'" if string_key else expression.name

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

    1147    def property_sql(self, expression: exp.Property) -> str:
    1148        property_cls = expression.__class__
    1149        if property_cls == exp.Property:
    1150            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1151
    1152        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1153        if not property_name:
    1154            self.unsupported(f"Unsupported property {expression.key}")
    1155
    1156        return f"{property_name}={self.sql(expression, 'this')}"

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

    1158    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1159        options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1160        options = f" {options}" if options else ""
    1161        return f"LIKE {self.sql(expression, 'this')}{options}"

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

    1163    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1164        no = "NO " if expression.args.get("no") else ""
    1165        protection = " PROTECTION" if expression.args.get("protection") else ""
    1166        return f"{no}FALLBACK{protection}"

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

    1168    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1169        no = "NO " if expression.args.get("no") else ""
    1170        local = expression.args.get("local")
    1171        local = f"{local} " if local else ""
    1172        dual = "DUAL " if expression.args.get("dual") else ""
    1173        before = "BEFORE " if expression.args.get("before") else ""
    1174        after = "AFTER " if expression.args.get("after") else ""
    1175        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1177    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1178        freespace = self.sql(expression, "this")
    1179        percent = " PERCENT" if expression.args.get("percent") else ""
    1180        return f"FREESPACE={freespace}{percent}"

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

    1182    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1183        if expression.args.get("default"):
    1184            property = "DEFAULT"
    1185        elif expression.args.get("on"):
    1186            property = "ON"
    1187        else:
    1188            property = "OFF"
    1189        return f"CHECKSUM={property}"

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

    1191    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1192        if expression.args.get("no"):
    1193            return "NO MERGEBLOCKRATIO"
    1194        if expression.args.get("default"):
    1195            return "DEFAULT MERGEBLOCKRATIO"
    1196
    1197        percent = " PERCENT" if expression.args.get("percent") else ""
    1198        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1200    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1201        default = expression.args.get("default")
    1202        minimum = expression.args.get("minimum")
    1203        maximum = expression.args.get("maximum")
    1204        if default or minimum or maximum:
    1205            if default:
    1206                prop = "DEFAULT"
    1207            elif minimum:
    1208                prop = "MINIMUM"
    1209            else:
    1210                prop = "MAXIMUM"
    1211            return f"{prop} DATABLOCKSIZE"
    1212        units = expression.args.get("units")
    1213        units = f" {units}" if units else ""
    1214        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1216    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1217        autotemp = expression.args.get("autotemp")
    1218        always = expression.args.get("always")
    1219        default = expression.args.get("default")
    1220        manual = expression.args.get("manual")
    1221        never = expression.args.get("never")
    1222
    1223        if autotemp is not None:
    1224            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1225        elif always:
    1226            prop = "ALWAYS"
    1227        elif default:
    1228            prop = "DEFAULT"
    1229        elif manual:
    1230            prop = "MANUAL"
    1231        elif never:
    1232            prop = "NEVER"
    1233        return f"BLOCKCOMPRESSION={prop}"

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

    1235    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1236        no = expression.args.get("no")
    1237        no = " NO" if no else ""
    1238        concurrent = expression.args.get("concurrent")
    1239        concurrent = " CONCURRENT" if concurrent else ""
    1240
    1241        for_ = ""
    1242        if expression.args.get("for_all"):
    1243            for_ = " FOR ALL"
    1244        elif expression.args.get("for_insert"):
    1245            for_ = " FOR INSERT"
    1246        elif expression.args.get("for_none"):
    1247            for_ = " FOR NONE"
    1248        return f"WITH{no}{concurrent} ISOLATED LOADING{for_}"

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

    1250    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1251        if isinstance(expression.this, list):
    1252            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1253        if expression.this:
    1254            modulus = self.sql(expression, "this")
    1255            remainder = self.sql(expression, "expression")
    1256            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1257
    1258        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1259        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1260        return f"FROM ({from_expressions}) TO ({to_expressions})"

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

    1262    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1263        this = self.sql(expression, "this")
    1264
    1265        for_values_or_default = expression.expression
    1266        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1267            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1268        else:
    1269            for_values_or_default = " DEFAULT"
    1270
    1271        return f"PARTITION OF {this}{for_values_or_default}"

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

    1273    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1274        kind = expression.args.get("kind")
    1275        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1276        for_or_in = expression.args.get("for_or_in")
    1277        for_or_in = f" {for_or_in}" if for_or_in else ""
    1278        lock_type = expression.args.get("lock_type")
    1279        override = " OVERRIDE" if expression.args.get("override") else ""
    1280        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"

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

    1282    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1283        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1284        statistics = expression.args.get("statistics")
    1285        statistics_sql = ""
    1286        if statistics is not None:
    1287            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1288        return f"{data_sql}{statistics_sql}"

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

    1290    def insert_sql(self, expression: exp.Insert) -> str:
    1291        overwrite = expression.args.get("overwrite")
    1292
    1293        if isinstance(expression.this, exp.Directory):
    1294            this = " OVERWRITE" if overwrite else " INTO"
    1295        else:
    1296            this = " OVERWRITE TABLE" if overwrite else " INTO"
    1297
    1298        alternative = expression.args.get("alternative")
    1299        alternative = f" OR {alternative}" if alternative else ""
    1300        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1301
    1302        this = f"{this} {self.sql(expression, 'this')}"
    1303
    1304        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1305        partition_sql = (
    1306            f" {self.sql(expression, 'partition')}" if expression.args.get("partition") else ""
    1307        )
    1308        where = self.sql(expression, "where")
    1309        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1310        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1311        conflict = self.sql(expression, "conflict")
    1312        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1313        returning = self.sql(expression, "returning")
    1314
    1315        if self.RETURNING_END:
    1316            expression_sql = f"{expression_sql}{conflict}{returning}"
    1317        else:
    1318            expression_sql = f"{returning}{expression_sql}{conflict}"
    1319
    1320        sql = f"INSERT{alternative}{ignore}{this}{by_name}{exists}{partition_sql}{where}{expression_sql}"
    1321        return self.prepend_ctes(expression, sql)

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

    1323    def intersect_sql(self, expression: exp.Intersect) -> str:
    1324        return self.prepend_ctes(
    1325            expression,
    1326            self.set_operation(expression, self.intersect_op(expression)),
    1327        )

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

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

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

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

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

    1335    def kill_sql(self, expression: exp.Kill) -> str:
    1336        kind = self.sql(expression, "kind")
    1337        kind = f" {kind}" if kind else ""
    1338        this = self.sql(expression, "this")
    1339        this = f" {this}" if this else ""
    1340        return f"KILL{kind}{this}"

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

    1342    def pseudotype_sql(self, expression: exp.PseudoType) -> str:
    1343        return expression.name.upper()

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

    1345    def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str:
    1346        return expression.name.upper()

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

    1348    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1349        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1350        constraint = self.sql(expression, "constraint")
    1351        if constraint:
    1352            constraint = f"ON CONSTRAINT {constraint}"
    1353        key = self.expressions(expression, key="key", flat=True)
    1354        do = "" if expression.args.get("duplicate") else " DO "
    1355        nothing = "NOTHING" if expression.args.get("nothing") else ""
    1356        expressions = self.expressions(expression, flat=True)
    1357        set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1358        if expressions:
    1359            expressions = f"UPDATE {set_keyword}{expressions}"
    1360        return f"{self.seg(conflict)} {constraint}{key}{do}{nothing}{expressions}"

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

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

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

    1365    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1366        fields = expression.args.get("fields")
    1367        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1368        escaped = expression.args.get("escaped")
    1369        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1370        items = expression.args.get("collection_items")
    1371        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1372        keys = expression.args.get("map_keys")
    1373        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1374        lines = expression.args.get("lines")
    1375        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1376        null = expression.args.get("null")
    1377        null = f" NULL DEFINED AS {null}" if null else ""
    1378        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1383    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1384        this = f"{self.sql(expression, 'this')} INDEX"
    1385        target = self.sql(expression, "target")
    1386        target = f" FOR {target}" if target else ""
    1387        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1389    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1390        table = ".".join(
    1391            part
    1392            for part in [
    1393                self.sql(expression, "catalog"),
    1394                self.sql(expression, "db"),
    1395                self.sql(expression, "this"),
    1396            ]
    1397            if part
    1398        )
    1399
    1400        version = self.sql(expression, "version")
    1401        version = f" {version}" if version else ""
    1402        alias = self.sql(expression, "alias")
    1403        alias = f"{sep}{alias}" if alias else ""
    1404        hints = self.expressions(expression, key="hints", sep=" ")
    1405        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1406        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1407        pivots = f" {pivots}" if pivots else ""
    1408        joins = self.expressions(expression, key="joins", sep="", skip_first=True)
    1409        laterals = self.expressions(expression, key="laterals", sep="")
    1410
    1411        file_format = self.sql(expression, "format")
    1412        if file_format:
    1413            pattern = self.sql(expression, "pattern")
    1414            pattern = f", PATTERN => {pattern}" if pattern else ""
    1415            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    1416
    1417        index = self.sql(expression, "index")
    1418        index = f" AT {index}" if index else ""
    1419
    1420        ordinality = expression.args.get("ordinality") or ""
    1421        if ordinality:
    1422            ordinality = f" WITH ORDINALITY{alias}"
    1423            alias = ""
    1424
    1425        return f"{table}{version}{file_format}{alias}{index}{hints}{pivots}{joins}{laterals}{ordinality}"

def tablesample_sql( self, expression: sqlglot.expressions.TableSample, seed_prefix: str = 'SEED', sep=' AS ') -> str: View Source

    1427    def tablesample_sql(
    1428        self, expression: exp.TableSample, seed_prefix: str = "SEED", sep=" AS "
    1429    ) -> str:
    1430        if self.ALIAS_POST_TABLESAMPLE and expression.this.alias:
    1431            table = expression.this.copy()
    1432            table.set("alias", None)
    1433            this = self.sql(table)
    1434            alias = f"{sep}{self.sql(expression.this, 'alias')}"
    1435        else:
    1436            this = self.sql(expression, "this")
    1437            alias = ""
    1438
    1439        method = self.sql(expression, "method")
    1440        method = f"{method.upper()} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1441        numerator = self.sql(expression, "bucket_numerator")
    1442        denominator = self.sql(expression, "bucket_denominator")
    1443        field = self.sql(expression, "bucket_field")
    1444        field = f" ON {field}" if field else ""
    1445        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1446        percent = self.sql(expression, "percent")
    1447        percent = f"{percent} PERCENT" if percent else ""
    1448        rows = self.sql(expression, "rows")
    1449        rows = f"{rows} ROWS" if rows else ""
    1450
    1451        size = self.sql(expression, "size")
    1452        if size and self.TABLESAMPLE_SIZE_IS_PERCENT:
    1453            size = f"{size} PERCENT"
    1454
    1455        seed = self.sql(expression, "seed")
    1456        seed = f" {seed_prefix} ({seed})" if seed else ""
    1457        kind = expression.args.get("kind", "TABLESAMPLE")
    1458
    1459        expr = f"{bucket}{percent}{rows}{size}"
    1460        if self.TABLESAMPLE_REQUIRES_PARENS:
    1461            expr = f"({expr})"
    1462
    1463        return f"{this} {kind} {method}{expr}{seed}{alias}"

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

    1465    def pivot_sql(self, expression: exp.Pivot) -> str:
    1466        expressions = self.expressions(expression, flat=True)
    1467
    1468        if expression.this:
    1469            this = self.sql(expression, "this")
    1470            if not expressions:
    1471                return f"UNPIVOT {this}"
    1472
    1473            on = f"{self.seg('ON')} {expressions}"
    1474            using = self.expressions(expression, key="using", flat=True)
    1475            using = f"{self.seg('USING')} {using}" if using else ""
    1476            group = self.sql(expression, "group")
    1477            return f"PIVOT {this}{on}{using}{group}"
    1478
    1479        alias = self.sql(expression, "alias")
    1480        alias = f" AS {alias}" if alias else ""
    1481        unpivot = expression.args.get("unpivot")
    1482        direction = "UNPIVOT" if unpivot else "PIVOT"
    1483        field = self.sql(expression, "field")
    1484        include_nulls = expression.args.get("include_nulls")
    1485        if include_nulls is not None:
    1486            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    1487        else:
    1488            nulls = ""
    1489        return f"{direction}{nulls}({expressions} FOR {field}){alias}"

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

    1491    def version_sql(self, expression: exp.Version) -> str:
    1492        this = f"FOR {expression.name}"
    1493        kind = expression.text("kind")
    1494        expr = self.sql(expression, "expression")
    1495        return f"{this} {kind} {expr}"

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

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

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

    1500    def update_sql(self, expression: exp.Update) -> str:
    1501        this = self.sql(expression, "this")
    1502        set_sql = self.expressions(expression, flat=True)
    1503        from_sql = self.sql(expression, "from")
    1504        where_sql = self.sql(expression, "where")
    1505        returning = self.sql(expression, "returning")
    1506        order = self.sql(expression, "order")
    1507        limit = self.sql(expression, "limit")
    1508        if self.RETURNING_END:
    1509            expression_sql = f"{from_sql}{where_sql}{returning}"
    1510        else:
    1511            expression_sql = f"{returning}{from_sql}{where_sql}"
    1512        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    1513        return self.prepend_ctes(expression, sql)

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

    1515    def values_sql(self, expression: exp.Values) -> str:
    1516        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    1517        if self.VALUES_AS_TABLE or not expression.find_ancestor(exp.From, exp.Join):
    1518            args = self.expressions(expression)
    1519            alias = self.sql(expression, "alias")
    1520            values = f"VALUES{self.seg('')}{args}"
    1521            values = (
    1522                f"({values})"
    1523                if self.WRAP_DERIVED_VALUES and (alias or isinstance(expression.parent, exp.From))
    1524                else values
    1525            )
    1526            return f"{values} AS {alias}" if alias else values
    1527
    1528        # Converts `VALUES...` expression into a series of select unions.
    1529        alias_node = expression.args.get("alias")
    1530        column_names = alias_node and alias_node.columns
    1531
    1532        selects: t.List[exp.Subqueryable] = []
    1533
    1534        for i, tup in enumerate(expression.expressions):
    1535            row = tup.expressions
    1536
    1537            if i == 0 and column_names:
    1538                row = [
    1539                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    1540                ]
    1541
    1542            selects.append(exp.Select(expressions=row))
    1543
    1544        if self.pretty:
    1545            # This may result in poor performance for large-cardinality `VALUES` tables, due to
    1546            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
    1547            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
    1548            subqueryable = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
    1549            return self.subquery_sql(
    1550                subqueryable.subquery(alias_node and alias_node.this, copy=False)
    1551            )
    1552
    1553        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
    1554        unions = " UNION ALL ".join(self.sql(select) for select in selects)
    1555        return f"({unions}){alias}"

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

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

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

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

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

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

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

    1568    def group_sql(self, expression: exp.Group) -> str:
    1569        group_by = self.op_expressions("GROUP BY", expression)
    1570
    1571        if expression.args.get("all"):
    1572            return f"{group_by} ALL"
    1573
    1574        grouping_sets = self.expressions(expression, key="grouping_sets", indent=False)
    1575        grouping_sets = (
    1576            f"{self.seg('GROUPING SETS')} {self.wrap(grouping_sets)}" if grouping_sets else ""
    1577        )
    1578
    1579        cube = expression.args.get("cube", [])
    1580        if seq_get(cube, 0) is True:
    1581            return f"{group_by}{self.seg('WITH CUBE')}"
    1582        else:
    1583            cube_sql = self.expressions(expression, key="cube", indent=False)
    1584            cube_sql = f"{self.seg('CUBE')} {self.wrap(cube_sql)}" if cube_sql else ""
    1585
    1586        rollup = expression.args.get("rollup", [])
    1587        if seq_get(rollup, 0) is True:
    1588            return f"{group_by}{self.seg('WITH ROLLUP')}"
    1589        else:
    1590            rollup_sql = self.expressions(expression, key="rollup", indent=False)
    1591            rollup_sql = f"{self.seg('ROLLUP')} {self.wrap(rollup_sql)}" if rollup_sql else ""
    1592
    1593        groupings = csv(
    1594            grouping_sets,
    1595            cube_sql,
    1596            rollup_sql,
    1597            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    1598            sep=self.GROUPINGS_SEP,
    1599        )
    1600
    1601        if expression.args.get("expressions") and groupings:
    1602            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    1603
    1604        return f"{group_by}{groupings}"

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

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

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

    1610    def connect_sql(self, expression: exp.Connect) -> str:
    1611        start = self.sql(expression, "start")
    1612        start = self.seg(f"START WITH {start}") if start else ""
    1613        connect = self.sql(expression, "connect")
    1614        connect = self.seg(f"CONNECT BY {connect}")
    1615        return start + connect

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

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

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

    1620    def join_sql(self, expression: exp.Join) -> str:
    1621        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    1622            side = None
    1623        else:
    1624            side = expression.side
    1625
    1626        op_sql = " ".join(
    1627            op
    1628            for op in (
    1629                expression.method,
    1630                "GLOBAL" if expression.args.get("global") else None,
    1631                side,
    1632                expression.kind,
    1633                expression.hint if self.JOIN_HINTS else None,
    1634            )
    1635            if op
    1636        )
    1637        on_sql = self.sql(expression, "on")
    1638        using = expression.args.get("using")
    1639
    1640        if not on_sql and using:
    1641            on_sql = csv(*(self.sql(column) for column in using))
    1642
    1643        this_sql = self.sql(expression, "this")
    1644
    1645        if on_sql:
    1646            on_sql = self.indent(on_sql, skip_first=True)
    1647            space = self.seg(" " * self.pad) if self.pretty else " "
    1648            if using:
    1649                on_sql = f"{space}USING ({on_sql})"
    1650            else:
    1651                on_sql = f"{space}ON {on_sql}"
    1652        elif not op_sql:
    1653            return f", {this_sql}"
    1654
    1655        op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    1656        return f"{self.seg(op_sql)} {this_sql}{on_sql}"

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

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

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

    1663    def lateral_sql(self, expression: exp.Lateral) -> str:
    1664        this = self.sql(expression, "this")
    1665
    1666        if expression.args.get("view"):
    1667            alias = expression.args["alias"]
    1668            columns = self.expressions(alias, key="columns", flat=True)
    1669            table = f" {alias.name}" if alias.name else ""
    1670            columns = f" AS {columns}" if columns else ""
    1671            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    1672            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    1673
    1674        alias = self.sql(expression, "alias")
    1675        alias = f" AS {alias}" if alias else ""
    1676        return f"LATERAL {this}{alias}"

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

    1678    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    1679        this = self.sql(expression, "this")
    1680        args = ", ".join(
    1681            self.sql(self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e)
    1682            for e in (expression.args.get(k) for k in ("offset", "expression"))
    1683            if e
    1684        )
    1685        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args}"

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

    1687    def offset_sql(self, expression: exp.Offset) -> str:
    1688        this = self.sql(expression, "this")
    1689        expression = expression.expression
    1690        expression = (
    1691            self._simplify_unless_literal(expression) if self.LIMIT_ONLY_LITERALS else expression
    1692        )
    1693        return f"{this}{self.seg('OFFSET')} {self.sql(expression)}"

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

    1695    def setitem_sql(self, expression: exp.SetItem) -> str:
    1696        kind = self.sql(expression, "kind")
    1697        kind = f"{kind} " if kind else ""
    1698        this = self.sql(expression, "this")
    1699        expressions = self.expressions(expression)
    1700        collate = self.sql(expression, "collate")
    1701        collate = f" COLLATE {collate}" if collate else ""
    1702        global_ = "GLOBAL " if expression.args.get("global") else ""
    1703        return f"{global_}{kind}{this}{expressions}{collate}"

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

    1705    def set_sql(self, expression: exp.Set) -> str:
    1706        expressions = (
    1707            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    1708        )
    1709        tag = " TAG" if expression.args.get("tag") else ""
    1710        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"

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

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

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

    1715    def lock_sql(self, expression: exp.Lock) -> str:
    1716        if not self.LOCKING_READS_SUPPORTED:
    1717            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    1718            return ""
    1719
    1720        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    1721        expressions = self.expressions(expression, flat=True)
    1722        expressions = f" OF {expressions}" if expressions else ""
    1723        wait = expression.args.get("wait")
    1724
    1725        if wait is not None:
    1726            if isinstance(wait, exp.Literal):
    1727                wait = f" WAIT {self.sql(wait)}"
    1728            else:
    1729                wait = " NOWAIT" if wait else " SKIP LOCKED"
    1730
    1731        return f"{lock_type}{expressions}{wait or ''}"

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

    1733    def literal_sql(self, expression: exp.Literal) -> str:
    1734        text = expression.this or ""
    1735        if expression.is_string:
    1736            text = f"{self.QUOTE_START}{self.escape_str(text)}{self.QUOTE_END}"
    1737        return text

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

    1739    def escape_str(self, text: str) -> str:
    1740        text = text.replace(self.QUOTE_END, self._escaped_quote_end)
    1741        if self.INVERSE_ESCAPE_SEQUENCES:
    1742            text = "".join(self.INVERSE_ESCAPE_SEQUENCES.get(ch, ch) for ch in text)
    1743        elif self.pretty:
    1744            text = text.replace("\n", self.SENTINEL_LINE_BREAK)
    1745        return text

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

    1747    def loaddata_sql(self, expression: exp.LoadData) -> str:
    1748        local = " LOCAL" if expression.args.get("local") else ""
    1749        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    1750        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    1751        this = f" INTO TABLE {self.sql(expression, 'this')}"
    1752        partition = self.sql(expression, "partition")
    1753        partition = f" {partition}" if partition else ""
    1754        input_format = self.sql(expression, "input_format")
    1755        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    1756        serde = self.sql(expression, "serde")
    1757        serde = f" SERDE {serde}" if serde else ""
    1758        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    1760    def null_sql(self, *_) -> str:
    1761        return "NULL"

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

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

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

    1766    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    1767        this = self.sql(expression, "this")
    1768        this = f"{this} " if this else this
    1769        return self.op_expressions(f"{this}ORDER BY", expression, flat=this or flat)  # type: ignore

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

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

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

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

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

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

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

    1780    def ordered_sql(self, expression: exp.Ordered) -> str:
    1781        desc = expression.args.get("desc")
    1782        asc = not desc
    1783
    1784        nulls_first = expression.args.get("nulls_first")
    1785        nulls_last = not nulls_first
    1786        nulls_are_large = self.NULL_ORDERING == "nulls_are_large"
    1787        nulls_are_small = self.NULL_ORDERING == "nulls_are_small"
    1788        nulls_are_last = self.NULL_ORDERING == "nulls_are_last"
    1789
    1790        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
    1791        nulls_sort_change = ""
    1792        if nulls_first and (
    1793            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    1794        ):
    1795            nulls_sort_change = " NULLS FIRST"
    1796        elif (
    1797            nulls_last
    1798            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    1799            and not nulls_are_last
    1800        ):
    1801            nulls_sort_change = " NULLS LAST"
    1802
    1803        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    1804            self.unsupported(
    1805                "Sorting in an ORDER BY on NULLS FIRST/NULLS LAST is not supported by this dialect"
    1806            )
    1807            nulls_sort_change = ""
    1808
    1809        return f"{self.sql(expression, 'this')}{sort_order}{nulls_sort_change}"

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

    1811    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    1812        partition = self.partition_by_sql(expression)
    1813        order = self.sql(expression, "order")
    1814        measures = self.expressions(expression, key="measures")
    1815        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    1816        rows = self.sql(expression, "rows")
    1817        rows = self.seg(rows) if rows else ""
    1818        after = self.sql(expression, "after")
    1819        after = self.seg(after) if after else ""
    1820        pattern = self.sql(expression, "pattern")
    1821        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    1822        definition_sqls = [
    1823            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    1824            for definition in expression.args.get("define", [])
    1825        ]
    1826        definitions = self.expressions(sqls=definition_sqls)
    1827        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    1828        body = "".join(
    1829            (
    1830                partition,
    1831                order,
    1832                measures,
    1833                rows,
    1834                after,
    1835                pattern,
    1836                define,
    1837            )
    1838        )
    1839        alias = self.sql(expression, "alias")
    1840        alias = f" {alias}" if alias else ""
    1841        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    1843    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    1844        limit: t.Optional[exp.Fetch | exp.Limit] = expression.args.get("limit")
    1845
    1846        # If the limit is generated as TOP, we need to ensure it's not generated twice
    1847        with_offset_limit_modifiers = not isinstance(limit, exp.Limit) or not self.LIMIT_IS_TOP
    1848
    1849        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    1850            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    1851        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    1852            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    1853
    1854        fetch = isinstance(limit, exp.Fetch)
    1855
    1856        offset_limit_modifiers = (
    1857            self.offset_limit_modifiers(expression, fetch, limit)
    1858            if with_offset_limit_modifiers
    1859            else []
    1860        )
    1861
    1862        return csv(
    1863            *sqls,
    1864            *[self.sql(join) for join in expression.args.get("joins") or []],
    1865            self.sql(expression, "connect"),
    1866            self.sql(expression, "match"),
    1867            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    1868            self.sql(expression, "where"),
    1869            self.sql(expression, "group"),
    1870            self.sql(expression, "having"),
    1871            *self.after_having_modifiers(expression),
    1872            self.sql(expression, "order"),
    1873            *offset_limit_modifiers,
    1874            *self.after_limit_modifiers(expression),
    1875            sep="",
    1876        )

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

    1878    def offset_limit_modifiers(
    1879        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    1880    ) -> t.List[str]:
    1881        return [
    1882            self.sql(expression, "offset") if fetch else self.sql(limit),
    1883            self.sql(limit) if fetch else self.sql(expression, "offset"),
    1884        ]

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

    1886    def after_having_modifiers(self, expression: exp.Expression) -> t.List[str]:
    1887        return [
    1888            self.sql(expression, "qualify"),
    1889            self.seg("WINDOW ") + self.expressions(expression, key="windows", flat=True)
    1890            if expression.args.get("windows")
    1891            else "",
    1892            self.sql(expression, "distribute"),
    1893            self.sql(expression, "sort"),
    1894            self.sql(expression, "cluster"),
    1895        ]

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

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

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

    1902    def select_sql(self, expression: exp.Select) -> str:
    1903        hint = self.sql(expression, "hint")
    1904        distinct = self.sql(expression, "distinct")
    1905        distinct = f" {distinct}" if distinct else ""
    1906        kind = self.sql(expression, "kind").upper()
    1907        limit = expression.args.get("limit")
    1908        top = (
    1909            self.limit_sql(limit, top=True)
    1910            if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP
    1911            else ""
    1912        )
    1913
    1914        expressions = self.expressions(expression)
    1915
    1916        if kind:
    1917            if kind in self.SELECT_KINDS:
    1918                kind = f" AS {kind}"
    1919            else:
    1920                if kind == "STRUCT":
    1921                    expressions = self.expressions(
    1922                        sqls=[
    1923                            self.sql(
    1924                                exp.Struct(
    1925                                    expressions=[
    1926                                        exp.column(e.output_name).eq(
    1927                                            e.this if isinstance(e, exp.Alias) else e
    1928                                        )
    1929                                        for e in expression.expressions
    1930                                    ]
    1931                                )
    1932                            )
    1933                        ]
    1934                    )
    1935                kind = ""
    1936
    1937        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    1938        sql = self.query_modifiers(
    1939            expression,
    1940            f"SELECT{top}{hint}{distinct}{kind}{expressions}",
    1941            self.sql(expression, "into", comment=False),
    1942            self.sql(expression, "from", comment=False),
    1943        )
    1944        return self.prepend_ctes(expression, sql)

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

    1946    def schema_sql(self, expression: exp.Schema) -> str:
    1947        this = self.sql(expression, "this")
    1948        sql = self.schema_columns_sql(expression)
    1949        return f"{this} {sql}" if this and sql else this or sql

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

    1951    def schema_columns_sql(self, expression: exp.Schema) -> str:
    1952        if expression.expressions:
    1953            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    1954        return ""

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

    1956    def star_sql(self, expression: exp.Star) -> str:
    1957        except_ = self.expressions(expression, key="except", flat=True)
    1958        except_ = f"{self.seg(self.STAR_MAPPING['except'])} ({except_})" if except_ else ""
    1959        replace = self.expressions(expression, key="replace", flat=True)
    1960        replace = f"{self.seg(self.STAR_MAPPING['replace'])} ({replace})" if replace else ""
    1961        return f"*{except_}{replace}"

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

    1963    def parameter_sql(self, expression: exp.Parameter) -> str:
    1964        this = self.sql(expression, "this")
    1965        return f"{self.PARAMETER_TOKEN}{this}" if self.SUPPORTS_PARAMETERS else this

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

    1967    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    1968        this = self.sql(expression, "this")
    1969        kind = expression.text("kind")
    1970        if kind:
    1971            kind = f"{kind}."
    1972        return f"@@{kind}{this}"

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

    1974    def placeholder_sql(self, expression: exp.Placeholder) -> str:
    1975        return f":{expression.name}" if expression.name else "?"

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

    1977    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    1978        alias = self.sql(expression, "alias")
    1979        alias = f"{sep}{alias}" if alias else ""
    1980
    1981        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1982        pivots = f" {pivots}" if pivots else ""
    1983
    1984        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    1985        return self.prepend_ctes(expression, sql)

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

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

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

    1991    def union_sql(self, expression: exp.Union) -> str:
    1992        return self.prepend_ctes(
    1993            expression,
    1994            self.set_operation(expression, self.union_op(expression)),
    1995        )

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

    1997    def union_op(self, expression: exp.Union) -> str:
    1998        kind = " DISTINCT" if self.EXPLICIT_UNION else ""
    1999        kind = kind if expression.args.get("distinct") else " ALL"
    2000        by_name = " BY NAME" if expression.args.get("by_name") else ""
    2001        return f"UNION{kind}{by_name}"

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

    2003    def unnest_sql(self, expression: exp.Unnest) -> str:
    2004        args = self.expressions(expression, flat=True)
    2005
    2006        alias = expression.args.get("alias")
    2007        offset = expression.args.get("offset")
    2008
    2009        if self.UNNEST_WITH_ORDINALITY:
    2010            if alias and isinstance(offset, exp.Expression):
    2011                alias.append("columns", offset)
    2012
    2013        if alias and self.UNNEST_COLUMN_ONLY:
    2014            columns = alias.columns
    2015            alias = self.sql(columns[0]) if columns else ""
    2016        else:
    2017            alias = self.sql(alias)
    2018
    2019        alias = f" AS {alias}" if alias else alias
    2020        if self.UNNEST_WITH_ORDINALITY:
    2021            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2022        else:
    2023            if isinstance(offset, exp.Expression):
    2024                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2025            elif offset:
    2026                suffix = f"{alias} WITH OFFSET"
    2027            else:
    2028                suffix = alias
    2029
    2030        return f"UNNEST({args}){suffix}"

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

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

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

    2036    def window_sql(self, expression: exp.Window) -> str:
    2037        this = self.sql(expression, "this")
    2038        partition = self.partition_by_sql(expression)
    2039        order = expression.args.get("order")
    2040        order = self.order_sql(order, flat=True) if order else ""
    2041        spec = self.sql(expression, "spec")
    2042        alias = self.sql(expression, "alias")
    2043        over = self.sql(expression, "over") or "OVER"
    2044
    2045        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2046
    2047        first = expression.args.get("first")
    2048        if first is None:
    2049            first = ""
    2050        else:
    2051            first = "FIRST" if first else "LAST"
    2052
    2053        if not partition and not order and not spec and alias:
    2054            return f"{this} {alias}"
    2055
    2056        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    2057        return f"{this} ({args})"

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

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

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

    2063    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2064        kind = self.sql(expression, "kind")
    2065        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2066        end = (
    2067            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2068            or "CURRENT ROW"
    2069        )
    2070        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    2077    def between_sql(self, expression: exp.Between) -> str:
    2078        this = self.sql(expression, "this")
    2079        low = self.sql(expression, "low")
    2080        high = self.sql(expression, "high")
    2081        return f"{this} BETWEEN {low} AND {high}"

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

    2083    def bracket_sql(self, expression: exp.Bracket) -> str:
    2084        expressions = apply_index_offset(expression.this, expression.expressions, self.INDEX_OFFSET)
    2085        expressions_sql = ", ".join(self.sql(e) for e in expressions)
    2086
    2087        return f"{self.sql(expression, 'this')}[{expressions_sql}]"

def safebracket_sql(self, expression: sqlglot.expressions.SafeBracket) -> str: View Source

    2089    def safebracket_sql(self, expression: exp.SafeBracket) -> str:
    2090        return self.bracket_sql(expression)

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

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

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

    2095    def any_sql(self, expression: exp.Any) -> str:
    2096        this = self.sql(expression, "this")
    2097        if isinstance(expression.this, exp.Subqueryable):
    2098            this = self.wrap(this)
    2099        return f"ANY {this}"

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

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

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

    2104    def case_sql(self, expression: exp.Case) -> str:
    2105        this = self.sql(expression, "this")
    2106        statements = [f"CASE {this}" if this else "CASE"]
    2107
    2108        for e in expression.args["ifs"]:
    2109            statements.append(f"WHEN {self.sql(e, 'this')}")
    2110            statements.append(f"THEN {self.sql(e, 'true')}")
    2111
    2112        default = self.sql(expression, "default")
    2113
    2114        if default:
    2115            statements.append(f"ELSE {default}")
    2116
    2117        statements.append("END")
    2118
    2119        if self.pretty and self.text_width(statements) > self.max_text_width:
    2120            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2121
    2122        return " ".join(statements)

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

    2124    def constraint_sql(self, expression: exp.Constraint) -> str:
    2125        this = self.sql(expression, "this")
    2126        expressions = self.expressions(expression, flat=True)
    2127        return f"CONSTRAINT {this} {expressions}"

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

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

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

    2134    def extract_sql(self, expression: exp.Extract) -> str:
    2135        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2136        expression_sql = self.sql(expression, "expression")
    2137        return f"EXTRACT({this} FROM {expression_sql})"

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

    2139    def trim_sql(self, expression: exp.Trim) -> str:
    2140        trim_type = self.sql(expression, "position")
    2141
    2142        if trim_type == "LEADING":
    2143            return self.func("LTRIM", expression.this)
    2144        elif trim_type == "TRAILING":
    2145            return self.func("RTRIM", expression.this)
    2146        else:
    2147            return self.func("TRIM", expression.this, expression.expression)

def safeconcat_sql(self, expression: sqlglot.expressions.SafeConcat) -> str: View Source

    2149    def safeconcat_sql(self, expression: exp.SafeConcat) -> str:
    2150        expressions = expression.expressions
    2151        if self.STRICT_STRING_CONCAT:
    2152            expressions = (exp.cast(e, "text") for e in expressions)
    2153        return self.func("CONCAT", *expressions)

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

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

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

    2159    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2160        expressions = self.expressions(expression, flat=True)
    2161        reference = self.sql(expression, "reference")
    2162        reference = f" {reference}" if reference else ""
    2163        delete = self.sql(expression, "delete")
    2164        delete = f" ON DELETE {delete}" if delete else ""
    2165        update = self.sql(expression, "update")
    2166        update = f" ON UPDATE {update}" if update else ""
    2167        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"

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

    2169    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2170        expressions = self.expressions(expression, flat=True)
    2171        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2172        options = f" {options}" if options else ""
    2173        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

    2183    def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str:
    2184        return f"{self.sql(expression, 'this')}: {self.sql(expression, 'expression')}"

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

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

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

    2189    def jsonobject_sql(self, expression: exp.JSONObject) -> str:
    2190        null_handling = expression.args.get("null_handling")
    2191        null_handling = f" {null_handling}" if null_handling else ""
    2192        unique_keys = expression.args.get("unique_keys")
    2193        if unique_keys is not None:
    2194            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2195        else:
    2196            unique_keys = ""
    2197        return_type = self.sql(expression, "return_type")
    2198        return_type = f" RETURNING {return_type}" if return_type else ""
    2199        encoding = self.sql(expression, "encoding")
    2200        encoding = f" ENCODING {encoding}" if encoding else ""
    2201        return self.func(
    2202            "JSON_OBJECT",
    2203            *expression.expressions,
    2204            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2205        )

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

    2207    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2208        null_handling = expression.args.get("null_handling")
    2209        null_handling = f" {null_handling}" if null_handling else ""
    2210        return_type = self.sql(expression, "return_type")
    2211        return_type = f" RETURNING {return_type}" if return_type else ""
    2212        strict = " STRICT" if expression.args.get("strict") else ""
    2213        return self.func(
    2214            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2215        )

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

    2217    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2218        this = self.sql(expression, "this")
    2219        order = self.sql(expression, "order")
    2220        null_handling = expression.args.get("null_handling")
    2221        null_handling = f" {null_handling}" if null_handling else ""
    2222        return_type = self.sql(expression, "return_type")
    2223        return_type = f" RETURNING {return_type}" if return_type else ""
    2224        strict = " STRICT" if expression.args.get("strict") else ""
    2225        return self.func(
    2226            "JSON_ARRAYAGG",
    2227            this,
    2228            suffix=f"{order}{null_handling}{return_type}{strict})",
    2229        )

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

    2231    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2232        path = self.sql(expression, "path")
    2233        path = f" PATH {path}" if path else ""
    2234        nested_schema = self.sql(expression, "nested_schema")
    2235
    2236        if nested_schema:
    2237            return f"NESTED{path} {nested_schema}"
    2238
    2239        this = self.sql(expression, "this")
    2240        kind = self.sql(expression, "kind")
    2241        kind = f" {kind}" if kind else ""
    2242        return f"{this}{kind}{path}"

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

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

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

    2247    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    2248        this = self.sql(expression, "this")
    2249        path = self.sql(expression, "path")
    2250        path = f", {path}" if path else ""
    2251        error_handling = expression.args.get("error_handling")
    2252        error_handling = f" {error_handling}" if error_handling else ""
    2253        empty_handling = expression.args.get("empty_handling")
    2254        empty_handling = f" {empty_handling}" if empty_handling else ""
    2255        schema = self.sql(expression, "schema")
    2256        return self.func(
    2257            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    2258        )

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

    2260    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    2261        this = self.sql(expression, "this")
    2262        kind = self.sql(expression, "kind")
    2263        path = self.sql(expression, "path")
    2264        path = f" {path}" if path else ""
    2265        as_json = " AS JSON" if expression.args.get("as_json") else ""
    2266        return f"{this} {kind}{path}{as_json}"

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

    2268    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    2269        this = self.sql(expression, "this")
    2270        path = self.sql(expression, "path")
    2271        path = f", {path}" if path else ""
    2272        expressions = self.expressions(expression)
    2273        with_ = (
    2274            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2275            if expressions
    2276            else ""
    2277        )
    2278        return f"OPENJSON({this}{path}){with_}"

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

    2280    def in_sql(self, expression: exp.In) -> str:
    2281        query = expression.args.get("query")
    2282        unnest = expression.args.get("unnest")
    2283        field = expression.args.get("field")
    2284        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    2285
    2286        if query:
    2287            in_sql = self.wrap(query)
    2288        elif unnest:
    2289            in_sql = self.in_unnest_op(unnest)
    2290        elif field:
    2291            in_sql = self.sql(field)
    2292        else:
    2293            in_sql = f"({self.expressions(expression, flat=True)})"
    2294
    2295        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    2300    def interval_sql(self, expression: exp.Interval) -> str:
    2301        unit = self.sql(expression, "unit")
    2302        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    2303            unit = self.TIME_PART_SINGULARS.get(unit.lower(), unit)
    2304        unit = f" {unit}" if unit else ""
    2305
    2306        if self.SINGLE_STRING_INTERVAL:
    2307            this = expression.this.name if expression.this else ""
    2308            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    2309
    2310        this = self.sql(expression, "this")
    2311        if this:
    2312            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    2313            this = f" {this}" if unwrapped else f" ({this})"
    2314
    2315        return f"INTERVAL{this}{unit}"

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

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

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

    2320    def reference_sql(self, expression: exp.Reference) -> str:
    2321        this = self.sql(expression, "this")
    2322        expressions = self.expressions(expression, flat=True)
    2323        expressions = f"({expressions})" if expressions else ""
    2324        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2325        options = f" {options}" if options else ""
    2326        return f"REFERENCES {this}{expressions}{options}"

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

    2328    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    2329        return self.func(expression.name, *expression.expressions)

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

    2331    def paren_sql(self, expression: exp.Paren) -> str:
    2332        if isinstance(expression.unnest(), exp.Select):
    2333            sql = self.wrap(expression)
    2334        else:
    2335            sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
    2336            sql = f"({sql}{self.seg(')', sep='')}"
    2337
    2338        return self.prepend_ctes(expression, sql)

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

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

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

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

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

    2349    def alias_sql(self, expression: exp.Alias) -> str:
    2350        alias = self.sql(expression, "alias")
    2351        alias = f" AS {alias}" if alias else ""
    2352        return f"{self.sql(expression, 'this')}{alias}"

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

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

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

    2357    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    2358        this = self.sql(expression, "this")
    2359        zone = self.sql(expression, "zone")
    2360        return f"{this} AT TIME ZONE {zone}"

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

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

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

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

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

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

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

    2371    def connector_sql(self, expression: exp.Connector, op: str) -> str:
    2372        if not self.pretty:
    2373            return self.binary(expression, op)
    2374
    2375        sqls = tuple(
    2376            self.maybe_comment(self.sql(e), e, e.parent.comments or []) if i != 1 else self.sql(e)
    2377            for i, e in enumerate(expression.flatten(unnest=False))
    2378        )
    2379
    2380        sep = "\n" if self.text_width(sqls) > self.max_text_width else " "
    2381        return f"{sep}{op} ".join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

    2401    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    2402        format_sql = self.sql(expression, "format")
    2403        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    2404        to_sql = self.sql(expression, "to")
    2405        to_sql = f" {to_sql}" if to_sql else ""
    2406        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{format_sql})"

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

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

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

    2412    def collate_sql(self, expression: exp.Collate) -> str:
    2413        if self.COLLATE_IS_FUNC:
    2414            return self.function_fallback_sql(expression)
    2415        return self.binary(expression, "COLLATE")

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

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

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

    2420    def comment_sql(self, expression: exp.Comment) -> str:
    2421        this = self.sql(expression, "this")
    2422        kind = expression.args["kind"]
    2423        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    2424        expression_sql = self.sql(expression, "expression")
    2425        return f"COMMENT{exists_sql}ON {kind} {this} IS {expression_sql}"

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

    2427    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    2428        this = self.sql(expression, "this")
    2429        delete = " DELETE" if expression.args.get("delete") else ""
    2430        recompress = self.sql(expression, "recompress")
    2431        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    2432        to_disk = self.sql(expression, "to_disk")
    2433        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    2434        to_volume = self.sql(expression, "to_volume")
    2435        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    2436        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    2438    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    2439        where = self.sql(expression, "where")
    2440        group = self.sql(expression, "group")
    2441        aggregates = self.expressions(expression, key="aggregates")
    2442        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    2443
    2444        if not (where or group or aggregates) and len(expression.expressions) == 1:
    2445            return f"TTL {self.expressions(expression, flat=True)}"
    2446
    2447        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    2452    def commit_sql(self, expression: exp.Commit) -> str:
    2453        chain = expression.args.get("chain")
    2454        if chain is not None:
    2455            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    2456
    2457        return f"COMMIT{chain or ''}"

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

    2459    def rollback_sql(self, expression: exp.Rollback) -> str:
    2460        savepoint = expression.args.get("savepoint")
    2461        savepoint = f" TO {savepoint}" if savepoint else ""
    2462        return f"ROLLBACK{savepoint}"

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

    2464    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    2465        this = self.sql(expression, "this")
    2466
    2467        dtype = self.sql(expression, "dtype")
    2468        if dtype:
    2469            collate = self.sql(expression, "collate")
    2470            collate = f" COLLATE {collate}" if collate else ""
    2471            using = self.sql(expression, "using")
    2472            using = f" USING {using}" if using else ""
    2473            return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}"
    2474
    2475        default = self.sql(expression, "default")
    2476        if default:
    2477            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    2478
    2479        if not expression.args.get("drop"):
    2480            self.unsupported("Unsupported ALTER COLUMN syntax")
    2481
    2482        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    2484    def renametable_sql(self, expression: exp.RenameTable) -> str:
    2485        if not self.RENAME_TABLE_WITH_DB:
    2486            # Remove db from tables
    2487            expression = expression.transform(
    2488                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    2489            )
    2490        this = self.sql(expression, "this")
    2491        return f"RENAME TO {this}"

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

    2493    def altertable_sql(self, expression: exp.AlterTable) -> str:
    2494        actions = expression.args["actions"]
    2495
    2496        if isinstance(actions[0], exp.ColumnDef):
    2497            if self.ALTER_TABLE_ADD_COLUMN_KEYWORD:
    2498                actions = self.expressions(
    2499                    expression,
    2500                    key="actions",
    2501                    prefix="ADD COLUMN ",
    2502                )
    2503            else:
    2504                actions = f"ADD {self.expressions(expression, key='actions')}"
    2505        elif isinstance(actions[0], exp.Schema):
    2506            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    2507        elif isinstance(actions[0], exp.Delete):
    2508            actions = self.expressions(expression, key="actions", flat=True)
    2509        else:
    2510            actions = self.expressions(expression, key="actions", flat=True)
    2511
    2512        exists = " IF EXISTS" if expression.args.get("exists") else ""
    2513        only = " ONLY" if expression.args.get("only") else ""
    2514        return f"ALTER TABLE{exists}{only} {self.sql(expression, 'this')} {actions}"

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

    2516    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    2517        expressions = self.expressions(expression)
    2518        exists = " IF EXISTS " if expression.args.get("exists") else " "
    2519        return f"DROP{exists}{expressions}"

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

    2521    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
    2522        this = self.sql(expression, "this")
    2523        expression_ = self.sql(expression, "expression")
    2524        add_constraint = f"ADD CONSTRAINT {this}" if this else "ADD"
    2525
    2526        enforced = expression.args.get("enforced")
    2527        if enforced is not None:
    2528            return f"{add_constraint} CHECK ({expression_}){' ENFORCED' if enforced else ''}"
    2529
    2530        return f"{add_constraint} {expression_}"

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

    2532    def distinct_sql(self, expression: exp.Distinct) -> str:
    2533        this = self.expressions(expression, flat=True)
    2534        this = f" {this}" if this else ""
    2535
    2536        on = self.sql(expression, "on")
    2537        on = f" ON {on}" if on else ""
    2538        return f"DISTINCT{this}{on}"

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

    2540    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
    2541        return f"{self.sql(expression, 'this')} IGNORE NULLS"

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

    2543    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
    2544        return f"{self.sql(expression, 'this')} RESPECT NULLS"

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

    2546    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    2547        return self.sql(
    2548            exp.Cast(
    2549                this=exp.Div(this=expression.this, expression=expression.expression),
    2550                to=exp.DataType(this=exp.DataType.Type.INT),
    2551            )
    2552        )

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

    2554    def dpipe_sql(self, expression: exp.DPipe) -> str:
    2555        return self.binary(expression, "||")

def safedpipe_sql(self, expression: sqlglot.expressions.SafeDPipe) -> str: View Source

    2557    def safedpipe_sql(self, expression: exp.SafeDPipe) -> str:
    2558        if self.STRICT_STRING_CONCAT:
    2559            return self.func("CONCAT", *(exp.cast(e, "text") for e in expression.flatten()))
    2560        return self.dpipe_sql(expression)

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

    2562    def div_sql(self, expression: exp.Div) -> str:
    2563        return self.binary(expression, "/")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2595    def is_sql(self, expression: exp.Is) -> str:
    2596        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    2597            return self.sql(
    2598                expression.this if expression.expression.this else exp.not_(expression.this)
    2599            )
    2600        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2644    def log_sql(self, expression: exp.Log) -> str:
    2645        args = list(expression.args.values())
    2646        if not self.LOG_BASE_FIRST:
    2647            args.reverse()
    2648        return self.func("LOG", *args)

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

    2650    def use_sql(self, expression: exp.Use) -> str:
    2651        kind = self.sql(expression, "kind")
    2652        kind = f" {kind}" if kind else ""
    2653        this = self.sql(expression, "this")
    2654        this = f" {this}" if this else ""
    2655        return f"USE{kind}{this}"

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

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

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

    2661    def function_fallback_sql(self, expression: exp.Func) -> str:
    2662        args = []
    2663
    2664        for key in expression.arg_types:
    2665            arg_value = expression.args.get(key)
    2666
    2667            if isinstance(arg_value, list):
    2668                for value in arg_value:
    2669                    args.append(value)
    2670            elif arg_value is not None:
    2671                args.append(arg_value)
    2672
    2673        if self.normalize_functions:
    2674            name = expression.sql_name()
    2675        else:
    2676            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    2677
    2678        return self.func(name, *args)

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

    2680    def func(
    2681        self,
    2682        name: str,
    2683        *args: t.Optional[exp.Expression | str],
    2684        prefix: str = "(",
    2685        suffix: str = ")",
    2686    ) -> str:
    2687        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

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

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

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

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

    2698    def format_time(self, expression: exp.Expression) -> t.Optional[str]:
    2699        return format_time(
    2700            self.sql(expression, "format"), self.INVERSE_TIME_MAPPING, self.INVERSE_TIME_TRIE
    2701        )

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

    2703    def expressions(
    2704        self,
    2705        expression: t.Optional[exp.Expression] = None,
    2706        key: t.Optional[str] = None,
    2707        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    2708        flat: bool = False,
    2709        indent: bool = True,
    2710        skip_first: bool = False,
    2711        sep: str = ", ",
    2712        prefix: str = "",
    2713    ) -> str:
    2714        expressions = expression.args.get(key or "expressions") if expression else sqls
    2715
    2716        if not expressions:
    2717            return ""
    2718
    2719        if flat:
    2720            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    2721
    2722        num_sqls = len(expressions)
    2723
    2724        # These are calculated once in case we have the leading_comma / pretty option set, correspondingly
    2725        pad = " " * self.pad
    2726        stripped_sep = sep.strip()
    2727
    2728        result_sqls = []
    2729        for i, e in enumerate(expressions):
    2730            sql = self.sql(e, comment=False)
    2731            if not sql:
    2732                continue
    2733
    2734            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    2735
    2736            if self.pretty:
    2737                if self.leading_comma:
    2738                    result_sqls.append(f"{sep if i > 0 else pad}{prefix}{sql}{comments}")
    2739                else:
    2740                    result_sqls.append(
    2741                        f"{prefix}{sql}{stripped_sep if i + 1 < num_sqls else ''}{comments}"
    2742                    )
    2743            else:
    2744                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    2745
    2746        result_sql = "\n".join(result_sqls) if self.pretty else "".join(result_sqls)
    2747        return self.indent(result_sql, skip_first=skip_first) if indent else result_sql

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

    2749    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    2750        flat = flat or isinstance(expression.parent, exp.Properties)
    2751        expressions_sql = self.expressions(expression, flat=flat)
    2752        if flat:
    2753            return f"{op} {expressions_sql}"
    2754        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    2756    def naked_property(self, expression: exp.Property) -> str:
    2757        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    2758        if not property_name:
    2759            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    2760        return f"{property_name} {self.sql(expression, 'this')}"

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

    2762    def set_operation(self, expression: exp.Union, op: str) -> str:
    2763        this = self.maybe_comment(self.sql(expression, "this"), comments=expression.comments)
    2764        op = self.seg(op)
    2765        return self.query_modifiers(
    2766            expression, f"{this}{op}{self.sep()}{self.sql(expression, 'expression')}"
    2767        )

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

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

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

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

    2775    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    2776        this = self.sql(expression, "this")
    2777        expressions = self.no_identify(self.expressions, expression)
    2778        expressions = (
    2779            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    2780        )
    2781        return f"{this}{expressions}"

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

    2783    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    2784        this = self.sql(expression, "this")
    2785        expressions = self.expressions(expression, flat=True)
    2786        return f"{this}({expressions})"

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

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

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

    2791    def when_sql(self, expression: exp.When) -> str:
    2792        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    2793        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    2794        condition = self.sql(expression, "condition")
    2795        condition = f" AND {condition}" if condition else ""
    2796
    2797        then_expression = expression.args.get("then")
    2798        if isinstance(then_expression, exp.Insert):
    2799            then = f"INSERT {self.sql(then_expression, 'this')}"
    2800            if "expression" in then_expression.args:
    2801                then += f" VALUES {self.sql(then_expression, 'expression')}"
    2802        elif isinstance(then_expression, exp.Update):
    2803            if isinstance(then_expression.args.get("expressions"), exp.Star):
    2804                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    2805            else:
    2806                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    2807        else:
    2808            then = self.sql(then_expression)
    2809        return f"WHEN {matched}{source}{condition} THEN {then}"

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

    2811    def merge_sql(self, expression: exp.Merge) -> str:
    2812        table = expression.this
    2813        table_alias = ""
    2814
    2815        hints = table.args.get("hints")
    2816        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    2817            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    2818            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    2819
    2820        this = self.sql(table)
    2821        using = f"USING {self.sql(expression, 'using')}"
    2822        on = f"ON {self.sql(expression, 'on')}"
    2823        expressions = self.expressions(expression, sep=" ")
    2824
    2825        return self.prepend_ctes(
    2826            expression, f"MERGE INTO {this}{table_alias} {using} {on} {expressions}"
    2827        )

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

    2829    def tochar_sql(self, expression: exp.ToChar) -> str:
    2830        if expression.args.get("format"):
    2831            self.unsupported("Format argument unsupported for TO_CHAR/TO_VARCHAR function")
    2832
    2833        return self.sql(exp.cast(expression.this, "text"))

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

    2835    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    2836        this = self.sql(expression, "this")
    2837        kind = self.sql(expression, "kind")
    2838        settings_sql = self.expressions(expression, key="settings", sep=" ")
    2839        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    2840        return f"{this}({kind}{args})"

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

    2842    def dictrange_sql(self, expression: exp.DictRange) -> str:
    2843        this = self.sql(expression, "this")
    2844        max = self.sql(expression, "max")
    2845        min = self.sql(expression, "min")
    2846        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

    2854    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    2855        expressions = self.expressions(expression, key="expressions", flat=True)
    2856        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    2857        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    2858        buckets = self.sql(expression, "buckets")
    2859        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    2861    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    2862        this = self.sql(expression, "this")
    2863        having = self.sql(expression, "having")
    2864
    2865        if having:
    2866            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    2867
    2868        return self.func("ANY_VALUE", this)

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

    2870    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    2871        transform = self.func("TRANSFORM", *expression.expressions)
    2872        row_format_before = self.sql(expression, "row_format_before")
    2873        row_format_before = f" {row_format_before}" if row_format_before else ""
    2874        record_writer = self.sql(expression, "record_writer")
    2875        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    2876        using = f" USING {self.sql(expression, 'command_script')}"
    2877        schema = self.sql(expression, "schema")
    2878        schema = f" AS {schema}" if schema else ""
    2879        row_format_after = self.sql(expression, "row_format_after")
    2880        row_format_after = f" {row_format_after}" if row_format_after else ""
    2881        record_reader = self.sql(expression, "record_reader")
    2882        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    2883        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

    2885    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    2886        key_block_size = self.sql(expression, "key_block_size")
    2887        if key_block_size:
    2888            return f"KEY_BLOCK_SIZE = {key_block_size}"
    2889
    2890        using = self.sql(expression, "using")
    2891        if using:
    2892            return f"USING {using}"
    2893
    2894        parser = self.sql(expression, "parser")
    2895        if parser:
    2896            return f"WITH PARSER {parser}"
    2897
    2898        comment = self.sql(expression, "comment")
    2899        if comment:
    2900            return f"COMMENT {comment}"
    2901
    2902        visible = expression.args.get("visible")
    2903        if visible is not None:
    2904            return "VISIBLE" if visible else "INVISIBLE"
    2905
    2906        engine_attr = self.sql(expression, "engine_attr")
    2907        if engine_attr:
    2908            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    2909
    2910        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    2911        if secondary_engine_attr:
    2912            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    2913
    2914        self.unsupported("Unsupported index constraint option.")
    2915        return ""

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

    2917    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    2918        kind = self.sql(expression, "kind")
    2919        kind = f"{kind} INDEX" if kind else "INDEX"
    2920        this = self.sql(expression, "this")
    2921        this = f" {this}" if this else ""
    2922        index_type = self.sql(expression, "index_type")
    2923        index_type = f" USING {index_type}" if index_type else ""
    2924        schema = self.sql(expression, "schema")
    2925        schema = f" {schema}" if schema else ""
    2926        options = self.expressions(expression, key="options", sep=" ")
    2927        options = f" {options}" if options else ""
    2928        return f"{kind}{this}{index_type}{schema}{options}"

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

    2930    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    2931        if self.NVL2_SUPPORTED:
    2932            return self.function_fallback_sql(expression)
    2933
    2934        case = exp.Case().when(
    2935            expression.this.is_(exp.null()).not_(copy=False),
    2936            expression.args["true"],
    2937            copy=False,
    2938        )
    2939        else_cond = expression.args.get("false")
    2940        if else_cond:
    2941            case.else_(else_cond, copy=False)
    2942
    2943        return self.sql(case)

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

    2945    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    2946        this = self.sql(expression, "this")
    2947        expr = self.sql(expression, "expression")
    2948        iterator = self.sql(expression, "iterator")
    2949        condition = self.sql(expression, "condition")
    2950        condition = f" IF {condition}" if condition else ""
    2951        return f"{this} FOR {expr} IN {iterator}{condition}"

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

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

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

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

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

    2959    def predict_sql(self, expression: exp.Predict) -> str:
    2960        model = self.sql(expression, "this")
    2961        model = f"MODEL {model}"
    2962        table = self.sql(expression, "expression")
    2963        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    2964        parameters = self.sql(expression, "params_struct")
    2965        return self.func("PREDICT", model, table, parameters or None)