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

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

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

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

    360    def __init__(
    361        self,
    362        pretty: t.Optional[bool] = None,
    363        identify: str | bool = False,
    364        normalize: bool = False,
    365        pad: int = 2,
    366        indent: int = 2,
    367        normalize_functions: t.Optional[str | bool] = None,
    368        unsupported_level: ErrorLevel = ErrorLevel.WARN,
    369        max_unsupported: int = 3,
    370        leading_comma: bool = False,
    371        max_text_width: int = 80,
    372        comments: bool = True,
    373    ):
    374        import sqlglot
    375
    376        self.pretty = pretty if pretty is not None else sqlglot.pretty
    377        self.identify = identify
    378        self.normalize = normalize
    379        self.pad = pad
    380        self._indent = indent
    381        self.unsupported_level = unsupported_level
    382        self.max_unsupported = max_unsupported
    383        self.leading_comma = leading_comma
    384        self.max_text_width = max_text_width
    385        self.comments = comments
    386
    387        # This is both a Dialect property and a Generator argument, so we prioritize the latter
    388        self.normalize_functions = (
    389            self.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
    390        )
    391
    392        self.unsupported_messages: t.List[str] = []
    393        self._escaped_quote_end: str = self.TOKENIZER_CLASS.STRING_ESCAPES[0] + self.QUOTE_END
    394        self._escaped_identifier_end: str = (
    395            self.TOKENIZER_CLASS.IDENTIFIER_ESCAPES[0] + self.IDENTIFIER_END
    396        )
    397        self._cache: t.Optional[t.Dict[int, str]] = None

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.IntervalDayToSecondSpan'>: 'DAY TO SECOND', <class 'sqlglot.expressions.IntervalYearToMonthSpan'>: 'YEAR TO MONTH', <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.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ReturnsProperty'>: <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.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>>}
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'
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
TYPE_MAPPING = {<Type.NCHAR: 'NCHAR'>: 'CHAR', <Type.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <Type.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <Type.LONGTEXT: 'LONGTEXT'>: 'TEXT', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <Type.LONGBLOB: 'LONGBLOB'>: '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.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.PartitionedByProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <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.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.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'>)
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 = {}
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'
ESCAPE_LINE_BREAK = False
@classmethod
def can_identify(text: str, identify: str | bool = 'safe') -> bool: View Source

    256    @classmethod
    257    def can_identify(cls, text: str, identify: str | bool = "safe") -> bool:
    258        """Checks if text can be identified given an identify option.
    259
    260        Args:
    261            text: The text to check.
    262            identify:
    263                "always" or `True`: Always returns true.
    264                "safe": True if the identifier is case-insensitive.
    265
    266        Returns:
    267            Whether or not the given text can be identified.
    268        """
    269        if identify is True or identify == "always":
    270            return True
    271
    272        if identify == "safe":
    273            return not cls.case_sensitive(text)
    274
    275        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: Optional[sqlglot.expressions.Expression], cache: Optional[Dict[int, str]] = None) -> str: View Source

    399    def generate(
    400        self,
    401        expression: t.Optional[exp.Expression],
    402        cache: t.Optional[t.Dict[int, str]] = None,
    403    ) -> str:
    404        """
    405        Generates the SQL string corresponding to the given syntax tree.
    406
    407        Args:
    408            expression: The syntax tree.
    409            cache: An optional sql string cache. This leverages the hash of an Expression
    410                which can be slow to compute, so only use it if you set _hash on each node.
    411
    412        Returns:
    413            The SQL string corresponding to `expression`.
    414        """
    415        if cache is not None:
    416            self._cache = cache
    417
    418        self.unsupported_messages = []
    419        sql = self.sql(expression).strip()
    420        self._cache = None
    421
    422        if self.unsupported_level == ErrorLevel.IGNORE:
    423            return sql
    424
    425        if self.unsupported_level == ErrorLevel.WARN:
    426            for msg in self.unsupported_messages:
    427                logger.warning(msg)
    428        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
    429            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
    430
    431        if self.pretty:
    432            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
    433        return sql

Generates the SQL string corresponding to the given syntax tree.

###### Arguments:

- expression: The syntax tree.
- cache: An optional sql string cache. This leverages the hash of an Expression which can be slow to compute, so only use it if you set _hash on each node.

###### Returns:

