sqlglot.dialects.clickhouse API documentation

Edit on GitHub

# sqlglot.dialects.clickhouse

View Source

      1from __future__ import annotations
      2
      3import typing as t
      4
      5from sqlglot import exp, generator, parser, tokens
      6from sqlglot.dialects.dialect import (
      7    Dialect,
      8    inline_array_sql,
      9    no_pivot_sql,
     10    rename_func,
     11    var_map_sql,
     12)
     13from sqlglot.errors import ParseError
     14from sqlglot.parser import parse_var_map
     15from sqlglot.tokens import Token, TokenType
     16
     17
     18def _lower_func(sql: str) -> str:
     19    index = sql.index("(")
     20    return sql[:index].lower() + sql[index:]
     21
     22
     23class ClickHouse(Dialect):
     24    NORMALIZE_FUNCTIONS: bool | str = False
     25    NULL_ORDERING = "nulls_are_last"
     26    STRICT_STRING_CONCAT = True
     27
     28    class Tokenizer(tokens.Tokenizer):
     29        COMMENTS = ["--", "#", "#!", ("/*", "*/")]
     30        IDENTIFIERS = ['"', "`"]
     31        STRING_ESCAPES = ["'", "\\"]
     32        BIT_STRINGS = [("0b", "")]
     33        HEX_STRINGS = [("0x", ""), ("0X", "")]
     34
     35        KEYWORDS = {
     36            **tokens.Tokenizer.KEYWORDS,
     37            "ATTACH": TokenType.COMMAND,
     38            "DATETIME64": TokenType.DATETIME64,
     39            "DICTIONARY": TokenType.DICTIONARY,
     40            "FINAL": TokenType.FINAL,
     41            "FLOAT32": TokenType.FLOAT,
     42            "FLOAT64": TokenType.DOUBLE,
     43            "GLOBAL": TokenType.GLOBAL,
     44            "INT128": TokenType.INT128,
     45            "INT16": TokenType.SMALLINT,
     46            "INT256": TokenType.INT256,
     47            "INT32": TokenType.INT,
     48            "INT64": TokenType.BIGINT,
     49            "INT8": TokenType.TINYINT,
     50            "MAP": TokenType.MAP,
     51            "TUPLE": TokenType.STRUCT,
     52            "UINT128": TokenType.UINT128,
     53            "UINT16": TokenType.USMALLINT,
     54            "UINT256": TokenType.UINT256,
     55            "UINT32": TokenType.UINT,
     56            "UINT64": TokenType.UBIGINT,
     57            "UINT8": TokenType.UTINYINT,
     58        }
     59
     60    class Parser(parser.Parser):
     61        FUNCTIONS = {
     62            **parser.Parser.FUNCTIONS,
     63            "ANY": exp.AnyValue.from_arg_list,
     64            "MAP": parse_var_map,
     65            "MATCH": exp.RegexpLike.from_arg_list,
     66            "UNIQ": exp.ApproxDistinct.from_arg_list,
     67            "XOR": lambda args: exp.Xor(expressions=args),
     68        }
     69
     70        FUNCTIONS_WITH_ALIASED_ARGS = {*parser.Parser.FUNCTIONS_WITH_ALIASED_ARGS, "TUPLE"}
     71
     72        FUNCTION_PARSERS = {
     73            **parser.Parser.FUNCTION_PARSERS,
     74            "QUANTILE": lambda self: self._parse_quantile(),
     75        }
     76
     77        FUNCTION_PARSERS.pop("MATCH")
     78
     79        NO_PAREN_FUNCTION_PARSERS = parser.Parser.NO_PAREN_FUNCTION_PARSERS.copy()
     80        NO_PAREN_FUNCTION_PARSERS.pop(TokenType.ANY)
     81
     82        RANGE_PARSERS = {
     83            **parser.Parser.RANGE_PARSERS,
     84            TokenType.GLOBAL: lambda self, this: self._match(TokenType.IN)
     85            and self._parse_in(this, is_global=True),
     86        }
     87
     88        # The PLACEHOLDER entry is popped because 1) it doesn't affect Clickhouse (it corresponds to
     89        # the postgres-specific JSONBContains parser) and 2) it makes parsing the ternary op simpler.
     90        COLUMN_OPERATORS = parser.Parser.COLUMN_OPERATORS.copy()
     91        COLUMN_OPERATORS.pop(TokenType.PLACEHOLDER)
     92
     93        JOIN_KINDS = {
     94            *parser.Parser.JOIN_KINDS,
     95            TokenType.ANY,
     96            TokenType.ASOF,
     97            TokenType.ANTI,
     98            TokenType.SEMI,
     99            TokenType.ARRAY,
    100        }
    101
    102        TABLE_ALIAS_TOKENS = {*parser.Parser.TABLE_ALIAS_TOKENS} - {
    103            TokenType.ANY,
    104            TokenType.SEMI,
    105            TokenType.ANTI,
    106            TokenType.SETTINGS,
    107            TokenType.FORMAT,
    108            TokenType.ARRAY,
    109        }
    110
    111        LOG_DEFAULTS_TO_LN = True
    112
    113        QUERY_MODIFIER_PARSERS = {
    114            **parser.Parser.QUERY_MODIFIER_PARSERS,
    115            TokenType.SETTINGS: lambda self: (
    116                "settings",
    117                self._advance() or self._parse_csv(self._parse_conjunction),
    118            ),
    119            TokenType.FORMAT: lambda self: ("format", self._advance() or self._parse_id_var()),
    120        }
    121
    122        def _parse_conjunction(self) -> t.Optional[exp.Expression]:
    123            this = super()._parse_conjunction()
    124
    125            if self._match(TokenType.PLACEHOLDER):
    126                return self.expression(
    127                    exp.If,
    128                    this=this,
    129                    true=self._parse_conjunction(),
    130                    false=self._match(TokenType.COLON) and self._parse_conjunction(),
    131                )
    132
    133            return this
    134
    135        def _parse_placeholder(self) -> t.Optional[exp.Expression]:
    136            """
    137            Parse a placeholder expression like SELECT {abc: UInt32} or FROM {table: Identifier}
    138            https://clickhouse.com/docs/en/sql-reference/syntax#defining-and-using-query-parameters
    139            """
    140            if not self._match(TokenType.L_BRACE):
    141                return None
    142
    143            this = self._parse_id_var()
    144            self._match(TokenType.COLON)
    145            kind = self._parse_types(check_func=False) or (
    146                self._match_text_seq("IDENTIFIER") and "Identifier"
    147            )
    148
    149            if not kind:
    150                self.raise_error("Expecting a placeholder type or 'Identifier' for tables")
    151            elif not self._match(TokenType.R_BRACE):
    152                self.raise_error("Expecting }")
    153
    154            return self.expression(exp.Placeholder, this=this, kind=kind)
    155
    156        def _parse_in(self, this: t.Optional[exp.Expression], is_global: bool = False) -> exp.In:
    157            this = super()._parse_in(this)
    158            this.set("is_global", is_global)
    159            return this
    160
    161        def _parse_table(
    162            self,
    163            schema: bool = False,
    164            joins: bool = False,
    165            alias_tokens: t.Optional[t.Collection[TokenType]] = None,
    166            parse_bracket: bool = False,
    167        ) -> t.Optional[exp.Expression]:
    168            this = super()._parse_table(
    169                schema=schema, joins=joins, alias_tokens=alias_tokens, parse_bracket=parse_bracket
    170            )
    171
    172            if self._match(TokenType.FINAL):
    173                this = self.expression(exp.Final, this=this)
    174
    175            return this
    176
    177        def _parse_position(self, haystack_first: bool = False) -> exp.StrPosition:
    178            return super()._parse_position(haystack_first=True)
    179
    180        # https://clickhouse.com/docs/en/sql-reference/statements/select/with/
    181        def _parse_cte(self) -> exp.CTE:
    182            index = self._index
    183            try:
    184                # WITH <identifier> AS <subquery expression>
    185                return super()._parse_cte()
    186            except ParseError:
    187                # WITH <expression> AS <identifier>
    188                self._retreat(index)
    189                statement = self._parse_statement()
    190
    191                if statement and isinstance(statement.this, exp.Alias):
    192                    self.raise_error("Expected CTE to have alias")
    193
    194                return self.expression(exp.CTE, this=statement, alias=statement and statement.this)
    195
    196        def _parse_join_parts(
    197            self,
    198        ) -> t.Tuple[t.Optional[Token], t.Optional[Token], t.Optional[Token]]:
    199            is_global = self._match(TokenType.GLOBAL) and self._prev
    200            kind_pre = self._match_set(self.JOIN_KINDS, advance=False) and self._prev
    201
    202            if kind_pre:
    203                kind = self._match_set(self.JOIN_KINDS) and self._prev
    204                side = self._match_set(self.JOIN_SIDES) and self._prev
    205                return is_global, side, kind
    206
    207            return (
    208                is_global,
    209                self._match_set(self.JOIN_SIDES) and self._prev,
    210                self._match_set(self.JOIN_KINDS) and self._prev,
    211            )
    212
    213        def _parse_join(
    214            self, skip_join_token: bool = False, parse_bracket: bool = False
    215        ) -> t.Optional[exp.Join]:
    216            join = super()._parse_join(skip_join_token=skip_join_token, parse_bracket=True)
    217
    218            if join:
    219                join.set("global", join.args.pop("method", None))
    220            return join
    221
    222        def _parse_function(
    223            self,
    224            functions: t.Optional[t.Dict[str, t.Callable]] = None,
    225            anonymous: bool = False,
    226            optional_parens: bool = True,
    227        ) -> t.Optional[exp.Expression]:
    228            func = super()._parse_function(
    229                functions=functions, anonymous=anonymous, optional_parens=optional_parens
    230            )
    231
    232            if isinstance(func, exp.Anonymous):
    233                params = self._parse_func_params(func)
    234
    235                if params:
    236                    return self.expression(
    237                        exp.ParameterizedAgg,
    238                        this=func.this,
    239                        expressions=func.expressions,
    240                        params=params,
    241                    )
    242
    243            return func
    244
    245        def _parse_func_params(
    246            self, this: t.Optional[exp.Func] = None
    247        ) -> t.Optional[t.List[t.Optional[exp.Expression]]]:
    248            if self._match_pair(TokenType.R_PAREN, TokenType.L_PAREN):
    249                return self._parse_csv(self._parse_lambda)
    250
    251            if self._match(TokenType.L_PAREN):
    252                params = self._parse_csv(self._parse_lambda)
    253                self._match_r_paren(this)
    254                return params
    255
    256            return None
    257
    258        def _parse_quantile(self) -> exp.Quantile:
    259            this = self._parse_lambda()
    260            params = self._parse_func_params()
    261            if params:
    262                return self.expression(exp.Quantile, this=params[0], quantile=this)
    263            return self.expression(exp.Quantile, this=this, quantile=exp.Literal.number(0.5))
    264
    265        def _parse_wrapped_id_vars(
    266            self, optional: bool = False
    267        ) -> t.List[t.Optional[exp.Expression]]:
    268            return super()._parse_wrapped_id_vars(optional=True)
    269
    270        def _parse_primary_key(
    271            self, wrapped_optional: bool = False, in_props: bool = False
    272        ) -> exp.PrimaryKeyColumnConstraint | exp.PrimaryKey:
    273            return super()._parse_primary_key(
    274                wrapped_optional=wrapped_optional or in_props, in_props=in_props
    275            )
    276
    277        def _parse_on_property(self) -> t.Optional[exp.Expression]:
    278            index = self._index
    279            if self._match_text_seq("CLUSTER"):
    280                this = self._parse_id_var()
    281                if this:
    282                    return self.expression(exp.OnCluster, this=this)
    283                else:
    284                    self._retreat(index)
    285            return None
    286
    287    class Generator(generator.Generator):
    288        QUERY_HINTS = False
    289        STRUCT_DELIMITER = ("(", ")")
    290
    291        TYPE_MAPPING = {
    292            **generator.Generator.TYPE_MAPPING,
    293            exp.DataType.Type.ARRAY: "Array",
    294            exp.DataType.Type.BIGINT: "Int64",
    295            exp.DataType.Type.DATETIME64: "DateTime64",
    296            exp.DataType.Type.DOUBLE: "Float64",
    297            exp.DataType.Type.FLOAT: "Float32",
    298            exp.DataType.Type.INT: "Int32",
    299            exp.DataType.Type.INT128: "Int128",
    300            exp.DataType.Type.INT256: "Int256",
    301            exp.DataType.Type.MAP: "Map",
    302            exp.DataType.Type.NULLABLE: "Nullable",
    303            exp.DataType.Type.SMALLINT: "Int16",
    304            exp.DataType.Type.STRUCT: "Tuple",
    305            exp.DataType.Type.TINYINT: "Int8",
    306            exp.DataType.Type.UBIGINT: "UInt64",
    307            exp.DataType.Type.UINT: "UInt32",
    308            exp.DataType.Type.UINT128: "UInt128",
    309            exp.DataType.Type.UINT256: "UInt256",
    310            exp.DataType.Type.USMALLINT: "UInt16",
    311            exp.DataType.Type.UTINYINT: "UInt8",
    312        }
    313
    314        TRANSFORMS = {
    315            **generator.Generator.TRANSFORMS,
    316            exp.AnyValue: rename_func("any"),
    317            exp.ApproxDistinct: rename_func("uniq"),
    318            exp.Array: inline_array_sql,
    319            exp.CastToStrType: rename_func("CAST"),
    320            exp.Final: lambda self, e: f"{self.sql(e, 'this')} FINAL",
    321            exp.Map: lambda self, e: _lower_func(var_map_sql(self, e)),
    322            exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}",
    323            exp.Pivot: no_pivot_sql,
    324            exp.Quantile: lambda self, e: self.func("quantile", e.args.get("quantile"))
    325            + f"({self.sql(e, 'this')})",
    326            exp.RegexpLike: lambda self, e: f"match({self.format_args(e.this, e.expression)})",
    327            exp.StrPosition: lambda self, e: f"position({self.format_args(e.this, e.args.get('substr'), e.args.get('position'))})",
    328            exp.VarMap: lambda self, e: _lower_func(var_map_sql(self, e)),
    329            exp.Xor: lambda self, e: self.func("xor", e.this, e.expression, *e.expressions),
    330        }
    331
    332        PROPERTIES_LOCATION = {
    333            **generator.Generator.PROPERTIES_LOCATION,
    334            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    335            exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA,
    336            exp.OnCluster: exp.Properties.Location.POST_NAME,
    337        }
    338
    339        JOIN_HINTS = False
    340        TABLE_HINTS = False
    341        EXPLICIT_UNION = True
    342        GROUPINGS_SEP = ""
    343
    344        # there's no list in docs, but it can be found in Clickhouse code
    345        # see `ClickHouse/src/Parsers/ParserCreate*.cpp`
    346        ON_CLUSTER_TARGETS = {
    347            "DATABASE",
    348            "TABLE",
    349            "VIEW",
    350            "DICTIONARY",
    351            "INDEX",
    352            "FUNCTION",
    353            "NAMED COLLECTION",
    354        }
    355
    356        def safeconcat_sql(self, expression: exp.SafeConcat) -> str:
    357            # Clickhouse errors out if we try to cast a NULL value to TEXT
    358            return self.func(
    359                "CONCAT",
    360                *[
    361                    exp.func("if", e.is_(exp.null()), e, exp.cast(e, "text"))
    362                    for e in t.cast(t.List[exp.Condition], expression.expressions)
    363                ],
    364            )
    365
    366        def cte_sql(self, expression: exp.CTE) -> str:
    367            if isinstance(expression.this, exp.Alias):
    368                return self.sql(expression, "this")
    369
    370            return super().cte_sql(expression)
    371
    372        def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
    373            return super().after_limit_modifiers(expression) + [
    374                self.seg("SETTINGS ") + self.expressions(expression, key="settings", flat=True)
    375                if expression.args.get("settings")
    376                else "",
    377                self.seg("FORMAT ") + self.sql(expression, "format")
    378                if expression.args.get("format")
    379                else "",
    380            ]
    381
    382        def parameterizedagg_sql(self, expression: exp.Anonymous) -> str:
    383            params = self.expressions(expression, key="params", flat=True)
    384            return self.func(expression.name, *expression.expressions) + f"({params})"
    385
    386        def placeholder_sql(self, expression: exp.Placeholder) -> str:
    387            return f"{{{expression.name}: {self.sql(expression, 'kind')}}}"
    388
    389        def oncluster_sql(self, expression: exp.OnCluster) -> str:
    390            return f"ON CLUSTER {self.sql(expression, 'this')}"
    391
    392        def createable_sql(
    393            self,
    394            expression: exp.Create,
    395            locations: dict[exp.Properties.Location, list[exp.Property]],
    396        ) -> str:
    397            kind = self.sql(expression, "kind").upper()
    398            if kind in self.ON_CLUSTER_TARGETS and locations.get(exp.Properties.Location.POST_NAME):
    399                this_name = self.sql(expression.this, "this")
    400                this_properties = " ".join(
    401                    [self.sql(prop) for prop in locations[exp.Properties.Location.POST_NAME]]
    402                )
    403                this_schema = self.schema_columns_sql(expression.this)
    404                return f"{this_name}{self.sep()}{this_properties}{self.sep()}{this_schema}"
    405            return super().createable_sql(expression, locations)

class ClickHouse(sqlglot.dialects.dialect.Dialect): View Source

     24class ClickHouse(Dialect):
     25    NORMALIZE_FUNCTIONS: bool | str = False
     26    NULL_ORDERING = "nulls_are_last"
     27    STRICT_STRING_CONCAT = True
     28
     29    class Tokenizer(tokens.Tokenizer):
     30        COMMENTS = ["--", "#", "#!", ("/*", "*/")]
     31        IDENTIFIERS = ['"', "`"]
     32        STRING_ESCAPES = ["'", "\\"]
     33        BIT_STRINGS = [("0b", "")]
     34        HEX_STRINGS = [("0x", ""), ("0X", "")]
     35
     36        KEYWORDS = {
     37            **tokens.Tokenizer.KEYWORDS,
     38            "ATTACH": TokenType.COMMAND,
     39            "DATETIME64": TokenType.DATETIME64,
     40            "DICTIONARY": TokenType.DICTIONARY,
     41            "FINAL": TokenType.FINAL,
     42            "FLOAT32": TokenType.FLOAT,
     43            "FLOAT64": TokenType.DOUBLE,
     44            "GLOBAL": TokenType.GLOBAL,
     45            "INT128": TokenType.INT128,
     46            "INT16": TokenType.SMALLINT,
     47            "INT256": TokenType.INT256,
     48            "INT32": TokenType.INT,
     49            "INT64": TokenType.BIGINT,
     50            "INT8": TokenType.TINYINT,
     51            "MAP": TokenType.MAP,
     52            "TUPLE": TokenType.STRUCT,
     53            "UINT128": TokenType.UINT128,
     54            "UINT16": TokenType.USMALLINT,
     55            "UINT256": TokenType.UINT256,
     56            "UINT32": TokenType.UINT,
     57            "UINT64": TokenType.UBIGINT,
     58            "UINT8": TokenType.UTINYINT,
     59        }
     60
     61    class Parser(parser.Parser):
     62        FUNCTIONS = {
     63            **parser.Parser.FUNCTIONS,
     64            "ANY": exp.AnyValue.from_arg_list,
     65            "MAP": parse_var_map,
     66            "MATCH": exp.RegexpLike.from_arg_list,
     67            "UNIQ": exp.ApproxDistinct.from_arg_list,
     68            "XOR": lambda args: exp.Xor(expressions=args),
     69        }
     70
     71        FUNCTIONS_WITH_ALIASED_ARGS = {*parser.Parser.FUNCTIONS_WITH_ALIASED_ARGS, "TUPLE"}
     72
     73        FUNCTION_PARSERS = {
     74            **parser.Parser.FUNCTION_PARSERS,
     75            "QUANTILE": lambda self: self._parse_quantile(),
     76        }
     77
     78        FUNCTION_PARSERS.pop("MATCH")
     79
     80        NO_PAREN_FUNCTION_PARSERS = parser.Parser.NO_PAREN_FUNCTION_PARSERS.copy()
     81        NO_PAREN_FUNCTION_PARSERS.pop(TokenType.ANY)
     82
     83        RANGE_PARSERS = {
     84            **parser.Parser.RANGE_PARSERS,
     85            TokenType.GLOBAL: lambda self, this: self._match(TokenType.IN)
     86            and self._parse_in(this, is_global=True),
     87        }
     88
     89        # The PLACEHOLDER entry is popped because 1) it doesn't affect Clickhouse (it corresponds to
     90        # the postgres-specific JSONBContains parser) and 2) it makes parsing the ternary op simpler.
     91        COLUMN_OPERATORS = parser.Parser.COLUMN_OPERATORS.copy()
     92        COLUMN_OPERATORS.pop(TokenType.PLACEHOLDER)
     93
     94        JOIN_KINDS = {
     95            *parser.Parser.JOIN_KINDS,
     96            TokenType.ANY,
     97            TokenType.ASOF,
     98            TokenType.ANTI,
     99            TokenType.SEMI,
    100            TokenType.ARRAY,
    101        }
    102
    103        TABLE_ALIAS_TOKENS = {*parser.Parser.TABLE_ALIAS_TOKENS} - {
    104            TokenType.ANY,
    105            TokenType.SEMI,
    106            TokenType.ANTI,
    107            TokenType.SETTINGS,
    108            TokenType.FORMAT,
    109            TokenType.ARRAY,
    110        }
    111
    112        LOG_DEFAULTS_TO_LN = True
    113
    114        QUERY_MODIFIER_PARSERS = {
    115            **parser.Parser.QUERY_MODIFIER_PARSERS,
    116            TokenType.SETTINGS: lambda self: (
    117                "settings",
    118                self._advance() or self._parse_csv(self._parse_conjunction),
    119            ),
    120            TokenType.FORMAT: lambda self: ("format", self._advance() or self._parse_id_var()),
    121        }
    122
    123        def _parse_conjunction(self) -> t.Optional[exp.Expression]:
    124            this = super()._parse_conjunction()
    125
    126            if self._match(TokenType.PLACEHOLDER):
    127                return self.expression(
    128                    exp.If,
    129                    this=this,
    130                    true=self._parse_conjunction(),
    131                    false=self._match(TokenType.COLON) and self._parse_conjunction(),
    132                )
    133
    134            return this
    135
    136        def _parse_placeholder(self) -> t.Optional[exp.Expression]:
    137            """
    138            Parse a placeholder expression like SELECT {abc: UInt32} or FROM {table: Identifier}
    139            https://clickhouse.com/docs/en/sql-reference/syntax#defining-and-using-query-parameters
    140            """
    141            if not self._match(TokenType.L_BRACE):
    142                return None
    143
    144            this = self._parse_id_var()
    145            self._match(TokenType.COLON)
    146            kind = self._parse_types(check_func=False) or (
    147                self._match_text_seq("IDENTIFIER") and "Identifier"
    148            )
    149
    150            if not kind:
    151                self.raise_error("Expecting a placeholder type or 'Identifier' for tables")
    152            elif not self._match(TokenType.R_BRACE):
    153                self.raise_error("Expecting }")
    154
    155            return self.expression(exp.Placeholder, this=this, kind=kind)
    156
    157        def _parse_in(self, this: t.Optional[exp.Expression], is_global: bool = False) -> exp.In:
    158            this = super()._parse_in(this)
    159            this.set("is_global", is_global)
    160            return this
    161
    162        def _parse_table(
    163            self,
    164            schema: bool = False,
    165            joins: bool = False,
    166            alias_tokens: t.Optional[t.Collection[TokenType]] = None,
    167            parse_bracket: bool = False,
    168        ) -> t.Optional[exp.Expression]:
    169            this = super()._parse_table(
    170                schema=schema, joins=joins, alias_tokens=alias_tokens, parse_bracket=parse_bracket
    171            )
    172
    173            if self._match(TokenType.FINAL):
    174                this = self.expression(exp.Final, this=this)
    175
    176            return this
    177
    178        def _parse_position(self, haystack_first: bool = False) -> exp.StrPosition:
    179            return super()._parse_position(haystack_first=True)
    180
    181        # https://clickhouse.com/docs/en/sql-reference/statements/select/with/
    182        def _parse_cte(self) -> exp.CTE:
    183            index = self._index
    184            try:
    185                # WITH <identifier> AS <subquery expression>
    186                return super()._parse_cte()
    187            except ParseError:
    188                # WITH <expression> AS <identifier>
    189                self._retreat(index)
    190                statement = self._parse_statement()
    191
    192                if statement and isinstance(statement.this, exp.Alias):
    193                    self.raise_error("Expected CTE to have alias")
    194
    195                return self.expression(exp.CTE, this=statement, alias=statement and statement.this)
    196
    197        def _parse_join_parts(
    198            self,
    199        ) -> t.Tuple[t.Optional[Token], t.Optional[Token], t.Optional[Token]]:
    200            is_global = self._match(TokenType.GLOBAL) and self._prev
    201            kind_pre = self._match_set(self.JOIN_KINDS, advance=False) and self._prev
    202
    203            if kind_pre:
    204                kind = self._match_set(self.JOIN_KINDS) and self._prev
    205                side = self._match_set(self.JOIN_SIDES) and self._prev
    206                return is_global, side, kind
    207
    208            return (
    209                is_global,
    210                self._match_set(self.JOIN_SIDES) and self._prev,
    211                self._match_set(self.JOIN_KINDS) and self._prev,
    212            )
    213
    214        def _parse_join(
    215            self, skip_join_token: bool = False, parse_bracket: bool = False
    216        ) -> t.Optional[exp.Join]:
    217            join = super()._parse_join(skip_join_token=skip_join_token, parse_bracket=True)
    218
    219            if join:
    220                join.set("global", join.args.pop("method", None))
    221            return join
    222
    223        def _parse_function(
    224            self,
    225            functions: t.Optional[t.Dict[str, t.Callable]] = None,
    226            anonymous: bool = False,
    227            optional_parens: bool = True,
    228        ) -> t.Optional[exp.Expression]:
    229            func = super()._parse_function(
    230                functions=functions, anonymous=anonymous, optional_parens=optional_parens
    231            )
    232
    233            if isinstance(func, exp.Anonymous):
    234                params = self._parse_func_params(func)
    235
    236                if params:
    237                    return self.expression(
    238                        exp.ParameterizedAgg,
    239                        this=func.this,
    240                        expressions=func.expressions,
    241                        params=params,
    242                    )
    243
    244            return func
    245
    246        def _parse_func_params(
    247            self, this: t.Optional[exp.Func] = None
    248        ) -> t.Optional[t.List[t.Optional[exp.Expression]]]:
    249            if self._match_pair(TokenType.R_PAREN, TokenType.L_PAREN):
    250                return self._parse_csv(self._parse_lambda)
    251
    252            if self._match(TokenType.L_PAREN):
    253                params = self._parse_csv(self._parse_lambda)
    254                self._match_r_paren(this)
    255                return params
    256
    257            return None
    258
    259        def _parse_quantile(self) -> exp.Quantile:
    260            this = self._parse_lambda()
    261            params = self._parse_func_params()
    262            if params:
    263                return self.expression(exp.Quantile, this=params[0], quantile=this)
    264            return self.expression(exp.Quantile, this=this, quantile=exp.Literal.number(0.5))
    265
    266        def _parse_wrapped_id_vars(
    267            self, optional: bool = False
    268        ) -> t.List[t.Optional[exp.Expression]]:
    269            return super()._parse_wrapped_id_vars(optional=True)
    270
    271        def _parse_primary_key(
    272            self, wrapped_optional: bool = False, in_props: bool = False
    273        ) -> exp.PrimaryKeyColumnConstraint | exp.PrimaryKey:
    274            return super()._parse_primary_key(
    275                wrapped_optional=wrapped_optional or in_props, in_props=in_props
    276            )
    277
    278        def _parse_on_property(self) -> t.Optional[exp.Expression]:
    279            index = self._index
    280            if self._match_text_seq("CLUSTER"):
    281                this = self._parse_id_var()
    282                if this:
    283                    return self.expression(exp.OnCluster, this=this)
    284                else:
    285                    self._retreat(index)
    286            return None
    287
    288    class Generator(generator.Generator):
    289        QUERY_HINTS = False
    290        STRUCT_DELIMITER = ("(", ")")
    291
    292        TYPE_MAPPING = {
    293            **generator.Generator.TYPE_MAPPING,
    294            exp.DataType.Type.ARRAY: "Array",
    295            exp.DataType.Type.BIGINT: "Int64",
    296            exp.DataType.Type.DATETIME64: "DateTime64",
    297            exp.DataType.Type.DOUBLE: "Float64",
    298            exp.DataType.Type.FLOAT: "Float32",
    299            exp.DataType.Type.INT: "Int32",
    300            exp.DataType.Type.INT128: "Int128",
    301            exp.DataType.Type.INT256: "Int256",
    302            exp.DataType.Type.MAP: "Map",
    303            exp.DataType.Type.NULLABLE: "Nullable",
    304            exp.DataType.Type.SMALLINT: "Int16",
    305            exp.DataType.Type.STRUCT: "Tuple",
    306            exp.DataType.Type.TINYINT: "Int8",
    307            exp.DataType.Type.UBIGINT: "UInt64",
    308            exp.DataType.Type.UINT: "UInt32",
    309            exp.DataType.Type.UINT128: "UInt128",
    310            exp.DataType.Type.UINT256: "UInt256",
    311            exp.DataType.Type.USMALLINT: "UInt16",
    312            exp.DataType.Type.UTINYINT: "UInt8",
    313        }
    314
    315        TRANSFORMS = {
    316            **generator.Generator.TRANSFORMS,
    317            exp.AnyValue: rename_func("any"),
    318            exp.ApproxDistinct: rename_func("uniq"),
    319            exp.Array: inline_array_sql,
    320            exp.CastToStrType: rename_func("CAST"),
    321            exp.Final: lambda self, e: f"{self.sql(e, 'this')} FINAL",
    322            exp.Map: lambda self, e: _lower_func(var_map_sql(self, e)),
    323            exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}",
    324            exp.Pivot: no_pivot_sql,
    325            exp.Quantile: lambda self, e: self.func("quantile", e.args.get("quantile"))
    326            + f"({self.sql(e, 'this')})",
    327            exp.RegexpLike: lambda self, e: f"match({self.format_args(e.this, e.expression)})",
    328            exp.StrPosition: lambda self, e: f"position({self.format_args(e.this, e.args.get('substr'), e.args.get('position'))})",
    329            exp.VarMap: lambda self, e: _lower_func(var_map_sql(self, e)),
    330            exp.Xor: lambda self, e: self.func("xor", e.this, e.expression, *e.expressions),
    331        }
    332
    333        PROPERTIES_LOCATION = {
    334            **generator.Generator.PROPERTIES_LOCATION,
    335            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    336            exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA,
    337            exp.OnCluster: exp.Properties.Location.POST_NAME,
    338        }
    339
    340        JOIN_HINTS = False
    341        TABLE_HINTS = False
    342        EXPLICIT_UNION = True
    343        GROUPINGS_SEP = ""
    344
    345        # there's no list in docs, but it can be found in Clickhouse code
    346        # see `ClickHouse/src/Parsers/ParserCreate*.cpp`
    347        ON_CLUSTER_TARGETS = {
    348            "DATABASE",
    349            "TABLE",
    350            "VIEW",
    351            "DICTIONARY",
    352            "INDEX",
    353            "FUNCTION",
    354            "NAMED COLLECTION",
    355        }
    356
    357        def safeconcat_sql(self, expression: exp.SafeConcat) -> str:
    358            # Clickhouse errors out if we try to cast a NULL value to TEXT
    359            return self.func(
    360                "CONCAT",
    361                *[
    362                    exp.func("if", e.is_(exp.null()), e, exp.cast(e, "text"))
    363                    for e in t.cast(t.List[exp.Condition], expression.expressions)
    364                ],
    365            )
    366
    367        def cte_sql(self, expression: exp.CTE) -> str:
    368            if isinstance(expression.this, exp.Alias):
    369                return self.sql(expression, "this")
    370
    371            return super().cte_sql(expression)
    372
    373        def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
    374            return super().after_limit_modifiers(expression) + [
    375                self.seg("SETTINGS ") + self.expressions(expression, key="settings", flat=True)
    376                if expression.args.get("settings")
    377                else "",
    378                self.seg("FORMAT ") + self.sql(expression, "format")
    379                if expression.args.get("format")
    380                else "",
    381            ]
    382
    383        def parameterizedagg_sql(self, expression: exp.Anonymous) -> str:
    384            params = self.expressions(expression, key="params", flat=True)
    385            return self.func(expression.name, *expression.expressions) + f"({params})"
    386
    387        def placeholder_sql(self, expression: exp.Placeholder) -> str:
    388            return f"{{{expression.name}: {self.sql(expression, 'kind')}}}"
    389
    390        def oncluster_sql(self, expression: exp.OnCluster) -> str:
    391            return f"ON CLUSTER {self.sql(expression, 'this')}"
    392
    393        def createable_sql(
    394            self,
    395            expression: exp.Create,
    396            locations: dict[exp.Properties.Location, list[exp.Property]],
    397        ) -> str:
    398            kind = self.sql(expression, "kind").upper()
    399            if kind in self.ON_CLUSTER_TARGETS and locations.get(exp.Properties.Location.POST_NAME):
    400                this_name = self.sql(expression.this, "this")
    401                this_properties = " ".join(
    402                    [self.sql(prop) for prop in locations[exp.Properties.Location.POST_NAME]]
    403                )
    404                this_schema = self.schema_columns_sql(expression.this)
    405                return f"{this_name}{self.sep()}{this_properties}{self.sep()}{this_schema}"
    406            return super().createable_sql(expression, locations)