> The SQL string corresponding to `expression`.

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

    435    def unsupported(self, message: str) -> None:
    436        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    437            raise UnsupportedError(message)
    438        self.unsupported_messages.append(message)

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

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

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

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

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

    446    def pad_comment(self, comment: str) -> str:
    447        comment = " " + comment if comment[0].strip() else comment
    448        comment = comment + " " if comment[-1].strip() else comment
    449        return comment

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

    451    def maybe_comment(
    452        self,
    453        sql: str,
    454        expression: t.Optional[exp.Expression] = None,
    455        comments: t.Optional[t.List[str]] = None,
    456    ) -> str:
    457        comments = (
    458            ((expression and expression.comments) if comments is None else comments)  # type: ignore
    459            if self.comments
    460            else None
    461        )
    462
    463        if not comments or isinstance(expression, exp.Binary):
    464            return sql
    465
    466        sep = "\n" if self.pretty else " "
    467        comments_sql = sep.join(
    468            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
    469        )
    470
    471        if not comments_sql:
    472            return sql
    473
    474        if isinstance(expression, self.WITH_SEPARATED_COMMENTS):
    475            return (
    476                f"{self.sep()}{comments_sql}{sql}"
    477                if sql[0].isspace()
    478                else f"{comments_sql}{self.sep()}{sql}"
    479            )
    480
    481        return f"{sql} {comments_sql}"

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

    483    def wrap(self, expression: exp.Expression | str) -> str:
    484        this_sql = self.indent(
    485            self.sql(expression)
    486            if isinstance(expression, (exp.Select, exp.Union))
    487            else self.sql(expression, "this"),
    488            level=1,
    489            pad=0,
    490        )
    491        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"

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

    493    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    494        original = self.identify
    495        self.identify = False
    496        result = func(*args, **kwargs)
    497        self.identify = original
    498        return result

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

    500    def normalize_func(self, name: str) -> str:
    501        if self.normalize_functions == "upper" or self.normalize_functions is True:
    502            return name.upper()
    503        if self.normalize_functions == "lower":
    504            return name.lower()
    505        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

    507    def indent(
    508        self,
    509        sql: str,
    510        level: int = 0,
    511        pad: t.Optional[int] = None,
    512        skip_first: bool = False,
    513        skip_last: bool = False,
    514    ) -> str:
    515        if not self.pretty:
    516            return sql
    517
    518        pad = self.pad if pad is None else pad
    519        lines = sql.split("\n")
    520
    521        return "\n".join(
    522            line
    523            if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
    524            else f"{' ' * (level * self._indent + pad)}{line}"
    525            for i, line in enumerate(lines)
    526        )

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

    528    def sql(
    529        self,
    530        expression: t.Optional[str | exp.Expression],
    531        key: t.Optional[str] = None,
    532        comment: bool = True,
    533    ) -> str:
    534        if not expression:
    535            return ""
    536
    537        if isinstance(expression, str):
    538            return expression
    539
    540        if key:
    541            value = expression.args.get(key)
    542            if value:
    543                return self.sql(value)
    544            return ""
    545
    546        if self._cache is not None:
    547            expression_id = hash(expression)
    548
    549            if expression_id in self._cache:
    550                return self._cache[expression_id]
    551
    552        transform = self.TRANSFORMS.get(expression.__class__)
    553
    554        if callable(transform):
    555            sql = transform(self, expression)
    556        elif transform:
    557            sql = transform
    558        elif isinstance(expression, exp.Expression):
    559            exp_handler_name = f"{expression.key}_sql"
    560
    561            if hasattr(self, exp_handler_name):
    562                sql = getattr(self, exp_handler_name)(expression)
    563            elif isinstance(expression, exp.Func):
    564                sql = self.function_fallback_sql(expression)
    565            elif isinstance(expression, exp.Property):
    566                sql = self.property_sql(expression)
    567            else:
    568                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
    569        else:
    570            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
    571
    572        sql = self.maybe_comment(sql, expression) if self.comments and comment else sql
    573
    574        if self._cache is not None:
    575            self._cache[expression_id] = sql
    576        return sql

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

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

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

    583    def cache_sql(self, expression: exp.Cache) -> str:
    584        lazy = " LAZY" if expression.args.get("lazy") else ""
    585        table = self.sql(expression, "this")
    586        options = expression.args.get("options")
    587        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
    588        sql = self.sql(expression, "expression")
    589        sql = f" AS{self.sep()}{sql}" if sql else ""
    590        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
    591        return self.prepend_ctes(expression, sql)

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

    593    def characterset_sql(self, expression: exp.CharacterSet) -> str:
    594        if isinstance(expression.parent, exp.Cast):
    595            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
    596        default = "DEFAULT " if expression.args.get("default") else ""
    597        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"

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

    599    def column_sql(self, expression: exp.Column) -> str:
    600        join_mark = " (+)" if expression.args.get("join_mark") else ""
    601
    602        if join_mark and not self.COLUMN_JOIN_MARKS_SUPPORTED:
    603            join_mark = ""
    604            self.unsupported("Outer join syntax using the (+) operator is not supported.")
    605
    606        column = ".".join(
    607            self.sql(part)
    608            for part in (
    609                expression.args.get("catalog"),
    610                expression.args.get("db"),
    611                expression.args.get("table"),
    612                expression.args.get("this"),
    613            )
    614            if part
    615        )
    616
    617        return f"{column}{join_mark}"

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

    619    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    620        this = self.sql(expression, "this")
    621        this = f" {this}" if this else ""
    622        position = self.sql(expression, "position")
    623        return f"{position}{this}"

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

    625    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
    626        column = self.sql(expression, "this")
    627        kind = self.sql(expression, "kind")
    628        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
    629        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
    630        kind = f"{sep}{kind}" if kind else ""
    631        constraints = f" {constraints}" if constraints else ""
    632        position = self.sql(expression, "position")
    633        position = f" {position}" if position else ""
    634
    635        return f"{exists}{column}{kind}{constraints}{position}"

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

    637    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    638        this = self.sql(expression, "this")
    639        kind_sql = self.sql(expression, "kind").strip()
    640        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

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

    642    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
    643        this = self.sql(expression, "this")
    644        if expression.args.get("not_null"):
    645            persisted = " PERSISTED NOT NULL"
    646        elif expression.args.get("persisted"):
    647            persisted = " PERSISTED"
    648        else:
    649            persisted = ""
    650        return f"AS {this}{persisted}"

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

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

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

    655    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
    656        if isinstance(expression.this, list):
    657            this = self.wrap(self.expressions(expression, key="this", flat=True))
    658        else:
    659            this = self.sql(expression, "this")
    660
    661        return f"COMPRESS {this}"

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

    663    def generatedasidentitycolumnconstraint_sql(
    664        self, expression: exp.GeneratedAsIdentityColumnConstraint
    665    ) -> str:
    666        this = ""
    667        if expression.this is not None:
    668            on_null = " ON NULL" if expression.args.get("on_null") else ""
    669            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
    670
    671        start = expression.args.get("start")
    672        start = f"START WITH {start}" if start else ""
    673        increment = expression.args.get("increment")
    674        increment = f" INCREMENT BY {increment}" if increment else ""
    675        minvalue = expression.args.get("minvalue")
    676        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    677        maxvalue = expression.args.get("maxvalue")
    678        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    679        cycle = expression.args.get("cycle")
    680        cycle_sql = ""
    681
    682        if cycle is not None:
    683            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
    684            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
    685
    686        sequence_opts = ""
    687        if start or increment or cycle_sql:
    688            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
    689            sequence_opts = f" ({sequence_opts.strip()})"
    690
    691        expr = self.sql(expression, "expression")
    692        expr = f"({expr})" if expr else "IDENTITY"
    693
    694        return f"GENERATED{this} AS {expr}{sequence_opts}"

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

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

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

    699    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    700        desc = expression.args.get("desc")
    701        if desc is not None:
    702            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    703        return f"PRIMARY KEY"

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

    705    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    706        this = self.sql(expression, "this")
    707        this = f" {this}" if this else ""
    708        return f"UNIQUE{this}"

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

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

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

    713    def create_sql(self, expression: exp.Create) -> str:
    714        kind = self.sql(expression, "kind").upper()
    715        properties = expression.args.get("properties")
    716        properties_locs = self.locate_properties(properties) if properties else defaultdict()
    717
    718        this = self.createable_sql(expression, properties_locs)
    719
    720        properties_sql = ""
    721        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
    722            exp.Properties.Location.POST_WITH
    723        ):
    724            properties_sql = self.sql(
    725                exp.Properties(
    726                    expressions=[
    727                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
    728                        *properties_locs[exp.Properties.Location.POST_WITH],
    729                    ]
    730                )
    731            )
    732
    733        begin = " BEGIN" if expression.args.get("begin") else ""
    734        expression_sql = self.sql(expression, "expression")
    735        if expression_sql:
    736            expression_sql = f"{begin}{self.sep()}{expression_sql}"
    737
    738            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
    739                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
    740                    postalias_props_sql = self.properties(
    741                        exp.Properties(
    742                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
    743                        ),
    744                        wrapped=False,
    745                    )
    746                    expression_sql = f" AS {postalias_props_sql}{expression_sql}"
    747                else:
    748                    expression_sql = f" AS{expression_sql}"
    749
    750        postindex_props_sql = ""
    751        if properties_locs.get(exp.Properties.Location.POST_INDEX):
    752            postindex_props_sql = self.properties(
    753                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
    754                wrapped=False,
    755                prefix=" ",
    756            )
    757
    758        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
    759        indexes = f" {indexes}" if indexes else ""
    760        index_sql = indexes + postindex_props_sql
    761
    762        replace = " OR REPLACE" if expression.args.get("replace") else ""
    763        unique = " UNIQUE" if expression.args.get("unique") else ""
    764
    765        postcreate_props_sql = ""
    766        if properties_locs.get(exp.Properties.Location.POST_CREATE):
    767            postcreate_props_sql = self.properties(
    768                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
    769                sep=" ",
    770                prefix=" ",
    771                wrapped=False,
    772            )
    773
    774        modifiers = "".join((replace, unique, postcreate_props_sql))
    775
    776        postexpression_props_sql = ""
    777        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
    778            postexpression_props_sql = self.properties(
    779                exp.Properties(
    780                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
    781                ),
    782                sep=" ",
    783                prefix=" ",
    784                wrapped=False,
    785            )
    786
    787        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    788        no_schema_binding = (
    789            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
    790        )
    791
    792        clone = self.sql(expression, "clone")
    793        clone = f" {clone}" if clone else ""
    794
    795        expression_sql = f"CREATE{modifiers} {kind}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
    796        return self.prepend_ctes(expression, expression_sql)

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

    798    def clone_sql(self, expression: exp.Clone) -> str:
    799        this = self.sql(expression, "this")
    800        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    801        this = f"{shallow}CLONE {this}"
    802        when = self.sql(expression, "when")
    803
    804        if when:
    805            kind = self.sql(expression, "kind")
    806            expr = self.sql(expression, "expression")
    807            return f"{this} {when} ({kind} => {expr})"
    808
    809        return this

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

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

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

    814    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    815        with_ = self.sql(expression, "with")
    816        if with_:
    817            sql = f"{with_}{self.sep()}{sql}"
    818        return sql

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

    820    def with_sql(self, expression: exp.With) -> str:
    821        sql = self.expressions(expression, flat=True)
    822        recursive = "RECURSIVE " if expression.args.get("recursive") else ""
    823
    824        return f"WITH {recursive}{sql}"

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

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

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

    830    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    831        alias = self.sql(expression, "this")
    832        columns = self.expressions(expression, key="columns", flat=True)
    833        columns = f"({columns})" if columns else ""
    834        return f"{alias}{columns}"

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

    836    def bitstring_sql(self, expression: exp.BitString) -> str:
    837        this = self.sql(expression, "this")
    838        if self.BIT_START:
    839            return f"{self.BIT_START}{this}{self.BIT_END}"
    840        return f"{int(this, 2)}"

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

    842    def hexstring_sql(self, expression: exp.HexString) -> str:
    843        this = self.sql(expression, "this")
    844        if self.HEX_START:
    845            return f"{self.HEX_START}{this}{self.HEX_END}"
    846        return f"{int(this, 16)}"

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

    848    def bytestring_sql(self, expression: exp.ByteString) -> str:
    849        this = self.sql(expression, "this")
    850        if self.BYTE_START:
    851            return f"{self.BYTE_START}{this}{self.BYTE_END}"
    852        return this

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

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

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

    858    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    859        this = self.sql(expression, "this")
    860        specifier = self.sql(expression, "expression")
    861        specifier = f" {specifier}" if specifier else ""
    862        return f"{this}{specifier}"

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

    864    def datatype_sql(self, expression: exp.DataType) -> str:
    865        type_value = expression.this
    866
    867        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
    868            type_sql = self.sql(expression, "kind")
    869        else:
    870            type_sql = (
    871                self.TYPE_MAPPING.get(type_value, type_value.value)
    872                if isinstance(type_value, exp.DataType.Type)
    873                else type_value
    874            )
    875
    876        nested = ""
    877        interior = self.expressions(expression, flat=True)
    878        values = ""
    879
    880        if interior:
    881            if expression.args.get("nested"):
    882                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    883                if expression.args.get("values") is not None:
    884                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    885                    values = self.expressions(expression, key="values", flat=True)
    886                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    887            elif type_value == exp.DataType.Type.INTERVAL:
    888                nested = f" {interior}"
    889            else:
    890                nested = f"({interior})"
    891
    892        type_sql = f"{type_sql}{nested}{values}"
    893        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
    894            exp.DataType.Type.TIMETZ,
    895            exp.DataType.Type.TIMESTAMPTZ,
    896        ):
    897            type_sql = f"{type_sql} WITH TIME ZONE"
    898
    899        return type_sql

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

    901    def directory_sql(self, expression: exp.Directory) -> str:
    902        local = "LOCAL " if expression.args.get("local") else ""
    903        row_format = self.sql(expression, "row_format")
    904        row_format = f" {row_format}" if row_format else ""
    905        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

    907    def delete_sql(self, expression: exp.Delete) -> str:
    908        this = self.sql(expression, "this")
    909        this = f" FROM {this}" if this else ""
    910        using = self.sql(expression, "using")
    911        using = f" USING {using}" if using else ""
    912        where = self.sql(expression, "where")
    913        returning = self.sql(expression, "returning")
    914        limit = self.sql(expression, "limit")
    915        tables = self.expressions(expression, key="tables")
    916        tables = f" {tables}" if tables else ""
    917        if self.RETURNING_END:
    918            expression_sql = f"{this}{using}{where}{returning}{limit}"
    919        else:
    920            expression_sql = f"{returning}{this}{using}{where}{limit}"
    921        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

    923    def drop_sql(self, expression: exp.Drop) -> str:
    924        this = self.sql(expression, "this")
    925        kind = expression.args["kind"]
    926        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    927        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    928        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    929        cascade = " CASCADE" if expression.args.get("cascade") else ""
    930        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    931        purge = " PURGE" if expression.args.get("purge") else ""
    932        return (
    933            f"DROP{temporary}{materialized} {kind}{exists_sql}{this}{cascade}{constraints}{purge}"
    934        )

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

    936    def except_sql(self, expression: exp.Except) -> str:
    937        return self.prepend_ctes(
    938            expression,
    939            self.set_operation(expression, self.except_op(expression)),
    940        )

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

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

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

    945    def fetch_sql(self, expression: exp.Fetch) -> str:
    946        direction = expression.args.get("direction")
    947        direction = f" {direction.upper()}" if direction else ""
    948        count = expression.args.get("count")
    949        count = f" {count}" if count else ""
    950        if expression.args.get("percent"):
    951            count = f"{count} PERCENT"
    952        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    953        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"

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

    955    def filter_sql(self, expression: exp.Filter) -> str:
    956        this = self.sql(expression, "this")
    957        where = self.sql(expression, "expression")[1:]  # where has a leading space
    958        return f"{this} FILTER({where})"

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

    960    def hint_sql(self, expression: exp.Hint) -> str:
    961        if not self.QUERY_HINTS:
    962            self.unsupported("Hints are not supported")
    963            return ""
    964
    965        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

    967    def index_sql(self, expression: exp.Index) -> str:
    968        unique = "UNIQUE " if expression.args.get("unique") else ""
    969        primary = "PRIMARY " if expression.args.get("primary") else ""
    970        amp = "AMP " if expression.args.get("amp") else ""
    971        name = self.sql(expression, "this")
    972        name = f"{name} " if name else ""
    973        table = self.sql(expression, "table")
    974        table = f"{self.INDEX_ON} {table}" if table else ""
    975        using = self.sql(expression, "using")
    976        using = f" USING {using} " if using else ""
    977        index = "INDEX " if not table else ""
    978        columns = self.expressions(expression, key="columns", flat=True)
    979        columns = f"({columns})" if columns else ""
    980        partition_by = self.expressions(expression, key="partition_by", flat=True)
    981        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    982        return f"{unique}{primary}{amp}{index}{name}{table}{using}{columns}{partition_by}"

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

    984    def identifier_sql(self, expression: exp.Identifier) -> str:
    985        text = expression.name
    986        lower = text.lower()
    987        text = lower if self.normalize and not expression.quoted else text
    988        text = text.replace(self.IDENTIFIER_END, self._escaped_identifier_end)
    989        if (
    990            expression.quoted
    991            or self.can_identify(text, self.identify)
    992            or lower in self.RESERVED_KEYWORDS
    993            or (not self.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    994        ):
    995            text = f"{self.IDENTIFIER_START}{text}{self.IDENTIFIER_END}"
    996        return text

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

     998    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
     999        input_format = self.sql(expression, "input_format")
    1000        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1001        output_format = self.sql(expression, "output_format")
    1002        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1003        return self.sep().join((input_format, output_format))

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

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

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

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

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

    1012    def properties_sql(self, expression: exp.Properties) -> str:
    1013        root_properties = []
    1014        with_properties = []
    1015
    1016        for p in expression.expressions:
    1017            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1018            if p_loc == exp.Properties.Location.POST_WITH:
    1019                with_properties.append(p.copy())
    1020            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1021                root_properties.append(p.copy())
    1022
    1023        return self.root_properties(
    1024            exp.Properties(expressions=root_properties)
    1025        ) + self.with_properties(exp.Properties(expressions=with_properties))

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

    1027    def root_properties(self, properties: exp.Properties) -> str:
    1028        if properties.expressions:
    1029            return self.sep() + self.expressions(properties, indent=False, sep=" ")
    1030        return ""

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

    1032    def properties(
    1033        self,
    1034        properties: exp.Properties,
    1035        prefix: str = "",
    1036        sep: str = ", ",
    1037        suffix: str = "",
    1038        wrapped: bool = True,
    1039    ) -> str:
    1040        if properties.expressions:
    1041            expressions = self.expressions(properties, sep=sep, indent=False)
    1042            if expressions:
    1043                expressions = self.wrap(expressions) if wrapped else expressions
    1044                return f"{prefix}{' ' if prefix and prefix != ' ' else ''}{expressions}{suffix}"
    1045        return ""

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

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

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

    1050    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1051        properties_locs = defaultdict(list)
    1052        for p in properties.expressions:
    1053            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1054            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1055                properties_locs[p_loc].append(p.copy())
    1056            else:
    1057                self.unsupported(f"Unsupported property {p.key}")
    1058
    1059        return properties_locs

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

    1061    def property_sql(self, expression: exp.Property) -> str:
    1062        property_cls = expression.__class__
    1063        if property_cls == exp.Property:
    1064            return f"{expression.name}={self.sql(expression, 'value')}"
    1065
    1066        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1067        if not property_name:
    1068            self.unsupported(f"Unsupported property {expression.key}")
    1069
    1070        return f"{property_name}={self.sql(expression, 'this')}"

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

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

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

    1077    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1078        no = "NO " if expression.args.get("no") else ""
    1079        protection = " PROTECTION" if expression.args.get("protection") else ""
    1080        return f"{no}FALLBACK{protection}"

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

    1082    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1083        no = "NO " if expression.args.get("no") else ""
    1084        local = expression.args.get("local")
    1085        local = f"{local} " if local else ""
    1086        dual = "DUAL " if expression.args.get("dual") else ""
    1087        before = "BEFORE " if expression.args.get("before") else ""
    1088        after = "AFTER " if expression.args.get("after") else ""
    1089        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1091    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1092        freespace = self.sql(expression, "this")
    1093        percent = " PERCENT" if expression.args.get("percent") else ""
    1094        return f"FREESPACE={freespace}{percent}"

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

    1096    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1097        if expression.args.get("default"):
    1098            property = "DEFAULT"
    1099        elif expression.args.get("on"):
    1100            property = "ON"
    1101        else:
    1102            property = "OFF"
    1103        return f"CHECKSUM={property}"

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

    1105    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1106        if expression.args.get("no"):
    1107            return "NO MERGEBLOCKRATIO"
    1108        if expression.args.get("default"):
    1109            return "DEFAULT MERGEBLOCKRATIO"
    1110
    1111        percent = " PERCENT" if expression.args.get("percent") else ""
    1112        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1114    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1115        default = expression.args.get("default")
    1116        minimum = expression.args.get("minimum")
    1117        maximum = expression.args.get("maximum")
    1118        if default or minimum or maximum:
    1119            if default:
    1120                prop = "DEFAULT"
    1121            elif minimum:
    1122                prop = "MINIMUM"
    1123            else:
    1124                prop = "MAXIMUM"
    1125            return f"{prop} DATABLOCKSIZE"
    1126        units = expression.args.get("units")
    1127        units = f" {units}" if units else ""
    1128        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1130    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1131        autotemp = expression.args.get("autotemp")
    1132        always = expression.args.get("always")
    1133        default = expression.args.get("default")
    1134        manual = expression.args.get("manual")
    1135        never = expression.args.get("never")
    1136
    1137        if autotemp is not None:
    1138            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1139        elif always:
    1140            prop = "ALWAYS"
    1141        elif default:
    1142            prop = "DEFAULT"
    1143        elif manual:
    1144            prop = "MANUAL"
    1145        elif never:
    1146            prop = "NEVER"
    1147        return f"BLOCKCOMPRESSION={prop}"

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

    1149    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1150        no = expression.args.get("no")
    1151        no = " NO" if no else ""
    1152        concurrent = expression.args.get("concurrent")
    1153        concurrent = " CONCURRENT" if concurrent else ""
    1154
    1155        for_ = ""
    1156        if expression.args.get("for_all"):
    1157            for_ = " FOR ALL"
    1158        elif expression.args.get("for_insert"):
    1159            for_ = " FOR INSERT"
    1160        elif expression.args.get("for_none"):
    1161            for_ = " FOR NONE"
    1162        return f"WITH{no}{concurrent} ISOLATED LOADING{for_}"

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

    1164    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1165        kind = expression.args.get("kind")
    1166        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1167        for_or_in = expression.args.get("for_or_in")
    1168        lock_type = expression.args.get("lock_type")
    1169        override = " OVERRIDE" if expression.args.get("override") else ""
    1170        return f"LOCKING {kind}{this} {for_or_in} {lock_type}{override}"

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

    1172    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1173        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1174        statistics = expression.args.get("statistics")
    1175        statistics_sql = ""
    1176        if statistics is not None:
    1177            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1178        return f"{data_sql}{statistics_sql}"

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

    1180    def insert_sql(self, expression: exp.Insert) -> str:
    1181        overwrite = expression.args.get("overwrite")
    1182
    1183        if isinstance(expression.this, exp.Directory):
    1184            this = " OVERWRITE" if overwrite else " INTO"
    1185        else:
    1186            this = " OVERWRITE TABLE" if overwrite else " INTO"
    1187
    1188        alternative = expression.args.get("alternative")
    1189        alternative = f" OR {alternative}" if alternative else ""
    1190        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1191
    1192        this = f"{this} {self.sql(expression, 'this')}"
    1193
    1194        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1195        partition_sql = (
    1196            f" {self.sql(expression, 'partition')}" if expression.args.get("partition") else ""
    1197        )
    1198        where = self.sql(expression, "where")
    1199        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1200        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1201        conflict = self.sql(expression, "conflict")
    1202        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1203        returning = self.sql(expression, "returning")
    1204
    1205        if self.RETURNING_END:
    1206            expression_sql = f"{expression_sql}{conflict}{returning}"
    1207        else:
    1208            expression_sql = f"{returning}{expression_sql}{conflict}"
    1209
    1210        sql = f"INSERT{alternative}{ignore}{this}{by_name}{exists}{partition_sql}{where}{expression_sql}"
    1211        return self.prepend_ctes(expression, sql)

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

    1213    def intersect_sql(self, expression: exp.Intersect) -> str:
    1214        return self.prepend_ctes(
    1215            expression,
    1216            self.set_operation(expression, self.intersect_op(expression)),
    1217        )

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

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

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

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

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

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

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

    1228    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1229        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1230        constraint = self.sql(expression, "constraint")
    1231        if constraint:
    1232            constraint = f"ON CONSTRAINT {constraint}"
    1233        key = self.expressions(expression, key="key", flat=True)
    1234        do = "" if expression.args.get("duplicate") else " DO "
    1235        nothing = "NOTHING" if expression.args.get("nothing") else ""
    1236        expressions = self.expressions(expression, flat=True)
    1237        set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1238        if expressions:
    1239            expressions = f"UPDATE {set_keyword}{expressions}"
    1240        return f"{self.seg(conflict)} {constraint}{key}{do}{nothing}{expressions}"

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

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

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

    1245    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1246        fields = expression.args.get("fields")
    1247        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1248        escaped = expression.args.get("escaped")
    1249        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1250        items = expression.args.get("collection_items")
    1251        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1252        keys = expression.args.get("map_keys")
    1253        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1254        lines = expression.args.get("lines")
    1255        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1256        null = expression.args.get("null")
    1257        null = f" NULL DEFINED AS {null}" if null else ""
    1258        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1263    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1264        this = f"{self.sql(expression, 'this')} INDEX"
    1265        target = self.sql(expression, "target")
    1266        target = f" FOR {target}" if target else ""
    1267        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1269    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1270        table = ".".join(
    1271            part
    1272            for part in [
    1273                self.sql(expression, "catalog"),
    1274                self.sql(expression, "db"),
    1275                self.sql(expression, "this"),
    1276            ]
    1277            if part
    1278        )
    1279
    1280        version = self.sql(expression, "version")
    1281        version = f" {version}" if version else ""
    1282        alias = self.sql(expression, "alias")
    1283        alias = f"{sep}{alias}" if alias else ""
    1284        hints = self.expressions(expression, key="hints", sep=" ")
    1285        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1286        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1287        pivots = f" {pivots}" if pivots else ""
    1288        joins = self.expressions(expression, key="joins", sep="", skip_first=True)
    1289        laterals = self.expressions(expression, key="laterals", sep="")
    1290
    1291        return f"{table}{version}{alias}{hints}{pivots}{joins}{laterals}"

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

    1293    def tablesample_sql(
    1294        self, expression: exp.TableSample, seed_prefix: str = "SEED", sep=" AS "
    1295    ) -> str:
    1296        if self.ALIAS_POST_TABLESAMPLE and expression.this.alias:
    1297            table = expression.this.copy()
    1298            table.set("alias", None)
    1299            this = self.sql(table)
    1300            alias = f"{sep}{self.sql(expression.this, 'alias')}"
    1301        else:
    1302            this = self.sql(expression, "this")
    1303            alias = ""
    1304        method = self.sql(expression, "method")
    1305        method = f"{method.upper()} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1306        numerator = self.sql(expression, "bucket_numerator")
    1307        denominator = self.sql(expression, "bucket_denominator")
    1308        field = self.sql(expression, "bucket_field")
    1309        field = f" ON {field}" if field else ""
    1310        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1311        percent = self.sql(expression, "percent")
    1312        percent = f"{percent} PERCENT" if percent else ""
    1313        rows = self.sql(expression, "rows")
    1314        rows = f"{rows} ROWS" if rows else ""
    1315        size = self.sql(expression, "size")
    1316        if size and self.TABLESAMPLE_SIZE_IS_PERCENT:
    1317            size = f"{size} PERCENT"
    1318        seed = self.sql(expression, "seed")
    1319        seed = f" {seed_prefix} ({seed})" if seed else ""
    1320        kind = expression.args.get("kind", "TABLESAMPLE")
    1321        return f"{this} {kind} {method}({bucket}{percent}{rows}{size}){seed}{alias}"

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

    1323    def pivot_sql(self, expression: exp.Pivot) -> str:
    1324        expressions = self.expressions(expression, flat=True)
    1325
    1326        if expression.this:
    1327            this = self.sql(expression, "this")
    1328            on = f"{self.seg('ON')} {expressions}"
    1329            using = self.expressions(expression, key="using", flat=True)
    1330            using = f"{self.seg('USING')} {using}" if using else ""
    1331            group = self.sql(expression, "group")
    1332            return f"PIVOT {this}{on}{using}{group}"
    1333
    1334        alias = self.sql(expression, "alias")
    1335        alias = f" AS {alias}" if alias else ""
    1336        unpivot = expression.args.get("unpivot")
    1337        direction = "UNPIVOT" if unpivot else "PIVOT"
    1338        field = self.sql(expression, "field")
    1339        include_nulls = expression.args.get("include_nulls")
    1340        if include_nulls is not None:
    1341            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    1342        else:
    1343            nulls = ""
    1344        return f"{direction}{nulls}({expressions} FOR {field}){alias}"

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

    1346    def version_sql(self, expression: exp.Version) -> str:
    1347        this = f"FOR {expression.name}"
    1348        kind = expression.text("kind")
    1349        expr = self.sql(expression, "expression")
    1350        return f"{this} {kind} {expr}"

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

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

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

    1355    def update_sql(self, expression: exp.Update) -> str:
    1356        this = self.sql(expression, "this")
    1357        set_sql = self.expressions(expression, flat=True)
    1358        from_sql = self.sql(expression, "from")
    1359        where_sql = self.sql(expression, "where")
    1360        returning = self.sql(expression, "returning")
    1361        order = self.sql(expression, "order")
    1362        limit = self.sql(expression, "limit")
    1363        if self.RETURNING_END:
    1364            expression_sql = f"{from_sql}{where_sql}{returning}"
    1365        else:
    1366            expression_sql = f"{returning}{from_sql}{where_sql}"
    1367        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    1368        return self.prepend_ctes(expression, sql)

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

    1370    def values_sql(self, expression: exp.Values) -> str:
    1371        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    1372        if self.VALUES_AS_TABLE or not expression.find_ancestor(exp.From, exp.Join):
    1373            args = self.expressions(expression)
    1374            alias = self.sql(expression, "alias")
    1375            values = f"VALUES{self.seg('')}{args}"
    1376            values = (
    1377                f"({values})"
    1378                if self.WRAP_DERIVED_VALUES and (alias or isinstance(expression.parent, exp.From))
    1379                else values
    1380            )
    1381            return f"{values} AS {alias}" if alias else values
    1382
    1383        # Converts `VALUES...` expression into a series of select unions.
    1384        # Note: If you have a lot of unions then this will result in a large number of recursive statements to
    1385        # evaluate the expression. You may need to increase `sys.setrecursionlimit` to run and it can also be
    1386        # very slow.
    1387        expression = expression.copy()
    1388        column_names = expression.alias and expression.args["alias"].columns
    1389
    1390        selects = []
    1391
    1392        for i, tup in enumerate(expression.expressions):
    1393            row = tup.expressions
    1394
    1395            if i == 0 and column_names:
    1396                row = [
    1397                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    1398                ]
    1399
    1400            selects.append(exp.Select(expressions=row))
    1401
    1402        subquery_expression: exp.Select | exp.Union = selects[0]
    1403        if len(selects) > 1:
    1404            for select in selects[1:]:
    1405                subquery_expression = exp.union(
    1406                    subquery_expression, select, distinct=False, copy=False
    1407                )
    1408
    1409        return self.subquery_sql(subquery_expression.subquery(expression.alias, copy=False))

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

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

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

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

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

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

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

    1422    def group_sql(self, expression: exp.Group) -> str:
    1423        group_by = self.op_expressions("GROUP BY", expression)
    1424
    1425        if expression.args.get("all"):
    1426            return f"{group_by} ALL"
    1427
    1428        grouping_sets = self.expressions(expression, key="grouping_sets", indent=False)
    1429        grouping_sets = (
    1430            f"{self.seg('GROUPING SETS')} {self.wrap(grouping_sets)}" if grouping_sets else ""
    1431        )
    1432
    1433        cube = expression.args.get("cube", [])
    1434        if seq_get(cube, 0) is True:
    1435            return f"{group_by}{self.seg('WITH CUBE')}"
    1436        else:
    1437            cube_sql = self.expressions(expression, key="cube", indent=False)
    1438            cube_sql = f"{self.seg('CUBE')} {self.wrap(cube_sql)}" if cube_sql else ""
    1439
    1440        rollup = expression.args.get("rollup", [])
    1441        if seq_get(rollup, 0) is True:
    1442            return f"{group_by}{self.seg('WITH ROLLUP')}"
    1443        else:
    1444            rollup_sql = self.expressions(expression, key="rollup", indent=False)
    1445            rollup_sql = f"{self.seg('ROLLUP')} {self.wrap(rollup_sql)}" if rollup_sql else ""
    1446
    1447        groupings = csv(
    1448            grouping_sets,
    1449            cube_sql,
    1450            rollup_sql,
    1451            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    1452            sep=self.GROUPINGS_SEP,
    1453        )
    1454
    1455        if expression.args.get("expressions") and groupings:
    1456            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    1457
    1458        return f"{group_by}{groupings}"

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

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

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

    1464    def connect_sql(self, expression: exp.Connect) -> str:
    1465        start = self.sql(expression, "start")
    1466        start = self.seg(f"START WITH {start}") if start else ""
    1467        connect = self.sql(expression, "connect")
    1468        connect = self.seg(f"CONNECT BY {connect}")
    1469        return start + connect

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

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

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

    1474    def join_sql(self, expression: exp.Join) -> str:
    1475        op_sql = " ".join(
    1476            op
    1477            for op in (
    1478                expression.method,
    1479                "GLOBAL" if expression.args.get("global") else None,
    1480                expression.side,
    1481                expression.kind,
    1482                expression.hint if self.JOIN_HINTS else None,
    1483            )
    1484            if op
    1485        )
    1486        on_sql = self.sql(expression, "on")
    1487        using = expression.args.get("using")
    1488
    1489        if not on_sql and using:
    1490            on_sql = csv(*(self.sql(column) for column in using))
    1491
    1492        this_sql = self.sql(expression, "this")
    1493
    1494        if on_sql:
    1495            on_sql = self.indent(on_sql, skip_first=True)
    1496            space = self.seg(" " * self.pad) if self.pretty else " "
    1497            if using:
    1498                on_sql = f"{space}USING ({on_sql})"
    1499            else:
    1500                on_sql = f"{space}ON {on_sql}"
    1501        elif not op_sql:
    1502            return f", {this_sql}"
    1503
    1504        op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    1505        return f"{self.seg(op_sql)} {this_sql}{on_sql}"

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

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

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

    1512    def lateral_sql(self, expression: exp.Lateral) -> str:
    1513        this = self.sql(expression, "this")
    1514
    1515        if isinstance(expression.this, exp.Subquery):
    1516            return f"LATERAL {this}"
    1517
    1518        if expression.args.get("view"):
    1519            alias = expression.args["alias"]
    1520            columns = self.expressions(alias, key="columns", flat=True)
    1521            table = f" {alias.name}" if alias.name else ""
    1522            columns = f" AS {columns}" if columns else ""
    1523            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    1524            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    1525
    1526        alias = self.sql(expression, "alias")
    1527        alias = f" AS {alias}" if alias else ""
    1528        return f"LATERAL {this}{alias}"

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

    1530    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    1531        this = self.sql(expression, "this")
    1532        args = ", ".join(
    1533            sql
    1534            for sql in (
    1535                self.sql(expression, "offset"),
    1536                self.sql(expression, "expression"),
    1537            )
    1538            if sql
    1539        )
    1540        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args}"

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

    1542    def offset_sql(self, expression: exp.Offset) -> str:
    1543        this = self.sql(expression, "this")
    1544        return f"{this}{self.seg('OFFSET')} {self.sql(expression, 'expression')}"

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

    1546    def setitem_sql(self, expression: exp.SetItem) -> str:
    1547        kind = self.sql(expression, "kind")
    1548        kind = f"{kind} " if kind else ""
    1549        this = self.sql(expression, "this")
    1550        expressions = self.expressions(expression)
    1551        collate = self.sql(expression, "collate")
    1552        collate = f" COLLATE {collate}" if collate else ""
    1553        global_ = "GLOBAL " if expression.args.get("global") else ""
    1554        return f"{global_}{kind}{this}{expressions}{collate}"

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

    1556    def set_sql(self, expression: exp.Set) -> str:
    1557        expressions = (
    1558            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    1559        )
    1560        tag = " TAG" if expression.args.get("tag") else ""
    1561        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"

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

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

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

    1566    def lock_sql(self, expression: exp.Lock) -> str:
    1567        if not self.LOCKING_READS_SUPPORTED:
    1568            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    1569            return ""
    1570
    1571        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    1572        expressions = self.expressions(expression, flat=True)
    1573        expressions = f" OF {expressions}" if expressions else ""
    1574        wait = expression.args.get("wait")
    1575
    1576        if wait is not None:
    1577            if isinstance(wait, exp.Literal):
    1578                wait = f" WAIT {self.sql(wait)}"
    1579            else:
    1580                wait = " NOWAIT" if wait else " SKIP LOCKED"
    1581
    1582        return f"{lock_type}{expressions}{wait or ''}"

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

    1584    def literal_sql(self, expression: exp.Literal) -> str:
    1585        text = expression.this or ""
    1586        if expression.is_string:
    1587            text = f"{self.QUOTE_START}{self.escape_str(text)}{self.QUOTE_END}"
    1588        return text

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

    1590    def escape_str(self, text: str) -> str:
    1591        text = text.replace(self.QUOTE_END, self._escaped_quote_end)
    1592        if self.ESCAPE_LINE_BREAK:
    1593            text = text.replace("\n", "\\n")
    1594        elif self.pretty:
    1595            text = text.replace("\n", self.SENTINEL_LINE_BREAK)
    1596        return text

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

    1598    def loaddata_sql(self, expression: exp.LoadData) -> str:
    1599        local = " LOCAL" if expression.args.get("local") else ""
    1600        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    1601        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    1602        this = f" INTO TABLE {self.sql(expression, 'this')}"
    1603        partition = self.sql(expression, "partition")
    1604        partition = f" {partition}" if partition else ""
    1605        input_format = self.sql(expression, "input_format")
    1606        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    1607        serde = self.sql(expression, "serde")
    1608        serde = f" SERDE {serde}" if serde else ""
    1609        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    1611    def null_sql(self, *_) -> str:
    1612        return "NULL"

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

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

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

    1617    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    1618        this = self.sql(expression, "this")
    1619        this = f"{this} " if this else this
    1620        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

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

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

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

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

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

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

    1631    def ordered_sql(self, expression: exp.Ordered) -> str:
    1632        desc = expression.args.get("desc")
    1633        asc = not desc
    1634
    1635        nulls_first = expression.args.get("nulls_first")
    1636        nulls_last = not nulls_first
    1637        nulls_are_large = self.NULL_ORDERING == "nulls_are_large"
    1638        nulls_are_small = self.NULL_ORDERING == "nulls_are_small"
    1639        nulls_are_last = self.NULL_ORDERING == "nulls_are_last"
    1640
    1641        sort_order = " DESC" if desc else ""
    1642        nulls_sort_change = ""
    1643        if nulls_first and (
    1644            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    1645        ):
    1646            nulls_sort_change = " NULLS FIRST"
    1647        elif (
    1648            nulls_last
    1649            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    1650            and not nulls_are_last
    1651        ):
    1652            nulls_sort_change = " NULLS LAST"
    1653
    1654        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    1655            self.unsupported(
    1656                "Sorting in an ORDER BY on NULLS FIRST/NULLS LAST is not supported by this dialect"
    1657            )
    1658            nulls_sort_change = ""
    1659
    1660        return f"{self.sql(expression, 'this')}{sort_order}{nulls_sort_change}"

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

    1662    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    1663        partition = self.partition_by_sql(expression)
    1664        order = self.sql(expression, "order")
    1665        measures = self.expressions(expression, key="measures")
    1666        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    1667        rows = self.sql(expression, "rows")
    1668        rows = self.seg(rows) if rows else ""
    1669        after = self.sql(expression, "after")
    1670        after = self.seg(after) if after else ""
    1671        pattern = self.sql(expression, "pattern")
    1672        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    1673        definition_sqls = [
    1674            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    1675            for definition in expression.args.get("define", [])
    1676        ]
    1677        definitions = self.expressions(sqls=definition_sqls)
    1678        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    1679        body = "".join(
    1680            (
    1681                partition,
    1682                order,
    1683                measures,
    1684                rows,
    1685                after,
    1686                pattern,
    1687                define,
    1688            )
    1689        )
    1690        alias = self.sql(expression, "alias")
    1691        alias = f" {alias}" if alias else ""
    1692        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    1694    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    1695        limit: t.Optional[exp.Fetch | exp.Limit] = expression.args.get("limit")
    1696
    1697        # If the limit is generated as TOP, we need to ensure it's not generated twice
    1698        with_offset_limit_modifiers = not isinstance(limit, exp.Limit) or not self.LIMIT_IS_TOP
    1699
    1700        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    1701            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    1702        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    1703            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    1704
    1705        fetch = isinstance(limit, exp.Fetch)
    1706
    1707        offset_limit_modifiers = (
    1708            self.offset_limit_modifiers(expression, fetch, limit)
    1709            if with_offset_limit_modifiers
    1710            else []
    1711        )
    1712
    1713        return csv(
    1714            *sqls,
    1715            *[self.sql(join) for join in expression.args.get("joins") or []],
    1716            self.sql(expression, "connect"),
    1717            self.sql(expression, "match"),
    1718            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    1719            self.sql(expression, "where"),
    1720            self.sql(expression, "group"),
    1721            self.sql(expression, "having"),
    1722            *self.after_having_modifiers(expression),
    1723            self.sql(expression, "order"),
    1724            *offset_limit_modifiers,
    1725            *self.after_limit_modifiers(expression),
    1726            sep="",
    1727        )

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

    1729    def offset_limit_modifiers(
    1730        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    1731    ) -> t.List[str]:
    1732        return [
    1733            self.sql(expression, "offset") if fetch else self.sql(limit),
    1734            self.sql(limit) if fetch else self.sql(expression, "offset"),
    1735        ]

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

    1737    def after_having_modifiers(self, expression: exp.Expression) -> t.List[str]:
    1738        return [
    1739            self.sql(expression, "qualify"),
    1740            self.seg("WINDOW ") + self.expressions(expression, key="windows", flat=True)
    1741            if expression.args.get("windows")
    1742            else "",
    1743            self.sql(expression, "distribute"),
    1744            self.sql(expression, "sort"),
    1745            self.sql(expression, "cluster"),
    1746        ]

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

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

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

    1753    def select_sql(self, expression: exp.Select) -> str:
    1754        hint = self.sql(expression, "hint")
    1755        distinct = self.sql(expression, "distinct")
    1756        distinct = f" {distinct}" if distinct else ""
    1757        kind = self.sql(expression, "kind").upper()
    1758        limit = expression.args.get("limit")
    1759        top = (
    1760            self.limit_sql(limit, top=True)
    1761            if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP
    1762            else ""
    1763        )
    1764
    1765        expressions = self.expressions(expression)
    1766
    1767        if kind:
    1768            if kind in self.SELECT_KINDS:
    1769                kind = f" AS {kind}"
    1770            else:
    1771                if kind == "STRUCT":
    1772                    expressions = self.expressions(
    1773                        sqls=[
    1774                            self.sql(
    1775                                exp.Struct(
    1776                                    expressions=[
    1777                                        exp.column(e.output_name).eq(
    1778                                            e.this if isinstance(e, exp.Alias) else e
    1779                                        )
    1780                                        for e in expression.expressions
    1781                                    ]
    1782                                )
    1783                            )
    1784                        ]
    1785                    )
    1786                kind = ""
    1787
    1788        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    1789        sql = self.query_modifiers(
    1790            expression,
    1791            f"SELECT{top}{hint}{distinct}{kind}{expressions}",
    1792            self.sql(expression, "into", comment=False),
    1793            self.sql(expression, "from", comment=False),
    1794        )
    1795        return self.prepend_ctes(expression, sql)

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

    1797    def schema_sql(self, expression: exp.Schema) -> str:
    1798        this = self.sql(expression, "this")
    1799        this = f"{this} " if this else ""
    1800        sql = self.schema_columns_sql(expression)
    1801        return f"{this}{sql}"

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

    1803    def schema_columns_sql(self, expression: exp.Schema) -> str:
    1804        return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"

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

    1806    def star_sql(self, expression: exp.Star) -> str:
    1807        except_ = self.expressions(expression, key="except", flat=True)
    1808        except_ = f"{self.seg(self.STAR_MAPPING['except'])} ({except_})" if except_ else ""
    1809        replace = self.expressions(expression, key="replace", flat=True)
    1810        replace = f"{self.seg(self.STAR_MAPPING['replace'])} ({replace})" if replace else ""
    1811        return f"*{except_}{replace}"

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

    1813    def parameter_sql(self, expression: exp.Parameter) -> str:
    1814        this = self.sql(expression, "this")
    1815        this = f"{{{this}}}" if expression.args.get("wrapped") else f"{this}"
    1816        return f"{self.PARAMETER_TOKEN}{this}"

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

    1818    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    1819        this = self.sql(expression, "this")
    1820        kind = expression.text("kind")
    1821        if kind:
    1822            kind = f"{kind}."
    1823        return f"@@{kind}{this}"

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

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

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

    1828    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    1829        alias = self.sql(expression, "alias")
    1830        alias = f"{sep}{alias}" if alias else ""
    1831
    1832        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1833        pivots = f" {pivots}" if pivots else ""
    1834
    1835        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    1836        return self.prepend_ctes(expression, sql)

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

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

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

    1842    def union_sql(self, expression: exp.Union) -> str:
    1843        return self.prepend_ctes(
    1844            expression,
    1845            self.set_operation(expression, self.union_op(expression)),
    1846        )

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

    1848    def union_op(self, expression: exp.Union) -> str:
    1849        kind = " DISTINCT" if self.EXPLICIT_UNION else ""
    1850        kind = kind if expression.args.get("distinct") else " ALL"
    1851        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1852        return f"UNION{kind}{by_name}"

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

    1854    def unnest_sql(self, expression: exp.Unnest) -> str:
    1855        args = self.expressions(expression, flat=True)
    1856        alias = expression.args.get("alias")
    1857        if alias and self.UNNEST_COLUMN_ONLY:
    1858            columns = alias.columns
    1859            alias = self.sql(columns[0]) if columns else ""
    1860        else:
    1861            alias = self.sql(expression, "alias")
    1862        alias = f" AS {alias}" if alias else alias
    1863        ordinality = " WITH ORDINALITY" if expression.args.get("ordinality") else ""
    1864        offset = expression.args.get("offset")
    1865        offset = f" WITH OFFSET AS {self.sql(offset)}" if offset else ""
    1866        return f"UNNEST({args}){ordinality}{alias}{offset}"

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

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

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

    1872    def window_sql(self, expression: exp.Window) -> str:
    1873        this = self.sql(expression, "this")
    1874        partition = self.partition_by_sql(expression)
    1875        order = expression.args.get("order")
    1876        order = self.order_sql(order, flat=True) if order else ""
    1877        spec = self.sql(expression, "spec")
    1878        alias = self.sql(expression, "alias")
    1879        over = self.sql(expression, "over") or "OVER"
    1880
    1881        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    1882
    1883        first = expression.args.get("first")
    1884        if first is None:
    1885            first = ""
    1886        else:
    1887            first = "FIRST" if first else "LAST"
    1888
    1889        if not partition and not order and not spec and alias:
    1890            return f"{this} {alias}"
    1891
    1892        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    1893        return f"{this} ({args})"

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

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

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

    1899    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    1900        kind = self.sql(expression, "kind")
    1901        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    1902        end = (
    1903            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    1904            or "CURRENT ROW"
    1905        )
    1906        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    1913    def between_sql(self, expression: exp.Between) -> str:
    1914        this = self.sql(expression, "this")
    1915        low = self.sql(expression, "low")
    1916        high = self.sql(expression, "high")
    1917        return f"{this} BETWEEN {low} AND {high}"

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

    1919    def bracket_sql(self, expression: exp.Bracket) -> str:
    1920        expressions = apply_index_offset(expression.this, expression.expressions, self.INDEX_OFFSET)
    1921        expressions_sql = ", ".join(self.sql(e) for e in expressions)
    1922
    1923        return f"{self.sql(expression, 'this')}[{expressions_sql}]"

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

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

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

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

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

    1931    def any_sql(self, expression: exp.Any) -> str:
    1932        this = self.sql(expression, "this")
    1933        if isinstance(expression.this, exp.Subqueryable):
    1934            this = self.wrap(this)
    1935        return f"ANY {this}"

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

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

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

    1940    def case_sql(self, expression: exp.Case) -> str:
    1941        this = self.sql(expression, "this")
    1942        statements = [f"CASE {this}" if this else "CASE"]
    1943
    1944        for e in expression.args["ifs"]:
    1945            statements.append(f"WHEN {self.sql(e, 'this')}")
    1946            statements.append(f"THEN {self.sql(e, 'true')}")
    1947
    1948        default = self.sql(expression, "default")
    1949
    1950        if default:
    1951            statements.append(f"ELSE {default}")
    1952
    1953        statements.append("END")
    1954
    1955        if self.pretty and self.text_width(statements) > self.max_text_width:
    1956            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    1957
    1958        return " ".join(statements)

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

    1960    def constraint_sql(self, expression: exp.Constraint) -> str:
    1961        this = self.sql(expression, "this")
    1962        expressions = self.expressions(expression, flat=True)
    1963        return f"CONSTRAINT {this} {expressions}"

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

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

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

    1970    def extract_sql(self, expression: exp.Extract) -> str:
    1971        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    1972        expression_sql = self.sql(expression, "expression")
    1973        return f"EXTRACT({this} FROM {expression_sql})"

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

    1975    def trim_sql(self, expression: exp.Trim) -> str:
    1976        trim_type = self.sql(expression, "position")
    1977
    1978        if trim_type == "LEADING":
    1979            return self.func("LTRIM", expression.this)
    1980        elif trim_type == "TRAILING":
    1981            return self.func("RTRIM", expression.this)
    1982        else:
    1983            return self.func("TRIM", expression.this, expression.expression)

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

    1985    def safeconcat_sql(self, expression: exp.SafeConcat) -> str:
    1986        expressions = expression.expressions
    1987        if self.STRICT_STRING_CONCAT:
    1988            expressions = (exp.cast(e, "text") for e in expressions)
    1989        return self.func("CONCAT", *expressions)

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

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

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

    1995    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    1996        expressions = self.expressions(expression, flat=True)
    1997        reference = self.sql(expression, "reference")
    1998        reference = f" {reference}" if reference else ""
    1999        delete = self.sql(expression, "delete")
    2000        delete = f" ON DELETE {delete}" if delete else ""
    2001        update = self.sql(expression, "update")
    2002        update = f" ON UPDATE {update}" if update else ""
    2003        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"

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

    2005    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2006        expressions = self.expressions(expression, flat=True)
    2007        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2008        options = f" {options}" if options else ""
    2009        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

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

    2023    def jsonobject_sql(self, expression: exp.JSONObject) -> str:
    2024        null_handling = expression.args.get("null_handling")
    2025        null_handling = f" {null_handling}" if null_handling else ""
    2026        unique_keys = expression.args.get("unique_keys")
    2027        if unique_keys is not None:
    2028            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2029        else:
    2030            unique_keys = ""
    2031        return_type = self.sql(expression, "return_type")
    2032        return_type = f" RETURNING {return_type}" if return_type else ""
    2033        format_json = " FORMAT JSON" if expression.args.get("format_json") else ""
    2034        encoding = self.sql(expression, "encoding")
    2035        encoding = f" ENCODING {encoding}" if encoding else ""
    2036        return self.func(
    2037            "JSON_OBJECT",
    2038            *expression.expressions,
    2039            suffix=f"{null_handling}{unique_keys}{return_type}{format_json}{encoding})",
    2040        )

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

    2042    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    2043        this = self.sql(expression, "this")
    2044        kind = self.sql(expression, "kind")
    2045        path = self.sql(expression, "path")
    2046        path = f" {path}" if path else ""
    2047        as_json = " AS JSON" if expression.args.get("as_json") else ""
    2048        return f"{this} {kind}{path}{as_json}"

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

    2050    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    2051        this = self.sql(expression, "this")
    2052        path = self.sql(expression, "path")
    2053        path = f", {path}" if path else ""
    2054        expressions = self.expressions(expression)
    2055        with_ = (
    2056            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2057            if expressions
    2058            else ""
    2059        )
    2060        return f"OPENJSON({this}{path}){with_}"

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

    2062    def in_sql(self, expression: exp.In) -> str:
    2063        query = expression.args.get("query")
    2064        unnest = expression.args.get("unnest")
    2065        field = expression.args.get("field")
    2066        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    2067
    2068        if query:
    2069            in_sql = self.wrap(query)
    2070        elif unnest:
    2071            in_sql = self.in_unnest_op(unnest)
    2072        elif field:
    2073            in_sql = self.sql(field)
    2074        else:
    2075            in_sql = f"({self.expressions(expression, flat=True)})"
    2076
    2077        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    2082    def interval_sql(self, expression: exp.Interval) -> str:
    2083        unit = self.sql(expression, "unit")
    2084        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    2085            unit = self.TIME_PART_SINGULARS.get(unit.lower(), unit)
    2086        unit = f" {unit}" if unit else ""
    2087
    2088        if self.SINGLE_STRING_INTERVAL:
    2089            this = expression.this.name if expression.this else ""
    2090            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    2091
    2092        this = self.sql(expression, "this")
    2093        if this:
    2094            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    2095            this = f" {this}" if unwrapped else f" ({this})"
    2096
    2097        return f"INTERVAL{this}{unit}"

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

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

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

    2102    def reference_sql(self, expression: exp.Reference) -> str:
    2103        this = self.sql(expression, "this")
    2104        expressions = self.expressions(expression, flat=True)
    2105        expressions = f"({expressions})" if expressions else ""
    2106        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2107        options = f" {options}" if options else ""
    2108        return f"REFERENCES {this}{expressions}{options}"

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

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

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

    2113    def paren_sql(self, expression: exp.Paren) -> str:
    2114        if isinstance(expression.unnest(), exp.Select):
    2115            sql = self.wrap(expression)
    2116        else:
    2117            sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
    2118            sql = f"({sql}{self.seg(')', sep='')}"
    2119
    2120        return self.prepend_ctes(expression, sql)

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

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

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

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

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

    2131    def alias_sql(self, expression: exp.Alias) -> str:
    2132        alias = self.sql(expression, "alias")
    2133        alias = f" AS {alias}" if alias else ""
    2134        return f"{self.sql(expression, 'this')}{alias}"

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

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

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

    2139    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    2140        this = self.sql(expression, "this")
    2141        zone = self.sql(expression, "zone")
    2142        return f"{this} AT TIME ZONE {zone}"

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

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

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

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

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

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

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

    2153    def connector_sql(self, expression: exp.Connector, op: str) -> str:
    2154        if not self.pretty:
    2155            return self.binary(expression, op)
    2156
    2157        sqls = tuple(
    2158            self.maybe_comment(self.sql(e), e, e.parent.comments or []) if i != 1 else self.sql(e)
    2159            for i, e in enumerate(expression.flatten(unnest=False))
    2160        )
    2161
    2162        sep = "\n" if self.text_width(sqls) > self.max_text_width else " "
    2163        return f"{sep}{op} ".join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

    2183    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    2184        format_sql = self.sql(expression, "format")
    2185        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    2186        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS {self.sql(expression, 'to')}{format_sql})"

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

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

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

    2192    def collate_sql(self, expression: exp.Collate) -> str:
    2193        return self.binary(expression, "COLLATE")

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

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

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

    2198    def comment_sql(self, expression: exp.Comment) -> str:
    2199        this = self.sql(expression, "this")
    2200        kind = expression.args["kind"]
    2201        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    2202        expression_sql = self.sql(expression, "expression")
    2203        return f"COMMENT{exists_sql}ON {kind} {this} IS {expression_sql}"

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

    2205    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    2206        this = self.sql(expression, "this")
    2207        delete = " DELETE" if expression.args.get("delete") else ""
    2208        recompress = self.sql(expression, "recompress")
    2209        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    2210        to_disk = self.sql(expression, "to_disk")
    2211        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    2212        to_volume = self.sql(expression, "to_volume")
    2213        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    2214        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    2216    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    2217        where = self.sql(expression, "where")
    2218        group = self.sql(expression, "group")
    2219        aggregates = self.expressions(expression, key="aggregates")
    2220        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    2221
    2222        if not (where or group or aggregates) and len(expression.expressions) == 1:
    2223            return f"TTL {self.expressions(expression, flat=True)}"
    2224
    2225        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    2230    def commit_sql(self, expression: exp.Commit) -> str:
    2231        chain = expression.args.get("chain")
    2232        if chain is not None:
    2233            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    2234
    2235        return f"COMMIT{chain or ''}"

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

    2237    def rollback_sql(self, expression: exp.Rollback) -> str:
    2238        savepoint = expression.args.get("savepoint")
    2239        savepoint = f" TO {savepoint}" if savepoint else ""
    2240        return f"ROLLBACK{savepoint}"

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

    2242    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    2243        this = self.sql(expression, "this")
    2244
    2245        dtype = self.sql(expression, "dtype")
    2246        if dtype:
    2247            collate = self.sql(expression, "collate")
    2248            collate = f" COLLATE {collate}" if collate else ""
    2249            using = self.sql(expression, "using")
    2250            using = f" USING {using}" if using else ""
    2251            return f"ALTER COLUMN {this} TYPE {dtype}{collate}{using}"
    2252
    2253        default = self.sql(expression, "default")
    2254        if default:
    2255            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    2256
    2257        if not expression.args.get("drop"):
    2258            self.unsupported("Unsupported ALTER COLUMN syntax")
    2259
    2260        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    2262    def renametable_sql(self, expression: exp.RenameTable) -> str:
    2263        if not self.RENAME_TABLE_WITH_DB:
    2264            # Remove db from tables
    2265            expression = expression.transform(
    2266                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    2267            )
    2268        this = self.sql(expression, "this")
    2269        return f"RENAME TO {this}"

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

    2271    def altertable_sql(self, expression: exp.AlterTable) -> str:
    2272        actions = expression.args["actions"]
    2273
    2274        if isinstance(actions[0], exp.ColumnDef):
    2275            if self.ALTER_TABLE_ADD_COLUMN_KEYWORD:
    2276                actions = self.expressions(
    2277                    expression,
    2278                    key="actions",
    2279                    prefix="ADD COLUMN ",
    2280                )
    2281            else:
    2282                actions = f"ADD {self.expressions(expression, key='actions')}"
    2283        elif isinstance(actions[0], exp.Schema):
    2284            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    2285        elif isinstance(actions[0], exp.Delete):
    2286            actions = self.expressions(expression, key="actions", flat=True)
    2287        else:
    2288            actions = self.expressions(expression, key="actions")
    2289
    2290        exists = " IF EXISTS" if expression.args.get("exists") else ""
    2291        return f"ALTER TABLE{exists} {self.sql(expression, 'this')} {actions}"

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

    2293    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    2294        expressions = self.expressions(expression)
    2295        exists = " IF EXISTS " if expression.args.get("exists") else " "
    2296        return f"DROP{exists}{expressions}"

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

    2298    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
    2299        this = self.sql(expression, "this")
    2300        expression_ = self.sql(expression, "expression")
    2301        add_constraint = f"ADD CONSTRAINT {this}" if this else "ADD"
    2302
    2303        enforced = expression.args.get("enforced")
    2304        if enforced is not None:
    2305            return f"{add_constraint} CHECK ({expression_}){' ENFORCED' if enforced else ''}"
    2306
    2307        return f"{add_constraint} {expression_}"

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

    2309    def distinct_sql(self, expression: exp.Distinct) -> str:
    2310        this = self.expressions(expression, flat=True)
    2311        this = f" {this}" if this else ""
    2312
    2313        on = self.sql(expression, "on")
    2314        on = f" ON {on}" if on else ""
    2315        return f"DISTINCT{this}{on}"

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

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

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

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

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

    2323    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    2324        return self.sql(
    2325            exp.Cast(
    2326                this=exp.Div(this=expression.this.copy(), expression=expression.expression.copy()),
    2327                to=exp.DataType(this=exp.DataType.Type.INT),
    2328            )
    2329        )

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

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

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

    2334    def safedpipe_sql(self, expression: exp.SafeDPipe) -> str:
    2335        if self.STRICT_STRING_CONCAT:
    2336            return self.func("CONCAT", *(exp.cast(e, "text") for e in expression.flatten()))
    2337        return self.dpipe_sql(expression)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2372    def is_sql(self, expression: exp.Is) -> str:
    2373        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    2374            return self.sql(
    2375                expression.this if expression.expression.this else exp.not_(expression.this)
    2376            )
    2377        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2421    def use_sql(self, expression: exp.Use) -> str:
    2422        kind = self.sql(expression, "kind")
    2423        kind = f" {kind}" if kind else ""
    2424        this = self.sql(expression, "this")
    2425        this = f" {this}" if this else ""
    2426        return f"USE{kind}{this}"

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

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

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

    2432    def function_fallback_sql(self, expression: exp.Func) -> str:
    2433        args = []
    2434
    2435        for key in expression.arg_types:
    2436            arg_value = expression.args.get(key)
    2437
    2438            if isinstance(arg_value, list):
    2439                for value in arg_value:
    2440                    args.append(value)
    2441            elif arg_value is not None:
    2442                args.append(arg_value)
    2443
    2444        if self.normalize_functions:
    2445            name = expression.sql_name()
    2446        else:
    2447            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    2448
    2449        return self.func(name, *args)

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

    2451    def func(
    2452        self,
    2453        name: str,
    2454        *args: t.Optional[exp.Expression | str],
    2455        prefix: str = "(",
    2456        suffix: str = ")",
    2457    ) -> str:
    2458        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

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

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

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

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

    2469    def format_time(self, expression: exp.Expression) -> t.Optional[str]:
    2470        return format_time(
    2471            self.sql(expression, "format"), self.INVERSE_TIME_MAPPING, self.INVERSE_TIME_TRIE
    2472        )

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

    2474    def expressions(
    2475        self,
    2476        expression: t.Optional[exp.Expression] = None,
    2477        key: t.Optional[str] = None,
    2478        sqls: t.Optional[t.List[str]] = None,
    2479        flat: bool = False,
    2480        indent: bool = True,
    2481        skip_first: bool = False,
    2482        sep: str = ", ",
    2483        prefix: str = "",
    2484    ) -> str:
    2485        expressions = expression.args.get(key or "expressions") if expression else sqls
    2486
    2487        if not expressions:
    2488            return ""
    2489
    2490        if flat:
    2491            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    2492
    2493        num_sqls = len(expressions)
    2494
    2495        # These are calculated once in case we have the leading_comma / pretty option set, correspondingly
    2496        pad = " " * self.pad
    2497        stripped_sep = sep.strip()
    2498
    2499        result_sqls = []
    2500        for i, e in enumerate(expressions):
    2501            sql = self.sql(e, comment=False)
    2502            if not sql:
    2503                continue
    2504
    2505            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    2506
    2507            if self.pretty:
    2508                if self.leading_comma:
    2509                    result_sqls.append(f"{sep if i > 0 else pad}{prefix}{sql}{comments}")
    2510                else:
    2511                    result_sqls.append(
    2512                        f"{prefix}{sql}{stripped_sep if i + 1 < num_sqls else ''}{comments}"
    2513                    )
    2514            else:
    2515                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    2516
    2517        result_sql = "\n".join(result_sqls) if self.pretty else "".join(result_sqls)
    2518        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

    2520    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    2521        flat = flat or isinstance(expression.parent, exp.Properties)
    2522        expressions_sql = self.expressions(expression, flat=flat)
    2523        if flat:
    2524            return f"{op} {expressions_sql}"
    2525        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    2527    def naked_property(self, expression: exp.Property) -> str:
    2528        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    2529        if not property_name:
    2530            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    2531        return f"{property_name} {self.sql(expression, 'this')}"

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

    2533    def set_operation(self, expression: exp.Expression, op: str) -> str:
    2534        this = self.sql(expression, "this")
    2535        op = self.seg(op)
    2536        return self.query_modifiers(
    2537            expression, f"{this}{op}{self.sep()}{self.sql(expression, 'expression')}"
    2538        )

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

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

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

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

    2546    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    2547        this = self.sql(expression, "this")
    2548        expressions = self.no_identify(self.expressions, expression)
    2549        expressions = (
    2550            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    2551        )
    2552        return f"{this}{expressions}"

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

    2554    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    2555        this = self.sql(expression, "this")
    2556        expressions = self.expressions(expression, flat=True)
    2557        return f"{this}({expressions})"

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

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

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

    2562    def when_sql(self, expression: exp.When) -> str:
    2563        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    2564        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    2565        condition = self.sql(expression, "condition")
    2566        condition = f" AND {condition}" if condition else ""
    2567
    2568        then_expression = expression.args.get("then")
    2569        if isinstance(then_expression, exp.Insert):
    2570            then = f"INSERT {self.sql(then_expression, 'this')}"
    2571            if "expression" in then_expression.args:
    2572                then += f" VALUES {self.sql(then_expression, 'expression')}"
    2573        elif isinstance(then_expression, exp.Update):
    2574            if isinstance(then_expression.args.get("expressions"), exp.Star):
    2575                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    2576            else:
    2577                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    2578        else:
    2579            then = self.sql(then_expression)
    2580        return f"WHEN {matched}{source}{condition} THEN {then}"

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

    2582    def merge_sql(self, expression: exp.Merge) -> str:
    2583        table = expression.this
    2584        table_alias = ""
    2585
    2586        hints = table.args.get("hints")
    2587        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    2588            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    2589            table = table.copy()
    2590            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    2591
    2592        this = self.sql(table)
    2593        using = f"USING {self.sql(expression, 'using')}"
    2594        on = f"ON {self.sql(expression, 'on')}"
    2595        expressions = self.expressions(expression, sep=" ")
    2596
    2597        return f"MERGE INTO {this}{table_alias} {using} {on} {expressions}"

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

    2599    def tochar_sql(self, expression: exp.ToChar) -> str:
    2600        if expression.args.get("format"):
    2601            self.unsupported("Format argument unsupported for TO_CHAR/TO_VARCHAR function")
    2602
    2603        return self.sql(exp.cast(expression.this, "text"))

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

    2605    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    2606        this = self.sql(expression, "this")
    2607        kind = self.sql(expression, "kind")
    2608        settings_sql = self.expressions(expression, key="settings", sep=" ")
    2609        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    2610        return f"{this}({kind}{args})"

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

    2612    def dictrange_sql(self, expression: exp.DictRange) -> str:
    2613        this = self.sql(expression, "this")
    2614        max = self.sql(expression, "max")
    2615        min = self.sql(expression, "min")
    2616        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

    2624    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    2625        expressions = self.expressions(expression, key="expressions", flat=True)
    2626        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    2627        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    2628        buckets = self.sql(expression, "buckets")
    2629        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    2631    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    2632        this = self.sql(expression, "this")
    2633        having = self.sql(expression, "having")
    2634
    2635        if having:
    2636            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    2637
    2638        return self.func("ANY_VALUE", this)

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

    2640    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    2641        transform = self.func("TRANSFORM", *expression.expressions)
    2642        row_format_before = self.sql(expression, "row_format_before")
    2643        row_format_before = f" {row_format_before}" if row_format_before else ""
    2644        record_writer = self.sql(expression, "record_writer")
    2645        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    2646        using = f" USING {self.sql(expression, 'command_script')}"
    2647        schema = self.sql(expression, "schema")
    2648        schema = f" AS {schema}" if schema else ""
    2649        row_format_after = self.sql(expression, "row_format_after")
    2650        row_format_after = f" {row_format_after}" if row_format_after else ""
    2651        record_reader = self.sql(expression, "record_reader")
    2652        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    2653        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

    2655    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    2656        key_block_size = self.sql(expression, "key_block_size")
    2657        if key_block_size:
    2658            return f"KEY_BLOCK_SIZE = {key_block_size}"
    2659
    2660        using = self.sql(expression, "using")
    2661        if using:
    2662            return f"USING {using}"
    2663
    2664        parser = self.sql(expression, "parser")
    2665        if parser:
    2666            return f"WITH PARSER {parser}"
    2667
    2668        comment = self.sql(expression, "comment")
    2669        if comment:
    2670            return f"COMMENT {comment}"
    2671
    2672        visible = expression.args.get("visible")
    2673        if visible is not None:
    2674            return "VISIBLE" if visible else "INVISIBLE"
    2675
    2676        engine_attr = self.sql(expression, "engine_attr")
    2677        if engine_attr:
    2678            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    2679
    2680        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    2681        if secondary_engine_attr:
    2682            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    2683
    2684        self.unsupported("Unsupported index constraint option.")
    2685        return ""

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

    2687    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    2688        kind = self.sql(expression, "kind")
    2689        kind = f"{kind} INDEX" if kind else "INDEX"
    2690        this = self.sql(expression, "this")
    2691        this = f" {this}" if this else ""
    2692        type_ = self.sql(expression, "type")
    2693        type_ = f" USING {type_}" if type_ else ""
    2694        schema = self.sql(expression, "schema")
    2695        schema = f" {schema}" if schema else ""
    2696        options = self.expressions(expression, key="options", sep=" ")
    2697        options = f" {options}" if options else ""
    2698        return f"{kind}{this}{type_}{schema}{options}"

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

    2700    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    2701        if self.NVL2_SUPPORTED:
    2702            return self.function_fallback_sql(expression)
    2703
    2704        case = exp.Case().when(
    2705            expression.this.is_(exp.null()).not_(copy=False),
    2706            expression.args["true"].copy(),
    2707            copy=False,
    2708        )
    2709        else_cond = expression.args.get("false")
    2710        if else_cond:
    2711            case.else_(else_cond.copy(), copy=False)
    2712
    2713        return self.sql(case)

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

    2715    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    2716        this = self.sql(expression, "this")
    2717        expr = self.sql(expression, "expression")
    2718        iterator = self.sql(expression, "iterator")
    2719        condition = self.sql(expression, "condition")
    2720        condition = f" IF {condition}" if condition else ""
    2721        return f"{this} FOR {expr} IN {iterator}{condition}"

def cached_generator( cache: Optional[Dict[int, str]] = None) -> Callable[[sqlglot.expressions.Expression], str]: View Source

    2724def cached_generator(
    2725    cache: t.Optional[t.Dict[int, str]] = None
    2726) -> t.Callable[[exp.Expression], str]:
    2727    """Returns a cached generator."""
    2728    cache = {} if cache is None else cache
    2729    generator = Generator(normalize=True, identify="safe")
    2730    return lambda e: generator.generate(e, cache)

Returns a cached generator.