NORMALIZE_FUNCTIONS: bool | str = False
NULL_ORDERING = 'nulls_are_last'
STRICT_STRING_CONCAT = True
tokenizer_class = <class 'sqlglot.dialects.clickhouse.ClickHouse.Tokenizer'>
parser_class = <class 'sqlglot.dialects.clickhouse.ClickHouse.Parser'>
generator_class = <class 'sqlglot.dialects.clickhouse.ClickHouse.Generator'>
TIME_TRIE: Dict = {}
FORMAT_TRIE: Dict = {}
INVERSE_TIME_MAPPING: Dict[str, str] = {}
INVERSE_TIME_TRIE: Dict = {}
QUOTE_START = "'"
QUOTE_END = "'"
IDENTIFIER_START = '"'
IDENTIFIER_END = '"'
BIT_START = '0b'
BIT_END = ''
HEX_START = '0x'
HEX_END = ''
BYTE_START = None
BYTE_END = None

##### Inherited Members

sqlglot.dialects.dialect.Dialect
  INDEX_OFFSET
  UNNEST_COLUMN_ONLY
  ALIAS_POST_TABLESAMPLE
  RESOLVES_IDENTIFIERS_AS_UPPERCASE
  IDENTIFIERS_CAN_START_WITH_DIGIT
  DATE_FORMAT
  DATEINT_FORMAT
  TIME_FORMAT
  TIME_MAPPING
  FORMAT_MAPPING
  PSEUDOCOLUMNS
  get_or_raise
  format_time
  normalize_identifier
  case_sensitive
  can_identify
  quote_identifier
  parse
  parse_into
  generate
  transpile
  tokenize
  tokenizer
  parser
  generator

class ClickHouse.Tokenizer(sqlglot.tokens.Tokenizer): View Source

    29    class Tokenizer(tokens.Tokenizer):
    30        COMMENTS = ["--", "#", "#!", ("/*", "*/")]
    31        IDENTIFIERS = ['"', "`"]
    32        STRING_ESCAPES = ["'", "\\"]
    33        BIT_STRINGS = [("0b", "")]
    34        HEX_STRINGS = [("0x", ""), ("0X", "")]
    35
    36        KEYWORDS = {
    37            **tokens.Tokenizer.KEYWORDS,
    38            "ATTACH": TokenType.COMMAND,
    39            "DATETIME64": TokenType.DATETIME64,
    40            "DICTIONARY": TokenType.DICTIONARY,
    41            "FINAL": TokenType.FINAL,
    42            "FLOAT32": TokenType.FLOAT,
    43            "FLOAT64": TokenType.DOUBLE,
    44            "GLOBAL": TokenType.GLOBAL,
    45            "INT128": TokenType.INT128,
    46            "INT16": TokenType.SMALLINT,
    47            "INT256": TokenType.INT256,
    48            "INT32": TokenType.INT,
    49            "INT64": TokenType.BIGINT,
    50            "INT8": TokenType.TINYINT,
    51            "MAP": TokenType.MAP,
    52            "TUPLE": TokenType.STRUCT,
    53            "UINT128": TokenType.UINT128,
    54            "UINT16": TokenType.USMALLINT,
    55            "UINT256": TokenType.UINT256,
    56            "UINT32": TokenType.UINT,
    57            "UINT64": TokenType.UBIGINT,
    58            "UINT8": TokenType.UTINYINT,
    59        }

COMMENTS = ['--', '#', '#!', ('/*', '*/')]
IDENTIFIERS = ['"', '`']
STRING_ESCAPES = ["'", '\\']
BIT_STRINGS = [('0b', '')]
HEX_STRINGS = [('0x', ''), ('0X', '')]
KEYWORDS = {'{%': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%-': <TokenType.BLOCK_START: 'BLOCK_START'>, '%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '+%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '{{+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{{-': <TokenType.BLOCK_START: 'BLOCK_START'>, '+}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '/*+': <TokenType.HINT: 'HINT'>, '==': <TokenType.EQ: 'EQ'>, '::': <TokenType.DCOLON: 'DCOLON'>, '||': <TokenType.DPIPE: 'DPIPE'>, '>=': <TokenType.GTE: 'GTE'>, '<=': <TokenType.LTE: 'LTE'>, '<>': <TokenType.NEQ: 'NEQ'>, '!=': <TokenType.NEQ: 'NEQ'>, '<=>': <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>, '->': <TokenType.ARROW: 'ARROW'>, '->>': <TokenType.DARROW: 'DARROW'>, '=>': <TokenType.FARROW: 'FARROW'>, '#>': <TokenType.HASH_ARROW: 'HASH_ARROW'>, '#>>': <TokenType.DHASH_ARROW: 'DHASH_ARROW'>, '<->': <TokenType.LR_ARROW: 'LR_ARROW'>, '&&': <TokenType.DAMP: 'DAMP'>, 'ALL': <TokenType.ALL: 'ALL'>, 'ALWAYS': <TokenType.ALWAYS: 'ALWAYS'>, 'AND': <TokenType.AND: 'AND'>, 'ANTI': <TokenType.ANTI: 'ANTI'>, 'ANY': <TokenType.ANY: 'ANY'>, 'ASC': <TokenType.ASC: 'ASC'>, 'AS': <TokenType.ALIAS: 'ALIAS'>, 'ASOF': <TokenType.ASOF: 'ASOF'>, 'AUTOINCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'AUTO_INCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'BEGIN': <TokenType.BEGIN: 'BEGIN'>, 'BETWEEN': <TokenType.BETWEEN: 'BETWEEN'>, 'CACHE': <TokenType.CACHE: 'CACHE'>, 'UNCACHE': <TokenType.UNCACHE: 'UNCACHE'>, 'CASE': <TokenType.CASE: 'CASE'>, 'CHARACTER SET': <TokenType.CHARACTER_SET: 'CHARACTER_SET'>, 'CLUSTER BY': <TokenType.CLUSTER_BY: 'CLUSTER_BY'>, 'COLLATE': <TokenType.COLLATE: 'COLLATE'>, 'COLUMN': <TokenType.COLUMN: 'COLUMN'>, 'COMMIT': <TokenType.COMMIT: 'COMMIT'>, 'CONSTRAINT': <TokenType.CONSTRAINT: 'CONSTRAINT'>, 'CREATE': <TokenType.CREATE: 'CREATE'>, 'CROSS': <TokenType.CROSS: 'CROSS'>, 'CUBE': <TokenType.CUBE: 'CUBE'>, 'CURRENT_DATE': <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, 'CURRENT_TIME': <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, 'CURRENT_TIMESTAMP': <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, 'CURRENT_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>, 'DATABASE': <TokenType.DATABASE: 'DATABASE'>, 'DEFAULT': <TokenType.DEFAULT: 'DEFAULT'>, 'DELETE': <TokenType.DELETE: 'DELETE'>, 'DESC': <TokenType.DESC: 'DESC'>, 'DESCRIBE': <TokenType.DESCRIBE: 'DESCRIBE'>, 'DISTINCT': <TokenType.DISTINCT: 'DISTINCT'>, 'DISTRIBUTE BY': <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>, 'DIV': <TokenType.DIV: 'DIV'>, 'DROP': <TokenType.DROP: 'DROP'>, 'ELSE': <TokenType.ELSE: 'ELSE'>, 'END': <TokenType.END: 'END'>, 'ESCAPE': <TokenType.ESCAPE: 'ESCAPE'>, 'EXCEPT': <TokenType.EXCEPT: 'EXCEPT'>, 'EXECUTE': <TokenType.EXECUTE: 'EXECUTE'>, 'EXISTS': <TokenType.EXISTS: 'EXISTS'>, 'FALSE': <TokenType.FALSE: 'FALSE'>, 'FETCH': <TokenType.FETCH: 'FETCH'>, 'FILTER': <TokenType.FILTER: 'FILTER'>, 'FIRST': <TokenType.FIRST: 'FIRST'>, 'FULL': <TokenType.FULL: 'FULL'>, 'FUNCTION': <TokenType.FUNCTION: 'FUNCTION'>, 'FOR': <TokenType.FOR: 'FOR'>, 'FOREIGN KEY': <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, 'FORMAT': <TokenType.FORMAT: 'FORMAT'>, 'FROM': <TokenType.FROM: 'FROM'>, 'GEOGRAPHY': <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, 'GEOMETRY': <TokenType.GEOMETRY: 'GEOMETRY'>, 'GLOB': <TokenType.GLOB: 'GLOB'>, 'GROUP BY': <TokenType.GROUP_BY: 'GROUP_BY'>, 'GROUPING SETS': <TokenType.GROUPING_SETS: 'GROUPING_SETS'>, 'HAVING': <TokenType.HAVING: 'HAVING'>, 'IF': <TokenType.IF: 'IF'>, 'ILIKE': <TokenType.ILIKE: 'ILIKE'>, 'IN': <TokenType.IN: 'IN'>, 'INDEX': <TokenType.INDEX: 'INDEX'>, 'INET': <TokenType.INET: 'INET'>, 'INNER': <TokenType.INNER: 'INNER'>, 'INSERT': <TokenType.INSERT: 'INSERT'>, 'INTERVAL': <TokenType.INTERVAL: 'INTERVAL'>, 'INTERSECT': <TokenType.INTERSECT: 'INTERSECT'>, 'INTO': <TokenType.INTO: 'INTO'>, 'IS': <TokenType.IS: 'IS'>, 'ISNULL': <TokenType.ISNULL: 'ISNULL'>, 'JOIN': <TokenType.JOIN: 'JOIN'>, 'KEEP': <TokenType.KEEP: 'KEEP'>, 'LATERAL': <TokenType.LATERAL: 'LATERAL'>, 'LEFT': <TokenType.LEFT: 'LEFT'>, 'LIKE': <TokenType.LIKE: 'LIKE'>, 'LIMIT': <TokenType.LIMIT: 'LIMIT'>, 'LOAD': <TokenType.LOAD: 'LOAD'>, 'LOCK': <TokenType.LOCK: 'LOCK'>, 'MERGE': <TokenType.MERGE: 'MERGE'>, 'NATURAL': <TokenType.NATURAL: 'NATURAL'>, 'NEXT': <TokenType.NEXT: 'NEXT'>, 'NEXT VALUE FOR': <TokenType.NEXT_VALUE_FOR: 'NEXT_VALUE_FOR'>, 'NOT': <TokenType.NOT: 'NOT'>, 'NOTNULL': <TokenType.NOTNULL: 'NOTNULL'>, 'NULL': <TokenType.NULL: 'NULL'>, 'OBJECT': <TokenType.OBJECT: 'OBJECT'>, 'OFFSET': <TokenType.OFFSET: 'OFFSET'>, 'ON': <TokenType.ON: 'ON'>, 'OR': <TokenType.OR: 'OR'>, 'XOR': <TokenType.XOR: 'XOR'>, 'ORDER BY': <TokenType.ORDER_BY: 'ORDER_BY'>, 'ORDINALITY': <TokenType.ORDINALITY: 'ORDINALITY'>, 'OUTER': <TokenType.OUTER: 'OUTER'>, 'OVER': <TokenType.OVER: 'OVER'>, 'OVERLAPS': <TokenType.OVERLAPS: 'OVERLAPS'>, 'OVERWRITE': <TokenType.OVERWRITE: 'OVERWRITE'>, 'PARTITION': <TokenType.PARTITION: 'PARTITION'>, 'PARTITION BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED_BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PERCENT': <TokenType.PERCENT: 'PERCENT'>, 'PIVOT': <TokenType.PIVOT: 'PIVOT'>, 'PRAGMA': <TokenType.PRAGMA: 'PRAGMA'>, 'PRIMARY KEY': <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>, 'PROCEDURE': <TokenType.PROCEDURE: 'PROCEDURE'>, 'QUALIFY': <TokenType.QUALIFY: 'QUALIFY'>, 'RANGE': <TokenType.RANGE: 'RANGE'>, 'RECURSIVE': <TokenType.RECURSIVE: 'RECURSIVE'>, 'REGEXP': <TokenType.RLIKE: 'RLIKE'>, 'REPLACE': <TokenType.REPLACE: 'REPLACE'>, 'RETURNING': <TokenType.RETURNING: 'RETURNING'>, 'REFERENCES': <TokenType.REFERENCES: 'REFERENCES'>, 'RIGHT': <TokenType.RIGHT: 'RIGHT'>, 'RLIKE': <TokenType.RLIKE: 'RLIKE'>, 'ROLLBACK': <TokenType.ROLLBACK: 'ROLLBACK'>, 'ROLLUP': <TokenType.ROLLUP: 'ROLLUP'>, 'ROW': <TokenType.ROW: 'ROW'>, 'ROWS': <TokenType.ROWS: 'ROWS'>, 'SCHEMA': <TokenType.SCHEMA: 'SCHEMA'>, 'SELECT': <TokenType.SELECT: 'SELECT'>, 'SEMI': <TokenType.SEMI: 'SEMI'>, 'SET': <TokenType.SET: 'SET'>, 'SETTINGS': <TokenType.SETTINGS: 'SETTINGS'>, 'SHOW': <TokenType.SHOW: 'SHOW'>, 'SIMILAR TO': <TokenType.SIMILAR_TO: 'SIMILAR_TO'>, 'SOME': <TokenType.SOME: 'SOME'>, 'SORT BY': <TokenType.SORT_BY: 'SORT_BY'>, 'TABLE': <TokenType.TABLE: 'TABLE'>, 'TABLESAMPLE': <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>, 'TEMP': <TokenType.TEMPORARY: 'TEMPORARY'>, 'TEMPORARY': <TokenType.TEMPORARY: 'TEMPORARY'>, 'THEN': <TokenType.THEN: 'THEN'>, 'TRUE': <TokenType.TRUE: 'TRUE'>, 'UNION': <TokenType.UNION: 'UNION'>, 'UNNEST': <TokenType.UNNEST: 'UNNEST'>, 'UNPIVOT': <TokenType.UNPIVOT: 'UNPIVOT'>, 'UPDATE': <TokenType.UPDATE: 'UPDATE'>, 'USE': <TokenType.USE: 'USE'>, 'USING': <TokenType.USING: 'USING'>, 'UUID': <TokenType.UUID: 'UUID'>, 'VALUES': <TokenType.VALUES: 'VALUES'>, 'VIEW': <TokenType.VIEW: 'VIEW'>, 'VOLATILE': <TokenType.VOLATILE: 'VOLATILE'>, 'WHEN': <TokenType.WHEN: 'WHEN'>, 'WHERE': <TokenType.WHERE: 'WHERE'>, 'WINDOW': <TokenType.WINDOW: 'WINDOW'>, 'WITH': <TokenType.WITH: 'WITH'>, 'APPLY': <TokenType.APPLY: 'APPLY'>, 'ARRAY': <TokenType.ARRAY: 'ARRAY'>, 'BIT': <TokenType.BIT: 'BIT'>, 'BOOL': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BOOLEAN': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BYTE': <TokenType.TINYINT: 'TINYINT'>, 'TINYINT': <TokenType.TINYINT: 'TINYINT'>, 'SHORT': <TokenType.SMALLINT: 'SMALLINT'>, 'SMALLINT': <TokenType.SMALLINT: 'SMALLINT'>, 'INT2': <TokenType.SMALLINT: 'SMALLINT'>, 'INTEGER': <TokenType.INT: 'INT'>, 'INT': <TokenType.INT: 'INT'>, 'INT4': <TokenType.INT: 'INT'>, 'LONG': <TokenType.BIGINT: 'BIGINT'>, 'BIGINT': <TokenType.BIGINT: 'BIGINT'>, 'INT8': <TokenType.TINYINT: 'TINYINT'>, 'DEC': <TokenType.DECIMAL: 'DECIMAL'>, 'DECIMAL': <TokenType.DECIMAL: 'DECIMAL'>, 'BIGDECIMAL': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'BIGNUMERIC': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'MAP': <TokenType.MAP: 'MAP'>, 'NULLABLE': <TokenType.NULLABLE: 'NULLABLE'>, 'NUMBER': <TokenType.DECIMAL: 'DECIMAL'>, 'NUMERIC': <TokenType.DECIMAL: 'DECIMAL'>, 'FIXED': <TokenType.DECIMAL: 'DECIMAL'>, 'REAL': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT4': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT8': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE PRECISION': <TokenType.DOUBLE: 'DOUBLE'>, 'JSON': <TokenType.JSON: 'JSON'>, 'CHAR': <TokenType.CHAR: 'CHAR'>, 'CHARACTER': <TokenType.CHAR: 'CHAR'>, 'NCHAR': <TokenType.NCHAR: 'NCHAR'>, 'VARCHAR': <TokenType.VARCHAR: 'VARCHAR'>, 'VARCHAR2': <TokenType.VARCHAR: 'VARCHAR'>, 'NVARCHAR': <TokenType.NVARCHAR: 'NVARCHAR'>, 'NVARCHAR2': <TokenType.NVARCHAR: 'NVARCHAR'>, 'STR': <TokenType.TEXT: 'TEXT'>, 'STRING': <TokenType.TEXT: 'TEXT'>, 'TEXT': <TokenType.TEXT: 'TEXT'>, 'CLOB': <TokenType.TEXT: 'TEXT'>, 'LONGVARCHAR': <TokenType.TEXT: 'TEXT'>, 'BINARY': <TokenType.BINARY: 'BINARY'>, 'BLOB': <TokenType.VARBINARY: 'VARBINARY'>, 'BYTEA': <TokenType.VARBINARY: 'VARBINARY'>, 'VARBINARY': <TokenType.VARBINARY: 'VARBINARY'>, 'TIME': <TokenType.TIME: 'TIME'>, 'TIMESTAMP': <TokenType.TIMESTAMP: 'TIMESTAMP'>, 'TIMESTAMPTZ': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'TIMESTAMPLTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'DATE': <TokenType.DATE: 'DATE'>, 'DATETIME': <TokenType.DATETIME: 'DATETIME'>, 'INT4RANGE': <TokenType.INT4RANGE: 'INT4RANGE'>, 'INT4MULTIRANGE': <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, 'INT8RANGE': <TokenType.INT8RANGE: 'INT8RANGE'>, 'INT8MULTIRANGE': <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, 'NUMRANGE': <TokenType.NUMRANGE: 'NUMRANGE'>, 'NUMMULTIRANGE': <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, 'TSRANGE': <TokenType.TSRANGE: 'TSRANGE'>, 'TSMULTIRANGE': <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, 'TSTZRANGE': <TokenType.TSTZRANGE: 'TSTZRANGE'>, 'TSTZMULTIRANGE': <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, 'DATERANGE': <TokenType.DATERANGE: 'DATERANGE'>, 'DATEMULTIRANGE': <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, 'UNIQUE': <TokenType.UNIQUE: 'UNIQUE'>, 'STRUCT': <TokenType.STRUCT: 'STRUCT'>, 'VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'ALTER': <TokenType.ALTER: 'ALTER'>, 'ANALYZE': <TokenType.COMMAND: 'COMMAND'>, 'CALL': <TokenType.COMMAND: 'COMMAND'>, 'COMMENT': <TokenType.COMMENT: 'COMMENT'>, 'COPY': <TokenType.COMMAND: 'COMMAND'>, 'EXPLAIN': <TokenType.COMMAND: 'COMMAND'>, 'GRANT': <TokenType.COMMAND: 'COMMAND'>, 'OPTIMIZE': <TokenType.COMMAND: 'COMMAND'>, 'PREPARE': <TokenType.COMMAND: 'COMMAND'>, 'TRUNCATE': <TokenType.COMMAND: 'COMMAND'>, 'VACUUM': <TokenType.COMMAND: 'COMMAND'>, 'USER-DEFINED': <TokenType.USERDEFINED: 'USERDEFINED'>, 'ATTACH': <TokenType.COMMAND: 'COMMAND'>, 'DATETIME64': <TokenType.DATETIME64: 'DATETIME64'>, 'DICTIONARY': <TokenType.DICTIONARY: 'DICTIONARY'>, 'FINAL': <TokenType.FINAL: 'FINAL'>, 'FLOAT32': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT64': <TokenType.DOUBLE: 'DOUBLE'>, 'GLOBAL': <TokenType.GLOBAL: 'GLOBAL'>, 'INT128': <TokenType.INT128: 'INT128'>, 'INT16': <TokenType.SMALLINT: 'SMALLINT'>, 'INT256': <TokenType.INT256: 'INT256'>, 'INT32': <TokenType.INT: 'INT'>, 'INT64': <TokenType.BIGINT: 'BIGINT'>, 'TUPLE': <TokenType.STRUCT: 'STRUCT'>, 'UINT128': <TokenType.UINT128: 'UINT128'>, 'UINT16': <TokenType.USMALLINT: 'USMALLINT'>, 'UINT256': <TokenType.UINT256: 'UINT256'>, 'UINT32': <TokenType.UINT: 'UINT'>, 'UINT64': <TokenType.UBIGINT: 'UBIGINT'>, 'UINT8': <TokenType.UTINYINT: 'UTINYINT'>}

##### Inherited Members

sqlglot.tokens.Tokenizer
  SINGLE_TOKENS
  BYTE_STRINGS
  RAW_STRINGS
  IDENTIFIER_ESCAPES
  QUOTES
  VAR_SINGLE_TOKENS
  IDENTIFIERS_CAN_START_WITH_DIGIT
  WHITE_SPACE
  COMMANDS
  COMMAND_PREFIX_TOKENS
  NUMERIC_LITERALS
  ENCODE
  reset
  tokenize
  peek
  size
  sql
  tokens

class ClickHouse.Parser(sqlglot.parser.Parser): View Source

     61    class Parser(parser.Parser):
     62        FUNCTIONS = {
     63            **parser.Parser.FUNCTIONS,
     64            "ANY": exp.AnyValue.from_arg_list,
     65            "MAP": parse_var_map,
     66            "MATCH": exp.RegexpLike.from_arg_list,
     67            "UNIQ": exp.ApproxDistinct.from_arg_list,
     68            "XOR": lambda args: exp.Xor(expressions=args),
     69        }
     70
     71        FUNCTIONS_WITH_ALIASED_ARGS = {*parser.Parser.FUNCTIONS_WITH_ALIASED_ARGS, "TUPLE"}
     72
     73        FUNCTION_PARSERS = {
     74            **parser.Parser.FUNCTION_PARSERS,
     75            "QUANTILE": lambda self: self._parse_quantile(),
     76        }
     77
     78        FUNCTION_PARSERS.pop("MATCH")
     79
     80        NO_PAREN_FUNCTION_PARSERS = parser.Parser.NO_PAREN_FUNCTION_PARSERS.copy()
     81        NO_PAREN_FUNCTION_PARSERS.pop(TokenType.ANY)
     82
     83        RANGE_PARSERS = {
     84            **parser.Parser.RANGE_PARSERS,
     85            TokenType.GLOBAL: lambda self, this: self._match(TokenType.IN)
     86            and self._parse_in(this, is_global=True),
     87        }
     88
     89        # The PLACEHOLDER entry is popped because 1) it doesn't affect Clickhouse (it corresponds to
     90        # the postgres-specific JSONBContains parser) and 2) it makes parsing the ternary op simpler.
     91        COLUMN_OPERATORS = parser.Parser.COLUMN_OPERATORS.copy()
     92        COLUMN_OPERATORS.pop(TokenType.PLACEHOLDER)
     93
     94        JOIN_KINDS = {
     95            *parser.Parser.JOIN_KINDS,
     96            TokenType.ANY,
     97            TokenType.ASOF,
     98            TokenType.ANTI,
     99            TokenType.SEMI,
    100            TokenType.ARRAY,
    101        }
    102
    103        TABLE_ALIAS_TOKENS = {*parser.Parser.TABLE_ALIAS_TOKENS} - {
    104            TokenType.ANY,
    105            TokenType.SEMI,
    106            TokenType.ANTI,
    107            TokenType.SETTINGS,
    108            TokenType.FORMAT,
    109            TokenType.ARRAY,
    110        }
    111
    112        LOG_DEFAULTS_TO_LN = True
    113
    114        QUERY_MODIFIER_PARSERS = {
    115            **parser.Parser.QUERY_MODIFIER_PARSERS,
    116            TokenType.SETTINGS: lambda self: (
    117                "settings",
    118                self._advance() or self._parse_csv(self._parse_conjunction),
    119            ),
    120            TokenType.FORMAT: lambda self: ("format", self._advance() or self._parse_id_var()),
    121        }
    122
    123        def _parse_conjunction(self) -> t.Optional[exp.Expression]:
    124            this = super()._parse_conjunction()
    125
    126            if self._match(TokenType.PLACEHOLDER):
    127                return self.expression(
    128                    exp.If,
    129                    this=this,
    130                    true=self._parse_conjunction(),
    131                    false=self._match(TokenType.COLON) and self._parse_conjunction(),
    132                )
    133
    134            return this
    135
    136        def _parse_placeholder(self) -> t.Optional[exp.Expression]:
    137            """
    138            Parse a placeholder expression like SELECT {abc: UInt32} or FROM {table: Identifier}
    139            https://clickhouse.com/docs/en/sql-reference/syntax#defining-and-using-query-parameters
    140            """
    141            if not self._match(TokenType.L_BRACE):
    142                return None
    143
    144            this = self._parse_id_var()
    145            self._match(TokenType.COLON)
    146            kind = self._parse_types(check_func=False) or (
    147                self._match_text_seq("IDENTIFIER") and "Identifier"
    148            )
    149
    150            if not kind:
    151                self.raise_error("Expecting a placeholder type or 'Identifier' for tables")
    152            elif not self._match(TokenType.R_BRACE):
    153                self.raise_error("Expecting }")
    154
    155            return self.expression(exp.Placeholder, this=this, kind=kind)
    156
    157        def _parse_in(self, this: t.Optional[exp.Expression], is_global: bool = False) -> exp.In:
    158            this = super()._parse_in(this)
    159            this.set("is_global", is_global)
    160            return this
    161
    162        def _parse_table(
    163            self,
    164            schema: bool = False,
    165            joins: bool = False,
    166            alias_tokens: t.Optional[t.Collection[TokenType]] = None,
    167            parse_bracket: bool = False,
    168        ) -> t.Optional[exp.Expression]:
    169            this = super()._parse_table(
    170                schema=schema, joins=joins, alias_tokens=alias_tokens, parse_bracket=parse_bracket
    171            )
    172
    173            if self._match(TokenType.FINAL):
    174                this = self.expression(exp.Final, this=this)
    175
    176            return this
    177
    178        def _parse_position(self, haystack_first: bool = False) -> exp.StrPosition:
    179            return super()._parse_position(haystack_first=True)
    180
    181        # https://clickhouse.com/docs/en/sql-reference/statements/select/with/
    182        def _parse_cte(self) -> exp.CTE:
    183            index = self._index
    184            try:
    185                # WITH <identifier> AS <subquery expression>
    186                return super()._parse_cte()
    187            except ParseError:
    188                # WITH <expression> AS <identifier>
    189                self._retreat(index)
    190                statement = self._parse_statement()
    191
    192                if statement and isinstance(statement.this, exp.Alias):
    193                    self.raise_error("Expected CTE to have alias")
    194
    195                return self.expression(exp.CTE, this=statement, alias=statement and statement.this)
    196
    197        def _parse_join_parts(
    198            self,
    199        ) -> t.Tuple[t.Optional[Token], t.Optional[Token], t.Optional[Token]]:
    200            is_global = self._match(TokenType.GLOBAL) and self._prev
    201            kind_pre = self._match_set(self.JOIN_KINDS, advance=False) and self._prev
    202
    203            if kind_pre:
    204                kind = self._match_set(self.JOIN_KINDS) and self._prev
    205                side = self._match_set(self.JOIN_SIDES) and self._prev
    206                return is_global, side, kind
    207
    208            return (
    209                is_global,
    210                self._match_set(self.JOIN_SIDES) and self._prev,
    211                self._match_set(self.JOIN_KINDS) and self._prev,
    212            )
    213
    214        def _parse_join(
    215            self, skip_join_token: bool = False, parse_bracket: bool = False
    216        ) -> t.Optional[exp.Join]:
    217            join = super()._parse_join(skip_join_token=skip_join_token, parse_bracket=True)
    218
    219            if join:
    220                join.set("global", join.args.pop("method", None))
    221            return join
    222
    223        def _parse_function(
    224            self,
    225            functions: t.Optional[t.Dict[str, t.Callable]] = None,
    226            anonymous: bool = False,
    227            optional_parens: bool = True,
    228        ) -> t.Optional[exp.Expression]:
    229            func = super()._parse_function(
    230                functions=functions, anonymous=anonymous, optional_parens=optional_parens
    231            )
    232
    233            if isinstance(func, exp.Anonymous):
    234                params = self._parse_func_params(func)
    235
    236                if params:
    237                    return self.expression(
    238                        exp.ParameterizedAgg,
    239                        this=func.this,
    240                        expressions=func.expressions,
    241                        params=params,
    242                    )
    243
    244            return func
    245
    246        def _parse_func_params(
    247            self, this: t.Optional[exp.Func] = None
    248        ) -> t.Optional[t.List[t.Optional[exp.Expression]]]:
    249            if self._match_pair(TokenType.R_PAREN, TokenType.L_PAREN):
    250                return self._parse_csv(self._parse_lambda)
    251
    252            if self._match(TokenType.L_PAREN):
    253                params = self._parse_csv(self._parse_lambda)
    254                self._match_r_paren(this)
    255                return params
    256
    257            return None
    258
    259        def _parse_quantile(self) -> exp.Quantile:
    260            this = self._parse_lambda()
    261            params = self._parse_func_params()
    262            if params:
    263                return self.expression(exp.Quantile, this=params[0], quantile=this)
    264            return self.expression(exp.Quantile, this=this, quantile=exp.Literal.number(0.5))
    265
    266        def _parse_wrapped_id_vars(
    267            self, optional: bool = False
    268        ) -> t.List[t.Optional[exp.Expression]]:
    269            return super()._parse_wrapped_id_vars(optional=True)
    270
    271        def _parse_primary_key(
    272            self, wrapped_optional: bool = False, in_props: bool = False
    273        ) -> exp.PrimaryKeyColumnConstraint | exp.PrimaryKey:
    274            return super()._parse_primary_key(
    275                wrapped_optional=wrapped_optional or in_props, in_props=in_props
    276            )
    277
    278        def _parse_on_property(self) -> t.Optional[exp.Expression]:
    279            index = self._index
    280            if self._match_text_seq("CLUSTER"):
    281                this = self._parse_id_var()
    282                if this:
    283                    return self.expression(exp.OnCluster, this=this)
    284                else:
    285                    self._retreat(index)
    286            return None

Parser consumes a list of tokens produced by the Tokenizer and produces a parsed syntax tree.

###### Arguments:

- error_level: The desired error level. Default: ErrorLevel.IMMEDIATE
- error_message_context: Determines the amount of context to capture from a query string when displaying the error message (in number of characters). Default: 100
- max_errors: Maximum number of error messages to include in a raised ParseError. This is only relevant if error_level is ErrorLevel.RAISE. Default: 3

FUNCTIONS = {'ABS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Abs'>>, 'ANY_VALUE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.AnyValue'>>, 'APPROX_DISTINCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxDistinct'>>, 'APPROX_COUNT_DISTINCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxDistinct'>>, 'APPROX_QUANTILE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxQuantile'>>, 'ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Array'>>, 'ARRAY_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAgg'>>, 'ARRAY_ALL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAll'>>, 'ARRAY_ANY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAny'>>, 'ARRAY_CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayConcat'>>, 'ARRAY_CONTAINS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayContains'>>, 'FILTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayFilter'>>, 'ARRAY_FILTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayFilter'>>, 'ARRAY_JOIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayJoin'>>, 'ARRAY_SIZE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySize'>>, 'ARRAY_SORT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySort'>>, 'ARRAY_SUM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySum'>>, 'ARRAY_UNION_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayUnionAgg'>>, 'AVG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Avg'>>, 'CASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Case'>>, 'CAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Cast'>>, 'CAST_TO_STR_TYPE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CastToStrType'>>, 'CEIL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ceil'>>, 'CEILING': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ceil'>>, 'COALESCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'IFNULL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'NVL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Concat'>>, 'CONCAT_WS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ConcatWs'>>, 'COUNT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Count'>>, 'COUNT_IF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CountIf'>>, 'CURRENT_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentDate'>>, 'CURRENT_DATETIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentDatetime'>>, 'CURRENT_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTime'>>, 'CURRENT_TIMESTAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTimestamp'>>, 'CURRENT_USER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>, 'DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Date'>>, 'DATE_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateAdd'>>, 'DATEDIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateDiff'>>, 'DATE_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateDiff'>>, 'DATEFROMPARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateFromParts'>>, 'DATE_STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateStrToDate'>>, 'DATE_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateSub'>>, 'DATE_TO_DATE_STR': <function Parser.<lambda>>, 'DATE_TO_DI': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateToDi'>>, 'DATE_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateTrunc'>>, 'DATETIME_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeAdd'>>, 'DATETIME_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeDiff'>>, 'DATETIME_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeSub'>>, 'DATETIME_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeTrunc'>>, 'DAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Day'>>, 'DAY_OF_MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfMonth'>>, 'DAYOFMONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfMonth'>>, 'DAY_OF_WEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfWeek'>>, 'DAYOFWEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfWeek'>>, 'DAY_OF_YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfYear'>>, 'DAYOFYEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfYear'>>, 'DECODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Decode'>>, 'DI_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DiToDate'>>, 'ENCODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Encode'>>, 'EXP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Exp'>>, 'EXPLODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Explode'>>, 'EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Extract'>>, 'FLOOR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Floor'>>, 'FROM_BASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.FromBase'>>, 'FROM_BASE64': <bound method Func.from_arg_list of <class 'sqlglot.expressions.FromBase64'>>, 'GENERATE_SERIES': <bound method Func.from_arg_list of <class 'sqlglot.expressions.GenerateSeries'>>, 'GREATEST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Greatest'>>, 'GROUP_CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.GroupConcat'>>, 'HEX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Hex'>>, 'HLL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Hll'>>, 'IF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.If'>>, 'INITCAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Initcap'>>, 'IS_NAN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.IsNan'>>, 'ISNAN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.IsNan'>>, 'JSON_ARRAY_CONTAINS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONArrayContains'>>, 'JSONB_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONBExtract'>>, 'JSONB_EXTRACT_SCALAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONBExtractScalar'>>, 'JSON_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONExtract'>>, 'JSON_EXTRACT_SCALAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONExtractScalar'>>, 'JSON_FORMAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONFormat'>>, 'J_S_O_N_OBJECT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONObject'>>, 'LAST_DATE_OF_MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LastDateOfMonth'>>, 'LEAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Least'>>, 'LEFT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Left'>>, 'LENGTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Length'>>, 'LEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Length'>>, 'LEVENSHTEIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Levenshtein'>>, 'LN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ln'>>, 'LOG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Log'>>, 'LOG10': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Log10'>>, 'LOG2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Log2'>>, 'LOGICAL_AND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'BOOL_AND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'BOOLAND_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'LOGICAL_OR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'BOOL_OR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'BOOLOR_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'LOWER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Lower'>>, 'LCASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Lower'>>, 'MD5': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MD5'>>, 'MD5_DIGEST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MD5Digest'>>, 'MAP': <function parse_var_map>, 'MAP_FROM_ENTRIES': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MapFromEntries'>>, 'MATCH_AGAINST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MatchAgainst'>>, 'MAX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Max'>>, 'MIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Min'>>, 'MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Month'>>, 'MONTHS_BETWEEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MonthsBetween'>>, 'NEXT_VALUE_FOR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.NextValueFor'>>, 'NUMBER_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.NumberToStr'>>, 'NVL2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Nvl2'>>, 'OPEN_J_S_O_N': <bound method Func.from_arg_list of <class 'sqlglot.expressions.OpenJSON'>>, 'PARAMETERIZED_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ParameterizedAgg'>>, 'PERCENTILE_CONT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PercentileCont'>>, 'PERCENTILE_DISC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PercentileDisc'>>, 'POSEXPLODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Posexplode'>>, 'POWER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, 'POW': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, 'QUANTILE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Quantile'>>, 'RANGE_N': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RangeN'>>, 'READ_CSV': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ReadCSV'>>, 'REDUCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Reduce'>>, 'REGEXP_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpExtract'>>, 'REGEXP_I_LIKE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpILike'>>, 'REGEXP_LIKE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpLike'>>, 'REGEXP_REPLACE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpReplace'>>, 'REGEXP_SPLIT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpSplit'>>, 'REPEAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Repeat'>>, 'RIGHT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Right'>>, 'ROUND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Round'>>, 'ROW_NUMBER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RowNumber'>>, 'SHA': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA'>>, 'SHA1': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA'>>, 'SHA2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA2'>>, 'SAFE_CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SafeConcat'>>, 'SAFE_DIVIDE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SafeDivide'>>, 'SET_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SetAgg'>>, 'SORT_ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SortArray'>>, 'SPLIT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Split'>>, 'SQRT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Sqrt'>>, 'STANDARD_HASH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StandardHash'>>, 'STAR_MAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StarMap'>>, 'STARTS_WITH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StartsWith'>>, 'STARTSWITH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StartsWith'>>, 'STDDEV': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Stddev'>>, 'STDDEV_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StddevPop'>>, 'STDDEV_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StddevSamp'>>, 'STR_POSITION': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrPosition'>>, 'STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToDate'>>, 'STR_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToTime'>>, 'STR_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToUnix'>>, 'STRUCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Struct'>>, 'STRUCT_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StructExtract'>>, 'SUBSTRING': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Substring'>>, 'SUM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Sum'>>, 'TIME_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeAdd'>>, 'TIME_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeDiff'>>, 'TIME_STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToDate'>>, 'TIME_STR_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToTime'>>, 'TIME_STR_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToUnix'>>, 'TIME_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeSub'>>, 'TIME_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeToStr'>>, 'TIME_TO_TIME_STR': <function Parser.<lambda>>, 'TIME_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeToUnix'>>, 'TIME_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeTrunc'>>, 'TIMESTAMP_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampAdd'>>, 'TIMESTAMP_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampDiff'>>, 'TIMESTAMP_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampSub'>>, 'TIMESTAMP_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampTrunc'>>, 'TO_BASE64': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToBase64'>>, 'TO_CHAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToChar'>>, 'TRANSFORM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Transform'>>, 'TRIM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Trim'>>, 'TRY_CAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TryCast'>>, 'TS_OR_DI_TO_DI': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDiToDi'>>, 'TS_OR_DS_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsAdd'>>, 'TS_OR_DS_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsToDate'>>, 'TS_OR_DS_TO_DATE_STR': <function Parser.<lambda>>, 'UNHEX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Unhex'>>, 'UNIX_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToStr'>>, 'UNIX_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToTime'>>, 'UNIX_TO_TIME_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToTimeStr'>>, 'UPPER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Upper'>>, 'UCASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Upper'>>, 'VAR_MAP': <function parse_var_map>, 'VARIANCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VARIANCE_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VAR_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VARIANCE_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.VariancePop'>>, 'VAR_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.VariancePop'>>, 'WEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Week'>>, 'WEEK_OF_YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.WeekOfYear'>>, 'WEEKOFYEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.WeekOfYear'>>, 'WHEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.When'>>, 'X_M_L_TABLE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.XMLTable'>>, 'XOR': <function ClickHouse.Parser.<lambda>>, 'YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Year'>>, 'GLOB': <function Parser.<lambda>>, 'LIKE': <function parse_like>, 'ANY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.AnyValue'>>, 'MATCH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpLike'>>, 'UNIQ': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxDistinct'>>}
FUNCTIONS_WITH_ALIASED_ARGS = {'TUPLE', 'STRUCT'}
FUNCTION_PARSERS = {'ANY_VALUE': <function Parser.<lambda>>, 'CAST': <function Parser.<lambda>>, 'CONCAT': <function Parser.<lambda>>, 'CONVERT': <function Parser.<lambda>>, 'DECODE': <function Parser.<lambda>>, 'EXTRACT': <function Parser.<lambda>>, 'JSON_OBJECT': <function Parser.<lambda>>, 'LOG': <function Parser.<lambda>>, 'OPENJSON': <function Parser.<lambda>>, 'POSITION': <function Parser.<lambda>>, 'SAFE_CAST': <function Parser.<lambda>>, 'STRING_AGG': <function Parser.<lambda>>, 'SUBSTRING': <function Parser.<lambda>>, 'TRIM': <function Parser.<lambda>>, 'TRY_CAST': <function Parser.<lambda>>, 'TRY_CONVERT': <function Parser.<lambda>>, 'QUANTILE': <function ClickHouse.Parser.<lambda>>}
NO_PAREN_FUNCTION_PARSERS = {<TokenType.CASE: 'CASE'>: <function Parser.<lambda>>, <TokenType.IF: 'IF'>: <function Parser.<lambda>>, <TokenType.NEXT_VALUE_FOR: 'NEXT_VALUE_FOR'>: <function Parser.<lambda>>}
RANGE_PARSERS = {<TokenType.BETWEEN: 'BETWEEN'>: <function Parser.<lambda>>, <TokenType.GLOB: 'GLOB'>: <function binary_range_parser.<locals>.<lambda>>, <TokenType.ILIKE: 'ILIKE'>: <function binary_range_parser.<locals>.<lambda>>, <TokenType.IN: 'IN'>: <function Parser.<lambda>>, <TokenType.IRLIKE: 'IRLIKE'>: <function binary_range_parser.<locals>.<lambda>>, <TokenType.IS: 'IS'>: <function Parser.<lambda>>, <TokenType.LIKE: 'LIKE'>: <function binary_range_parser.<locals>.<lambda>>, <TokenType.OVERLAPS: 'OVERLAPS'>: <function binary_range_parser.<locals>.<lambda>>, <TokenType.RLIKE: 'RLIKE'>: <function binary_range_parser.<locals>.<lambda>>, <TokenType.SIMILAR_TO: 'SIMILAR_TO'>: <function binary_range_parser.<locals>.<lambda>>, <TokenType.GLOBAL: 'GLOBAL'>: <function ClickHouse.Parser.<lambda>>}
COLUMN_OPERATORS = {<TokenType.DOT: 'DOT'>: None, <TokenType.DCOLON: 'DCOLON'>: <function Parser.<lambda>>, <TokenType.ARROW: 'ARROW'>: <function Parser.<lambda>>, <TokenType.DARROW: 'DARROW'>: <function Parser.<lambda>>, <TokenType.HASH_ARROW: 'HASH_ARROW'>: <function Parser.<lambda>>, <TokenType.DHASH_ARROW: 'DHASH_ARROW'>: <function Parser.<lambda>>}
JOIN_KINDS = {<TokenType.ANY: 'ANY'>, <TokenType.CROSS: 'CROSS'>, <TokenType.ASOF: 'ASOF'>, <TokenType.ARRAY: 'ARRAY'>, <TokenType.ANTI: 'ANTI'>, <TokenType.OUTER: 'OUTER'>, <TokenType.INNER: 'INNER'>, <TokenType.SEMI: 'SEMI'>}
TABLE_ALIAS_TOKENS = {<TokenType.LONGBLOB: 'LONGBLOB'>, <TokenType.TRUE: 'TRUE'>, <TokenType.COMMENT: 'COMMENT'>, <TokenType.DATETIME: 'DATETIME'>, <TokenType.TEMPORARY: 'TEMPORARY'>, <TokenType.BIGINT: 'BIGINT'>, <TokenType.VARIANT: 'VARIANT'>, <TokenType.DATERANGE: 'DATERANGE'>, <TokenType.RANGE: 'RANGE'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.FUNCTION: 'FUNCTION'>, <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, <TokenType.ENUM: 'ENUM'>, <TokenType.DELETE: 'DELETE'>, <TokenType.HSTORE: 'HSTORE'>, <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, <TokenType.DEFAULT: 'DEFAULT'>, <TokenType.INT256: 'INT256'>, <TokenType.OBJECT: 'OBJECT'>, <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, <TokenType.INT128: 'INT128'>, <TokenType.END: 'END'>, <TokenType.BOOLEAN: 'BOOLEAN'>, <TokenType.PIVOT: 'PIVOT'>, <TokenType.DOUBLE: 'DOUBLE'>, <TokenType.INT4RANGE: 'INT4RANGE'>, <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, <TokenType.DATETIME64: 'DATETIME64'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.SUPER: 'SUPER'>, <TokenType.TOP: 'TOP'>, <TokenType.PROCEDURE: 'PROCEDURE'>, <TokenType.PERCENT: 'PERCENT'>, <TokenType.INT8RANGE: 'INT8RANGE'>, <TokenType.CHAR: 'CHAR'>, <TokenType.VARBINARY: 'VARBINARY'>, <TokenType.NUMRANGE: 'NUMRANGE'>, <TokenType.GEOMETRY: 'GEOMETRY'>, <TokenType.ASC: 'ASC'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.SMALLSERIAL: 'SMALLSERIAL'>, <TokenType.REFERENCES: 'REFERENCES'>, <TokenType.LOAD: 'LOAD'>, <TokenType.UINT256: 'UINT256'>, <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, <TokenType.BINARY: 'BINARY'>, <TokenType.TSTZRANGE: 'TSTZRANGE'>, <TokenType.INDEX: 'INDEX'>, <TokenType.FILTER: 'FILTER'>, <TokenType.UINT128: 'UINT128'>, <TokenType.JSON: 'JSON'>, <TokenType.INET: 'INET'>, <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, <TokenType.NCHAR: 'NCHAR'>, <TokenType.IF: 'IF'>, <TokenType.USERDEFINED: 'USERDEFINED'>, <TokenType.TIME: 'TIME'>, <TokenType.ROW: 'ROW'>, <TokenType.TSRANGE: 'TSRANGE'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.FLOAT: 'FLOAT'>, <TokenType.NEXT: 'NEXT'>, <TokenType.SOME: 'SOME'>, <TokenType.DATE: 'DATE'>, <TokenType.SET: 'SET'>, <TokenType.OVERWRITE: 'OVERWRITE'>, <TokenType.BIT: 'BIT'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.IPPREFIX: 'IPPREFIX'>, <TokenType.NVARCHAR: 'NVARCHAR'>, <TokenType.VAR: 'VAR'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.DECIMAL: 'DECIMAL'>, <TokenType.USMALLINT: 'USMALLINT'>, <TokenType.VIEW: 'VIEW'>, <TokenType.SMALLMONEY: 'SMALLMONEY'>, <TokenType.NULLABLE: 'NULLABLE'>, <TokenType.UINT: 'UINT'>, <TokenType.SHOW: 'SHOW'>, <TokenType.IPADDRESS: 'IPADDRESS'>, <TokenType.DIV: 'DIV'>, <TokenType.DESCRIBE: 'DESCRIBE'>, <TokenType.VARCHAR: 'VARCHAR'>, <TokenType.STRUCT: 'STRUCT'>, <TokenType.UTINYINT: 'UTINYINT'>, <TokenType.SERIAL: 'SERIAL'>, <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, <TokenType.CASE: 'CASE'>, <TokenType.PARTITION: 'PARTITION'>, <TokenType.IMAGE: 'IMAGE'>, <TokenType.MONEY: 'MONEY'>, <TokenType.ALL: 'ALL'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.ROWVERSION: 'ROWVERSION'>, <TokenType.MAP: 'MAP'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.UNIQUE: 'UNIQUE'>, <TokenType.DESC: 'DESC'>, <TokenType.IS: 'IS'>, <TokenType.XML: 'XML'>, <TokenType.HLLSKETCH: 'HLLSKETCH'>, <TokenType.UUID: 'UUID'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.KEEP: 'KEEP'>, <TokenType.LONGTEXT: 'LONGTEXT'>, <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, <TokenType.TIMESTAMP: 'TIMESTAMP'>, <TokenType.DICTIONARY: 'DICTIONARY'>, <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, <TokenType.VOLATILE: 'VOLATILE'>, <TokenType.FIRST: 'FIRST'>, <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>, <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, <TokenType.ROWS: 'ROWS'>, <TokenType.UNPIVOT: 'UNPIVOT'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.INT: 'INT'>, <TokenType.JSONB: 'JSONB'>, <TokenType.ORDINALITY: 'ORDINALITY'>, <TokenType.TINYINT: 'TINYINT'>, <TokenType.CACHE: 'CACHE'>, <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, <TokenType.SMALLINT: 'SMALLINT'>, <TokenType.COMMIT: 'COMMIT'>, <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <TokenType.UBIGINT: 'UBIGINT'>, <TokenType.CONSTRAINT: 'CONSTRAINT'>, <TokenType.ESCAPE: 'ESCAPE'>, <TokenType.MERGE: 'MERGE'>, <TokenType.BEGIN: 'BEGIN'>, <TokenType.FALSE: 'FALSE'>, <TokenType.TEXT: 'TEXT'>, <TokenType.PRAGMA: 'PRAGMA'>, <TokenType.BIGSERIAL: 'BIGSERIAL'>, <TokenType.COLUMN: 'COLUMN'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.TABLE: 'TABLE'>, <TokenType.INTERVAL: 'INTERVAL'>}
LOG_DEFAULTS_TO_LN = True
QUERY_MODIFIER_PARSERS = {<TokenType.MATCH_RECOGNIZE: 'MATCH_RECOGNIZE'>: <function Parser.<lambda>>, <TokenType.WHERE: 'WHERE'>: <function Parser.<lambda>>, <TokenType.GROUP_BY: 'GROUP_BY'>: <function Parser.<lambda>>, <TokenType.HAVING: 'HAVING'>: <function Parser.<lambda>>, <TokenType.QUALIFY: 'QUALIFY'>: <function Parser.<lambda>>, <TokenType.WINDOW: 'WINDOW'>: <function Parser.<lambda>>, <TokenType.ORDER_BY: 'ORDER_BY'>: <function Parser.<lambda>>, <TokenType.LIMIT: 'LIMIT'>: <function Parser.<lambda>>, <TokenType.FETCH: 'FETCH'>: <function Parser.<lambda>>, <TokenType.OFFSET: 'OFFSET'>: <function Parser.<lambda>>, <TokenType.FOR: 'FOR'>: <function Parser.<lambda>>, <TokenType.LOCK: 'LOCK'>: <function Parser.<lambda>>, <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>: <function Parser.<lambda>>, <TokenType.USING: 'USING'>: <function Parser.<lambda>>, <TokenType.CLUSTER_BY: 'CLUSTER_BY'>: <function Parser.<lambda>>, <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>: <function Parser.<lambda>>, <TokenType.SORT_BY: 'SORT_BY'>: <function Parser.<lambda>>, <TokenType.SETTINGS: 'SETTINGS'>: <function ClickHouse.Parser.<lambda>>, <TokenType.FORMAT: 'FORMAT'>: <function ClickHouse.Parser.<lambda>>}
STRICT_STRING_CONCAT = True
NORMALIZE_FUNCTIONS = False
NULL_ORDERING: str = 'nulls_are_last'
SHOW_TRIE: Dict = {}
SET_TRIE: Dict = {'GLOBAL': {0: True}, 'LOCAL': {0: True}, 'SESSION': {0: True}, 'TRANSACTION': {0: True}}
FORMAT_TRIE: Dict = {}
TIME_TRIE: Dict = {}

##### Inherited Members

sqlglot.parser.Parser
  Parser
  NO_PAREN_FUNCTIONS
  NESTED_TYPE_TOKENS
  ENUM_TYPE_TOKENS
  TYPE_TOKENS
  SUBQUERY_PREDICATES
  RESERVED_KEYWORDS
  DB_CREATABLES
  CREATABLES
  ID_VAR_TOKENS
  INTERVAL_VARS
  COMMENT_TABLE_ALIAS_TOKENS
  UPDATE_ALIAS_TOKENS
  TRIM_TYPES
  FUNC_TOKENS
  CONJUNCTION
  EQUALITY
  COMPARISON
  BITWISE
  TERM
  FACTOR
  TIMESTAMPS
  SET_OPERATIONS
  JOIN_METHODS
  JOIN_SIDES
  JOIN_HINTS
  LAMBDAS
  EXPRESSION_PARSERS
  STATEMENT_PARSERS
  UNARY_PARSERS
  PRIMARY_PARSERS
  PLACEHOLDER_PARSERS
  PROPERTY_PARSERS
  CONSTRAINT_PARSERS
  ALTER_PARSERS
  SCHEMA_UNNAMED_CONSTRAINTS
  SET_PARSERS
  SHOW_PARSERS
  TYPE_LITERAL_PARSERS
  MODIFIABLES
  DDL_SELECT_TOKENS
  PRE_VOLATILE_TOKENS
  TRANSACTION_KIND
  TRANSACTION_CHARACTERISTICS
  INSERT_ALTERNATIVES
  CLONE_KINDS
  TABLE_INDEX_HINT_TOKENS
  WINDOW_ALIAS_TOKENS
  WINDOW_BEFORE_PAREN_TOKENS
  WINDOW_SIDES
  ADD_CONSTRAINT_TOKENS
  STRICT_CAST
  CONCAT_NULL_OUTPUTS_STRING
  PREFIXED_PIVOT_COLUMNS
  IDENTIFY_PIVOT_STRINGS
  LOG_BASE_FIRST
  INDEX_OFFSET
  UNNEST_COLUMN_ONLY
  ALIAS_POST_TABLESAMPLE
  FORMAT_MAPPING
  TIME_MAPPING
  error_level
  error_message_context
  max_errors
  reset
  parse
  parse_into
  check_errors
  raise_error
  expression
  validate_expression
  errors
  sql

class ClickHouse.Generator(sqlglot.generator.Generator): View Source

    288    class Generator(generator.Generator):
    289        QUERY_HINTS = False
    290        STRUCT_DELIMITER = ("(", ")")
    291
    292        TYPE_MAPPING = {
    293            **generator.Generator.TYPE_MAPPING,
    294            exp.DataType.Type.ARRAY: "Array",
    295            exp.DataType.Type.BIGINT: "Int64",
    296            exp.DataType.Type.DATETIME64: "DateTime64",
    297            exp.DataType.Type.DOUBLE: "Float64",
    298            exp.DataType.Type.FLOAT: "Float32",
    299            exp.DataType.Type.INT: "Int32",
    300            exp.DataType.Type.INT128: "Int128",
    301            exp.DataType.Type.INT256: "Int256",
    302            exp.DataType.Type.MAP: "Map",
    303            exp.DataType.Type.NULLABLE: "Nullable",
    304            exp.DataType.Type.SMALLINT: "Int16",
    305            exp.DataType.Type.STRUCT: "Tuple",
    306            exp.DataType.Type.TINYINT: "Int8",
    307            exp.DataType.Type.UBIGINT: "UInt64",
    308            exp.DataType.Type.UINT: "UInt32",
    309            exp.DataType.Type.UINT128: "UInt128",
    310            exp.DataType.Type.UINT256: "UInt256",
    311            exp.DataType.Type.USMALLINT: "UInt16",
    312            exp.DataType.Type.UTINYINT: "UInt8",
    313        }
    314
    315        TRANSFORMS = {
    316            **generator.Generator.TRANSFORMS,
    317            exp.AnyValue: rename_func("any"),
    318            exp.ApproxDistinct: rename_func("uniq"),
    319            exp.Array: inline_array_sql,
    320            exp.CastToStrType: rename_func("CAST"),
    321            exp.Final: lambda self, e: f"{self.sql(e, 'this')} FINAL",
    322            exp.Map: lambda self, e: _lower_func(var_map_sql(self, e)),
    323            exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}",
    324            exp.Pivot: no_pivot_sql,
    325            exp.Quantile: lambda self, e: self.func("quantile", e.args.get("quantile"))
    326            + f"({self.sql(e, 'this')})",
    327            exp.RegexpLike: lambda self, e: f"match({self.format_args(e.this, e.expression)})",
    328            exp.StrPosition: lambda self, e: f"position({self.format_args(e.this, e.args.get('substr'), e.args.get('position'))})",
    329            exp.VarMap: lambda self, e: _lower_func(var_map_sql(self, e)),
    330            exp.Xor: lambda self, e: self.func("xor", e.this, e.expression, *e.expressions),
    331        }
    332
    333        PROPERTIES_LOCATION = {
    334            **generator.Generator.PROPERTIES_LOCATION,
    335            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    336            exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA,
    337            exp.OnCluster: exp.Properties.Location.POST_NAME,
    338        }
    339
    340        JOIN_HINTS = False
    341        TABLE_HINTS = False
    342        EXPLICIT_UNION = True
    343        GROUPINGS_SEP = ""
    344
    345        # there's no list in docs, but it can be found in Clickhouse code
    346        # see `ClickHouse/src/Parsers/ParserCreate*.cpp`
    347        ON_CLUSTER_TARGETS = {
    348            "DATABASE",
    349            "TABLE",
    350            "VIEW",
    351            "DICTIONARY",
    352            "INDEX",
    353            "FUNCTION",
    354            "NAMED COLLECTION",
    355        }
    356
    357        def safeconcat_sql(self, expression: exp.SafeConcat) -> str:
    358            # Clickhouse errors out if we try to cast a NULL value to TEXT
    359            return self.func(
    360                "CONCAT",
    361                *[
    362                    exp.func("if", e.is_(exp.null()), e, exp.cast(e, "text"))
    363                    for e in t.cast(t.List[exp.Condition], expression.expressions)
    364                ],
    365            )
    366
    367        def cte_sql(self, expression: exp.CTE) -> str:
    368            if isinstance(expression.this, exp.Alias):
    369                return self.sql(expression, "this")
    370
    371            return super().cte_sql(expression)
    372
    373        def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
    374            return super().after_limit_modifiers(expression) + [
    375                self.seg("SETTINGS ") + self.expressions(expression, key="settings", flat=True)
    376                if expression.args.get("settings")
    377                else "",
    378                self.seg("FORMAT ") + self.sql(expression, "format")
    379                if expression.args.get("format")
    380                else "",
    381            ]
    382
    383        def parameterizedagg_sql(self, expression: exp.Anonymous) -> str:
    384            params = self.expressions(expression, key="params", flat=True)
    385            return self.func(expression.name, *expression.expressions) + f"({params})"
    386
    387        def placeholder_sql(self, expression: exp.Placeholder) -> str:
    388            return f"{{{expression.name}: {self.sql(expression, 'kind')}}}"
    389
    390        def oncluster_sql(self, expression: exp.OnCluster) -> str:
    391            return f"ON CLUSTER {self.sql(expression, 'this')}"
    392
    393        def createable_sql(
    394            self,
    395            expression: exp.Create,
    396            locations: dict[exp.Properties.Location, list[exp.Property]],
    397        ) -> str:
    398            kind = self.sql(expression, "kind").upper()
    399            if kind in self.ON_CLUSTER_TARGETS and locations.get(exp.Properties.Location.POST_NAME):
    400                this_name = self.sql(expression.this, "this")
    401                this_properties = " ".join(
    402                    [self.sql(prop) for prop in locations[exp.Properties.Location.POST_NAME]]
    403                )
    404                this_schema = self.schema_columns_sql(expression.this)
    405                return f"{this_name}{self.sep()}{this_properties}{self.sep()}{this_schema}"
    406            return super().createable_sql(expression, locations)

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

QUERY_HINTS = False
STRUCT_DELIMITER = ('(', ')')
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', <Type.ARRAY: 'ARRAY'>: 'Array', <Type.BIGINT: 'BIGINT'>: 'Int64', <Type.DATETIME64: 'DATETIME64'>: 'DateTime64', <Type.DOUBLE: 'DOUBLE'>: 'Float64', <Type.FLOAT: 'FLOAT'>: 'Float32', <Type.INT: 'INT'>: 'Int32', <Type.INT128: 'INT128'>: 'Int128', <Type.INT256: 'INT256'>: 'Int256', <Type.MAP: 'MAP'>: 'Map', <Type.NULLABLE: 'NULLABLE'>: 'Nullable', <Type.SMALLINT: 'SMALLINT'>: 'Int16', <Type.STRUCT: 'STRUCT'>: 'Tuple', <Type.TINYINT: 'TINYINT'>: 'Int8', <Type.UBIGINT: 'UBIGINT'>: 'UInt64', <Type.UINT: 'UINT'>: 'UInt32', <Type.UINT128: 'UINT128'>: 'UInt128', <Type.UINT256: 'UINT256'>: 'UInt256', <Type.USMALLINT: 'USMALLINT'>: 'UInt16', <Type.UTINYINT: 'UTINYINT'>: 'UInt8'}
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.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.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.OnCommitProperty'>: <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 ClickHouse.Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AnyValue'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.ApproxDistinct'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.Array'>: <function inline_array_sql>, <class 'sqlglot.expressions.CastToStrType'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.Final'>: <function ClickHouse.Generator.<lambda>>, <class 'sqlglot.expressions.Map'>: <function ClickHouse.Generator.<lambda>>, <class 'sqlglot.expressions.PartitionedByProperty'>: <function ClickHouse.Generator.<lambda>>, <class 'sqlglot.expressions.Pivot'>: <function no_pivot_sql>, <class 'sqlglot.expressions.Quantile'>: <function ClickHouse.Generator.<lambda>>, <class 'sqlglot.expressions.RegexpLike'>: <function ClickHouse.Generator.<lambda>>, <class 'sqlglot.expressions.StrPosition'>: <function ClickHouse.Generator.<lambda>>, <class 'sqlglot.expressions.Xor'>: <function ClickHouse.Generator.<lambda>>}
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.OnCommitProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.Order'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PartitionedByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.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.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.OnCluster'>: <Location.POST_NAME: 'POST_NAME'>}
JOIN_HINTS = False
TABLE_HINTS = False
EXPLICIT_UNION = True
GROUPINGS_SEP = ''
ON_CLUSTER_TARGETS = {'DATABASE', 'TABLE', 'INDEX', 'VIEW', 'FUNCTION', 'NAMED COLLECTION', 'DICTIONARY'}
def safeconcat_sql(self, expression: sqlglot.expressions.SafeConcat) -> str: View Source

    357        def safeconcat_sql(self, expression: exp.SafeConcat) -> str:
    358            # Clickhouse errors out if we try to cast a NULL value to TEXT
    359            return self.func(
    360                "CONCAT",
    361                *[
    362                    exp.func("if", e.is_(exp.null()), e, exp.cast(e, "text"))
    363                    for e in t.cast(t.List[exp.Condition], expression.expressions)
    364                ],
    365            )

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

    367        def cte_sql(self, expression: exp.CTE) -> str:
    368            if isinstance(expression.this, exp.Alias):
    369                return self.sql(expression, "this")
    370
    371            return super().cte_sql(expression)

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

    373        def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
    374            return super().after_limit_modifiers(expression) + [
    375                self.seg("SETTINGS ") + self.expressions(expression, key="settings", flat=True)
    376                if expression.args.get("settings")
    377                else "",
    378                self.seg("FORMAT ") + self.sql(expression, "format")
    379                if expression.args.get("format")
    380                else "",
    381            ]

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

    383        def parameterizedagg_sql(self, expression: exp.Anonymous) -> str:
    384            params = self.expressions(expression, key="params", flat=True)
    385            return self.func(expression.name, *expression.expressions) + f"({params})"

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

    387        def placeholder_sql(self, expression: exp.Placeholder) -> str:
    388            return f"{{{expression.name}: {self.sql(expression, 'kind')}}}"

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

    390        def oncluster_sql(self, expression: exp.OnCluster) -> str:
    391            return f"ON CLUSTER {self.sql(expression, 'this')}"

def createable_sql( self, expression: sqlglot.expressions.Create, locations: dict[sqlglot.expressions.Properties.Location, list[sqlglot.expressions.Property]]) -> str: View Source

    393        def createable_sql(
    394            self,
    395            expression: exp.Create,
    396            locations: dict[exp.Properties.Location, list[exp.Property]],
    397        ) -> str:
    398            kind = self.sql(expression, "kind").upper()
    399            if kind in self.ON_CLUSTER_TARGETS and locations.get(exp.Properties.Location.POST_NAME):
    400                this_name = self.sql(expression.this, "this")
    401                this_properties = " ".join(
    402                    [self.sql(prop) for prop in locations[exp.Properties.Location.POST_NAME]]
    403                )
    404                this_schema = self.schema_columns_sql(expression.this)
    405                return f"{this_name}{self.sep()}{this_properties}{self.sep()}{this_schema}"
    406            return super().createable_sql(expression, locations)

SELECT_KINDS: Tuple[str, ...] = ()
INVERSE_TIME_MAPPING: Dict[str, str] = {}
INVERSE_TIME_TRIE: Dict = {}
STRICT_STRING_CONCAT = True
NORMALIZE_FUNCTIONS: bool | str = False
NULL_ORDERING = 'nulls_are_last'
@classmethod
def can_identify(text: str, identify: str | bool = 'safe') -> bool: View Source

    253    @classmethod
    254    def can_identify(cls, text: str, identify: str | bool = "safe") -> bool:
    255        """Checks if text can be identified given an identify option.
    256
    257        Args:
    258            text: The text to check.
    259            identify:
    260                "always" or `True`: Always returns true.
    261                "safe": True if the identifier is case-insensitive.
    262
    263        Returns:
    264            Whether or not the given text can be identified.
    265        """
    266        if identify is True or identify == "always":
    267            return True
    268
    269        if identify == "safe":
    270            return not cls.case_sensitive(text)
    271
    272        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 = '"'
STRING_ESCAPE = "'"
IDENTIFIER_ESCAPE = '"'
BIT_START: Optional[str] = '0b'
BIT_END: Optional[str] = ''
HEX_START: Optional[str] = '0x'
HEX_END: Optional[str] = ''
BYTE_START: Optional[str] = None
BYTE_END: Optional[str] = None

##### Inherited Members

sqlglot.generator.Generator
  Generator
  NULL_ORDERING_SUPPORTED
  LOCKING_READS_SUPPORTED
  WRAP_DERIVED_VALUES
  CREATE_FUNCTION_RETURN_AS
  MATCHED_BY_SOURCE
  SINGLE_STRING_INTERVAL
  INTERVAL_ALLOWS_PLURAL_FORM
  TABLESAMPLE_WITH_METHOD
  TABLESAMPLE_SIZE_IS_PERCENT
  LIMIT_FETCH
  RENAME_TABLE_WITH_DB
  INDEX_ON
  QUERY_HINT_SEP
  IS_BOOL_ALLOWED
  DUPLICATE_KEY_UPDATE_WITH_SET
  LIMIT_IS_TOP
  RETURNING_END
  COLUMN_JOIN_MARKS_SUPPORTED
  EXTRACT_ALLOWS_QUOTES
  VALUES_AS_TABLE
  STAR_MAPPING
  TIME_PART_SINGULARS
  TOKEN_MAPPING
  PARAMETER_TOKEN
  RESERVED_KEYWORDS
  WITH_SEPARATED_COMMENTS
  UNWRAPPED_INTERVAL_VALUES
  SENTINEL_LINE_BREAK
  INDEX_OFFSET
  UNNEST_COLUMN_ONLY
  ALIAS_POST_TABLESAMPLE
  IDENTIFIERS_CAN_START_WITH_DIGIT
  ESCAPE_LINE_BREAK
  pretty
  identify
  normalize
  pad
  unsupported_level
  max_unsupported
  leading_comma
  max_text_width
  comments
  normalize_functions
  unsupported_messages
  generate
  unsupported
  sep
  seg
  pad_comment
  maybe_comment
  wrap
  no_identify
  normalize_func
  indent
  sql
  uncache_sql
  cache_sql
  characterset_sql
  column_sql
  columnposition_sql
  columndef_sql
  columnconstraint_sql
  autoincrementcolumnconstraint_sql
  compresscolumnconstraint_sql
  generatedasidentitycolumnconstraint_sql
  notnullcolumnconstraint_sql
  primarykeycolumnconstraint_sql
  uniquecolumnconstraint_sql
  create_sql
  clone_sql
  describe_sql
  prepend_ctes
  with_sql
  tablealias_sql
  bitstring_sql
  hexstring_sql
  bytestring_sql
  rawstring_sql
  datatypesize_sql
  datatype_sql
  directory_sql
  delete_sql
  drop_sql
  except_sql
  except_op
  fetch_sql
  filter_sql
  hint_sql
  index_sql
  identifier_sql
  inputoutputformat_sql
  national_sql
  partition_sql
  properties_sql
  root_properties
  properties
  with_properties
  locate_properties
  property_sql
  likeproperty_sql
  fallbackproperty_sql
  journalproperty_sql
  freespaceproperty_sql
  checksumproperty_sql
  mergeblockratioproperty_sql
  datablocksizeproperty_sql
  blockcompressionproperty_sql
  isolatedloadingproperty_sql
  lockingproperty_sql
  withdataproperty_sql
  insert_sql
  intersect_sql
  intersect_op
  introducer_sql
  pseudotype_sql
  onconflict_sql
  returning_sql
  rowformatdelimitedproperty_sql
  withtablehint_sql
  indextablehint_sql
  table_sql
  tablesample_sql
  pivot_sql
  tuple_sql
  update_sql
  values_sql
  var_sql
  into_sql
  from_sql
  group_sql
  having_sql
  join_sql
  lambda_sql
  lateral_sql
  limit_sql
  offset_sql
  setitem_sql
  set_sql
  pragma_sql
  lock_sql
  literal_sql
  escape_str
  loaddata_sql
  null_sql
  boolean_sql
  order_sql
  cluster_sql
  distribute_sql
  sort_sql
  ordered_sql
  matchrecognize_sql
  query_modifiers
  offset_limit_modifiers
  after_having_modifiers
  select_sql
  schema_sql
  schema_columns_sql
  star_sql
  parameter_sql
  sessionparameter_sql
  subquery_sql
  qualify_sql
  union_sql
  union_op
  unnest_sql
  where_sql
  window_sql
  partition_by_sql
  windowspec_sql
  withingroup_sql
  between_sql
  bracket_sql
  safebracket_sql
  all_sql
  any_sql
  exists_sql
  case_sql
  constraint_sql
  nextvaluefor_sql
  extract_sql
  trim_sql
  check_sql
  foreignkey_sql
  primarykey_sql
  if_sql
  matchagainst_sql
  jsonkeyvalue_sql
  jsonobject_sql
  openjsoncolumndef_sql
  openjson_sql
  in_sql
  in_unnest_op
  interval_sql
  return_sql
  reference_sql
  anonymous_sql
  paren_sql
  neg_sql
  not_sql
  alias_sql
  aliases_sql
  attimezone_sql
  add_sql
  and_sql
  xor_sql
  connector_sql
  bitwiseand_sql
  bitwiseleftshift_sql
  bitwisenot_sql
  bitwiseor_sql
  bitwiserightshift_sql
  bitwisexor_sql
  cast_sql
  currentdate_sql
  collate_sql
  command_sql
  comment_sql
  mergetreettlaction_sql
  mergetreettl_sql
  transaction_sql
  commit_sql
  rollback_sql
  altercolumn_sql
  renametable_sql
  altertable_sql
  droppartition_sql
  addconstraint_sql
  distinct_sql
  ignorenulls_sql
  respectnulls_sql
  intdiv_sql
  dpipe_sql
  safedpipe_sql
  div_sql
  overlaps_sql
  distance_sql
  dot_sql
  eq_sql
  escape_sql
  glob_sql
  gt_sql
  gte_sql
  ilike_sql
  ilikeany_sql
  is_sql
  like_sql
  likeany_sql
  similarto_sql
  lt_sql
  lte_sql
  mod_sql
  mul_sql
  neq_sql
  nullsafeeq_sql
  nullsafeneq_sql
  or_sql
  slice_sql
  sub_sql
  trycast_sql
  use_sql
  binary
  function_fallback_sql
  func
  format_args
  text_width
  format_time
  expressions
  op_expressions
  naked_property
  set_operation
  tag_sql
  token_sql
  userdefinedfunction_sql
  joinhint_sql
  kwarg_sql
  when_sql
  merge_sql
  tochar_sql
  dictproperty_sql
  dictrange_sql
  dictsubproperty_sql
  clusteredbyproperty_sql
  anyvalue_sql
  querytransform_sql
  indexconstraintoption_sql
  indexcolumnconstraint_sql