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, transforms
      6from sqlglot.dialects.dialect import (
      7    Dialect,
      8    arg_max_or_min_no_count,
      9    inline_array_sql,
     10    no_pivot_sql,
     11    rename_func,
     12    var_map_sql,
     13)
     14from sqlglot.errors import ParseError
     15from sqlglot.helper import seq_get
     16from sqlglot.parser import parse_var_map
     17from sqlglot.tokens import Token, TokenType
     18
     19
     20def _lower_func(sql: str) -> str:
     21    index = sql.index("(")
     22    return sql[:index].lower() + sql[index:]
     23
     24
     25def _quantile_sql(self, e):
     26    quantile = e.args["quantile"]
     27    args = f"({self.sql(e, 'this')})"
     28    if isinstance(quantile, exp.Array):
     29        func = self.func("quantiles", *quantile)
     30    else:
     31        func = self.func("quantile", quantile)
     32    return func + args
     33
     34
     35class ClickHouse(Dialect):
     36    NORMALIZE_FUNCTIONS: bool | str = False
     37    NULL_ORDERING = "nulls_are_last"
     38    STRICT_STRING_CONCAT = True
     39    SUPPORTS_USER_DEFINED_TYPES = False
     40    SAFE_DIVISION = True
     41
     42    ESCAPE_SEQUENCES = {
     43        "\\0": "\0",
     44    }
     45
     46    class Tokenizer(tokens.Tokenizer):
     47        COMMENTS = ["--", "#", "#!", ("/*", "*/")]
     48        IDENTIFIERS = ['"', "`"]
     49        STRING_ESCAPES = ["'", "\\"]
     50        BIT_STRINGS = [("0b", "")]
     51        HEX_STRINGS = [("0x", ""), ("0X", "")]
     52        HEREDOC_STRINGS = ["$"]
     53
     54        KEYWORDS = {
     55            **tokens.Tokenizer.KEYWORDS,
     56            "ATTACH": TokenType.COMMAND,
     57            "DATETIME64": TokenType.DATETIME64,
     58            "DICTIONARY": TokenType.DICTIONARY,
     59            "ENUM": TokenType.ENUM,
     60            "ENUM8": TokenType.ENUM8,
     61            "ENUM16": TokenType.ENUM16,
     62            "FINAL": TokenType.FINAL,
     63            "FIXEDSTRING": TokenType.FIXEDSTRING,
     64            "FLOAT32": TokenType.FLOAT,
     65            "FLOAT64": TokenType.DOUBLE,
     66            "GLOBAL": TokenType.GLOBAL,
     67            "INT256": TokenType.INT256,
     68            "LOWCARDINALITY": TokenType.LOWCARDINALITY,
     69            "MAP": TokenType.MAP,
     70            "NESTED": TokenType.NESTED,
     71            "SAMPLE": TokenType.TABLE_SAMPLE,
     72            "TUPLE": TokenType.STRUCT,
     73            "UINT128": TokenType.UINT128,
     74            "UINT16": TokenType.USMALLINT,
     75            "UINT256": TokenType.UINT256,
     76            "UINT32": TokenType.UINT,
     77            "UINT64": TokenType.UBIGINT,
     78            "UINT8": TokenType.UTINYINT,
     79        }
     80
     81        SINGLE_TOKENS = {
     82            **tokens.Tokenizer.SINGLE_TOKENS,
     83            "$": TokenType.HEREDOC_STRING,
     84        }
     85
     86    class Parser(parser.Parser):
     87        FUNCTIONS = {
     88            **parser.Parser.FUNCTIONS,
     89            "ANY": exp.AnyValue.from_arg_list,
     90            "DATE_ADD": lambda args: exp.DateAdd(
     91                this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0)
     92            ),
     93            "DATEADD": lambda args: exp.DateAdd(
     94                this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0)
     95            ),
     96            "DATE_DIFF": lambda args: exp.DateDiff(
     97                this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0)
     98            ),
     99            "DATEDIFF": lambda args: exp.DateDiff(
    100                this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0)
    101            ),
    102            "MAP": parse_var_map,
    103            "MATCH": exp.RegexpLike.from_arg_list,
    104            "UNIQ": exp.ApproxDistinct.from_arg_list,
    105            "XOR": lambda args: exp.Xor(expressions=args),
    106        }
    107
    108        FUNCTIONS_WITH_ALIASED_ARGS = {*parser.Parser.FUNCTIONS_WITH_ALIASED_ARGS, "TUPLE"}
    109
    110        FUNCTION_PARSERS = {
    111            **parser.Parser.FUNCTION_PARSERS,
    112            "QUANTILE": lambda self: self._parse_quantile(),
    113        }
    114
    115        FUNCTION_PARSERS.pop("MATCH")
    116
    117        NO_PAREN_FUNCTION_PARSERS = parser.Parser.NO_PAREN_FUNCTION_PARSERS.copy()
    118        NO_PAREN_FUNCTION_PARSERS.pop("ANY")
    119
    120        RANGE_PARSERS = {
    121            **parser.Parser.RANGE_PARSERS,
    122            TokenType.GLOBAL: lambda self, this: self._match(TokenType.IN)
    123            and self._parse_in(this, is_global=True),
    124        }
    125
    126        # The PLACEHOLDER entry is popped because 1) it doesn't affect Clickhouse (it corresponds to
    127        # the postgres-specific JSONBContains parser) and 2) it makes parsing the ternary op simpler.
    128        COLUMN_OPERATORS = parser.Parser.COLUMN_OPERATORS.copy()
    129        COLUMN_OPERATORS.pop(TokenType.PLACEHOLDER)
    130
    131        JOIN_KINDS = {
    132            *parser.Parser.JOIN_KINDS,
    133            TokenType.ANY,
    134            TokenType.ASOF,
    135            TokenType.ARRAY,
    136        }
    137
    138        TABLE_ALIAS_TOKENS = parser.Parser.TABLE_ALIAS_TOKENS - {
    139            TokenType.ANY,
    140            TokenType.SETTINGS,
    141            TokenType.FORMAT,
    142            TokenType.ARRAY,
    143        }
    144
    145        LOG_DEFAULTS_TO_LN = True
    146
    147        QUERY_MODIFIER_PARSERS = {
    148            **parser.Parser.QUERY_MODIFIER_PARSERS,
    149            TokenType.SETTINGS: lambda self: (
    150                "settings",
    151                self._advance() or self._parse_csv(self._parse_conjunction),
    152            ),
    153            TokenType.FORMAT: lambda self: ("format", self._advance() or self._parse_id_var()),
    154        }
    155
    156        def _parse_conjunction(self) -> t.Optional[exp.Expression]:
    157            this = super()._parse_conjunction()
    158
    159            if self._match(TokenType.PLACEHOLDER):
    160                return self.expression(
    161                    exp.If,
    162                    this=this,
    163                    true=self._parse_conjunction(),
    164                    false=self._match(TokenType.COLON) and self._parse_conjunction(),
    165                )
    166
    167            return this
    168
    169        def _parse_placeholder(self) -> t.Optional[exp.Expression]:
    170            """
    171            Parse a placeholder expression like SELECT {abc: UInt32} or FROM {table: Identifier}
    172            https://clickhouse.com/docs/en/sql-reference/syntax#defining-and-using-query-parameters
    173            """
    174            if not self._match(TokenType.L_BRACE):
    175                return None
    176
    177            this = self._parse_id_var()
    178            self._match(TokenType.COLON)
    179            kind = self._parse_types(check_func=False, allow_identifiers=False) or (
    180                self._match_text_seq("IDENTIFIER") and "Identifier"
    181            )
    182
    183            if not kind:
    184                self.raise_error("Expecting a placeholder type or 'Identifier' for tables")
    185            elif not self._match(TokenType.R_BRACE):
    186                self.raise_error("Expecting }")
    187
    188            return self.expression(exp.Placeholder, this=this, kind=kind)
    189
    190        def _parse_in(self, this: t.Optional[exp.Expression], is_global: bool = False) -> exp.In:
    191            this = super()._parse_in(this)
    192            this.set("is_global", is_global)
    193            return this
    194
    195        def _parse_table(
    196            self,
    197            schema: bool = False,
    198            joins: bool = False,
    199            alias_tokens: t.Optional[t.Collection[TokenType]] = None,
    200            parse_bracket: bool = False,
    201        ) -> t.Optional[exp.Expression]:
    202            this = super()._parse_table(
    203                schema=schema, joins=joins, alias_tokens=alias_tokens, parse_bracket=parse_bracket
    204            )
    205
    206            if self._match(TokenType.FINAL):
    207                this = self.expression(exp.Final, this=this)
    208
    209            return this
    210
    211        def _parse_position(self, haystack_first: bool = False) -> exp.StrPosition:
    212            return super()._parse_position(haystack_first=True)
    213
    214        # https://clickhouse.com/docs/en/sql-reference/statements/select/with/
    215        def _parse_cte(self) -> exp.CTE:
    216            index = self._index
    217            try:
    218                # WITH <identifier> AS <subquery expression>
    219                return super()._parse_cte()
    220            except ParseError:
    221                # WITH <expression> AS <identifier>
    222                self._retreat(index)
    223
    224                return self.expression(
    225                    exp.CTE,
    226                    this=self._parse_field(),
    227                    alias=self._parse_table_alias(),
    228                    scalar=True,
    229                )
    230
    231        def _parse_join_parts(
    232            self,
    233        ) -> t.Tuple[t.Optional[Token], t.Optional[Token], t.Optional[Token]]:
    234            is_global = self._match(TokenType.GLOBAL) and self._prev
    235            kind_pre = self._match_set(self.JOIN_KINDS, advance=False) and self._prev
    236
    237            if kind_pre:
    238                kind = self._match_set(self.JOIN_KINDS) and self._prev
    239                side = self._match_set(self.JOIN_SIDES) and self._prev
    240                return is_global, side, kind
    241
    242            return (
    243                is_global,
    244                self._match_set(self.JOIN_SIDES) and self._prev,
    245                self._match_set(self.JOIN_KINDS) and self._prev,
    246            )
    247
    248        def _parse_join(
    249            self, skip_join_token: bool = False, parse_bracket: bool = False
    250        ) -> t.Optional[exp.Join]:
    251            join = super()._parse_join(skip_join_token=skip_join_token, parse_bracket=True)
    252
    253            if join:
    254                join.set("global", join.args.pop("method", None))
    255            return join
    256
    257        def _parse_function(
    258            self,
    259            functions: t.Optional[t.Dict[str, t.Callable]] = None,
    260            anonymous: bool = False,
    261            optional_parens: bool = True,
    262        ) -> t.Optional[exp.Expression]:
    263            func = super()._parse_function(
    264                functions=functions, anonymous=anonymous, optional_parens=optional_parens
    265            )
    266
    267            if isinstance(func, exp.Anonymous):
    268                params = self._parse_func_params(func)
    269
    270                if params:
    271                    return self.expression(
    272                        exp.ParameterizedAgg,
    273                        this=func.this,
    274                        expressions=func.expressions,
    275                        params=params,
    276                    )
    277
    278            return func
    279
    280        def _parse_func_params(
    281            self, this: t.Optional[exp.Func] = None
    282        ) -> t.Optional[t.List[exp.Expression]]:
    283            if self._match_pair(TokenType.R_PAREN, TokenType.L_PAREN):
    284                return self._parse_csv(self._parse_lambda)
    285
    286            if self._match(TokenType.L_PAREN):
    287                params = self._parse_csv(self._parse_lambda)
    288                self._match_r_paren(this)
    289                return params
    290
    291            return None
    292
    293        def _parse_quantile(self) -> exp.Quantile:
    294            this = self._parse_lambda()
    295            params = self._parse_func_params()
    296            if params:
    297                return self.expression(exp.Quantile, this=params[0], quantile=this)
    298            return self.expression(exp.Quantile, this=this, quantile=exp.Literal.number(0.5))
    299
    300        def _parse_wrapped_id_vars(self, optional: bool = False) -> t.List[exp.Expression]:
    301            return super()._parse_wrapped_id_vars(optional=True)
    302
    303        def _parse_primary_key(
    304            self, wrapped_optional: bool = False, in_props: bool = False
    305        ) -> exp.PrimaryKeyColumnConstraint | exp.PrimaryKey:
    306            return super()._parse_primary_key(
    307                wrapped_optional=wrapped_optional or in_props, in_props=in_props
    308            )
    309
    310        def _parse_on_property(self) -> t.Optional[exp.Expression]:
    311            index = self._index
    312            if self._match_text_seq("CLUSTER"):
    313                this = self._parse_id_var()
    314                if this:
    315                    return self.expression(exp.OnCluster, this=this)
    316                else:
    317                    self._retreat(index)
    318            return None
    319
    320    class Generator(generator.Generator):
    321        QUERY_HINTS = False
    322        STRUCT_DELIMITER = ("(", ")")
    323        NVL2_SUPPORTED = False
    324        TABLESAMPLE_REQUIRES_PARENS = False
    325
    326        STRING_TYPE_MAPPING = {
    327            exp.DataType.Type.CHAR: "String",
    328            exp.DataType.Type.LONGBLOB: "String",
    329            exp.DataType.Type.LONGTEXT: "String",
    330            exp.DataType.Type.MEDIUMBLOB: "String",
    331            exp.DataType.Type.MEDIUMTEXT: "String",
    332            exp.DataType.Type.TINYBLOB: "String",
    333            exp.DataType.Type.TINYTEXT: "String",
    334            exp.DataType.Type.TEXT: "String",
    335            exp.DataType.Type.VARBINARY: "String",
    336            exp.DataType.Type.VARCHAR: "String",
    337        }
    338
    339        TYPE_MAPPING = {
    340            **generator.Generator.TYPE_MAPPING,
    341            **STRING_TYPE_MAPPING,
    342            exp.DataType.Type.ARRAY: "Array",
    343            exp.DataType.Type.BIGINT: "Int64",
    344            exp.DataType.Type.DATETIME64: "DateTime64",
    345            exp.DataType.Type.DOUBLE: "Float64",
    346            exp.DataType.Type.ENUM: "Enum",
    347            exp.DataType.Type.ENUM8: "Enum8",
    348            exp.DataType.Type.ENUM16: "Enum16",
    349            exp.DataType.Type.FIXEDSTRING: "FixedString",
    350            exp.DataType.Type.FLOAT: "Float32",
    351            exp.DataType.Type.INT: "Int32",
    352            exp.DataType.Type.MEDIUMINT: "Int32",
    353            exp.DataType.Type.INT128: "Int128",
    354            exp.DataType.Type.INT256: "Int256",
    355            exp.DataType.Type.LOWCARDINALITY: "LowCardinality",
    356            exp.DataType.Type.MAP: "Map",
    357            exp.DataType.Type.NESTED: "Nested",
    358            exp.DataType.Type.NULLABLE: "Nullable",
    359            exp.DataType.Type.SMALLINT: "Int16",
    360            exp.DataType.Type.STRUCT: "Tuple",
    361            exp.DataType.Type.TINYINT: "Int8",
    362            exp.DataType.Type.UBIGINT: "UInt64",
    363            exp.DataType.Type.UINT: "UInt32",
    364            exp.DataType.Type.UINT128: "UInt128",
    365            exp.DataType.Type.UINT256: "UInt256",
    366            exp.DataType.Type.USMALLINT: "UInt16",
    367            exp.DataType.Type.UTINYINT: "UInt8",
    368        }
    369
    370        TRANSFORMS = {
    371            **generator.Generator.TRANSFORMS,
    372            exp.Select: transforms.preprocess([transforms.eliminate_qualify]),
    373            exp.AnyValue: rename_func("any"),
    374            exp.ApproxDistinct: rename_func("uniq"),
    375            exp.ArgMax: arg_max_or_min_no_count("argMax"),
    376            exp.ArgMin: arg_max_or_min_no_count("argMin"),
    377            exp.Array: inline_array_sql,
    378            exp.CastToStrType: rename_func("CAST"),
    379            exp.CurrentDate: lambda self, e: self.func("CURRENT_DATE"),
    380            exp.DateAdd: lambda self, e: self.func(
    381                "DATE_ADD", exp.Literal.string(e.text("unit") or "day"), e.expression, e.this
    382            ),
    383            exp.DateDiff: lambda self, e: self.func(
    384                "DATE_DIFF", exp.Literal.string(e.text("unit") or "day"), e.expression, e.this
    385            ),
    386            exp.Final: lambda self, e: f"{self.sql(e, 'this')} FINAL",
    387            exp.IsNan: rename_func("isNaN"),
    388            exp.Map: lambda self, e: _lower_func(var_map_sql(self, e)),
    389            exp.Nullif: rename_func("nullIf"),
    390            exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}",
    391            exp.Pivot: no_pivot_sql,
    392            exp.Quantile: _quantile_sql,
    393            exp.RegexpLike: lambda self, e: f"match({self.format_args(e.this, e.expression)})",
    394            exp.StartsWith: rename_func("startsWith"),
    395            exp.StrPosition: lambda self, e: f"position({self.format_args(e.this, e.args.get('substr'), e.args.get('position'))})",
    396            exp.VarMap: lambda self, e: _lower_func(var_map_sql(self, e)),
    397            exp.Xor: lambda self, e: self.func("xor", e.this, e.expression, *e.expressions),
    398        }
    399
    400        PROPERTIES_LOCATION = {
    401            **generator.Generator.PROPERTIES_LOCATION,
    402            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    403            exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA,
    404            exp.OnCluster: exp.Properties.Location.POST_NAME,
    405        }
    406
    407        JOIN_HINTS = False
    408        TABLE_HINTS = False
    409        EXPLICIT_UNION = True
    410        GROUPINGS_SEP = ""
    411
    412        # there's no list in docs, but it can be found in Clickhouse code
    413        # see `ClickHouse/src/Parsers/ParserCreate*.cpp`
    414        ON_CLUSTER_TARGETS = {
    415            "DATABASE",
    416            "TABLE",
    417            "VIEW",
    418            "DICTIONARY",
    419            "INDEX",
    420            "FUNCTION",
    421            "NAMED COLLECTION",
    422        }
    423
    424        def _any_to_has(
    425            self,
    426            expression: exp.EQ | exp.NEQ,
    427            default: t.Callable[[t.Any], str],
    428            prefix: str = "",
    429        ) -> str:
    430            if isinstance(expression.left, exp.Any):
    431                arr = expression.left
    432                this = expression.right
    433            elif isinstance(expression.right, exp.Any):
    434                arr = expression.right
    435                this = expression.left
    436            else:
    437                return default(expression)
    438            return prefix + self.func("has", arr.this.unnest(), this)
    439
    440        def eq_sql(self, expression: exp.EQ) -> str:
    441            return self._any_to_has(expression, super().eq_sql)
    442
    443        def neq_sql(self, expression: exp.NEQ) -> str:
    444            return self._any_to_has(expression, super().neq_sql, "NOT ")
    445
    446        def regexpilike_sql(self, expression: exp.RegexpILike) -> str:
    447            # Manually add a flag to make the search case-insensitive
    448            regex = self.func("CONCAT", "'(?i)'", expression.expression)
    449            return f"match({self.format_args(expression.this, regex)})"
    450
    451        def datatype_sql(self, expression: exp.DataType) -> str:
    452            # String is the standard ClickHouse type, every other variant is just an alias.
    453            # Additionally, any supplied length parameter will be ignored.
    454            #
    455            # https://clickhouse.com/docs/en/sql-reference/data-types/string
    456            if expression.this in self.STRING_TYPE_MAPPING:
    457                return "String"
    458
    459            return super().datatype_sql(expression)
    460
    461        def concat_sql(self, expression: exp.Concat) -> str:
    462            # Clickhouse errors out if we try to cast a NULL value to TEXT
    463            if expression.args.get("safe"):
    464                return self.func(
    465                    "CONCAT",
    466                    *[
    467                        exp.func("if", e.is_(exp.null()), e, exp.cast(e, "text"))
    468                        for e in expression.expressions
    469                    ],
    470                )
    471            return super().concat_sql(expression)
    472
    473        def cte_sql(self, expression: exp.CTE) -> str:
    474            if expression.args.get("scalar"):
    475                this = self.sql(expression, "this")
    476                alias = self.sql(expression, "alias")
    477                return f"{this} AS {alias}"
    478
    479            return super().cte_sql(expression)
    480
    481        def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
    482            return super().after_limit_modifiers(expression) + [
    483                self.seg("SETTINGS ") + self.expressions(expression, key="settings", flat=True)
    484                if expression.args.get("settings")
    485                else "",
    486                self.seg("FORMAT ") + self.sql(expression, "format")
    487                if expression.args.get("format")
    488                else "",
    489            ]
    490
    491        def parameterizedagg_sql(self, expression: exp.Anonymous) -> str:
    492            params = self.expressions(expression, key="params", flat=True)
    493            return self.func(expression.name, *expression.expressions) + f"({params})"
    494
    495        def placeholder_sql(self, expression: exp.Placeholder) -> str:
    496            return f"{{{expression.name}: {self.sql(expression, 'kind')}}}"
    497
    498        def oncluster_sql(self, expression: exp.OnCluster) -> str:
    499            return f"ON CLUSTER {self.sql(expression, 'this')}"
    500
    501        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
    502            kind = self.sql(expression, "kind").upper()
    503            if kind in self.ON_CLUSTER_TARGETS and locations.get(exp.Properties.Location.POST_NAME):
    504                this_name = self.sql(expression.this, "this")
    505                this_properties = " ".join(
    506                    [self.sql(prop) for prop in locations[exp.Properties.Location.POST_NAME]]
    507                )
    508                this_schema = self.schema_columns_sql(expression.this)
    509                return f"{this_name}{self.sep()}{this_properties}{self.sep()}{this_schema}"
    510
    511            return super().createable_sql(expression, locations)

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

     36class ClickHouse(Dialect):
     37    NORMALIZE_FUNCTIONS: bool | str = False
     38    NULL_ORDERING = "nulls_are_last"
     39    STRICT_STRING_CONCAT = True
     40    SUPPORTS_USER_DEFINED_TYPES = False
     41    SAFE_DIVISION = True
     42
     43    ESCAPE_SEQUENCES = {
     44        "\\0": "\0",
     45    }
     46
     47    class Tokenizer(tokens.Tokenizer):
     48        COMMENTS = ["--", "#", "#!", ("/*", "*/")]
     49        IDENTIFIERS = ['"', "`"]
     50        STRING_ESCAPES = ["'", "\\"]
     51        BIT_STRINGS = [("0b", "")]
     52        HEX_STRINGS = [("0x", ""), ("0X", "")]
     53        HEREDOC_STRINGS = ["$"]
     54
     55        KEYWORDS = {
     56            **tokens.Tokenizer.KEYWORDS,
     57            "ATTACH": TokenType.COMMAND,
     58            "DATETIME64": TokenType.DATETIME64,
     59            "DICTIONARY": TokenType.DICTIONARY,
     60            "ENUM": TokenType.ENUM,
     61            "ENUM8": TokenType.ENUM8,
     62            "ENUM16": TokenType.ENUM16,
     63            "FINAL": TokenType.FINAL,
     64            "FIXEDSTRING": TokenType.FIXEDSTRING,
     65            "FLOAT32": TokenType.FLOAT,
     66            "FLOAT64": TokenType.DOUBLE,
     67            "GLOBAL": TokenType.GLOBAL,
     68            "INT256": TokenType.INT256,
     69            "LOWCARDINALITY": TokenType.LOWCARDINALITY,
     70            "MAP": TokenType.MAP,
     71            "NESTED": TokenType.NESTED,
     72            "SAMPLE": TokenType.TABLE_SAMPLE,
     73            "TUPLE": TokenType.STRUCT,
     74            "UINT128": TokenType.UINT128,
     75            "UINT16": TokenType.USMALLINT,
     76            "UINT256": TokenType.UINT256,
     77            "UINT32": TokenType.UINT,
     78            "UINT64": TokenType.UBIGINT,
     79            "UINT8": TokenType.UTINYINT,
     80        }
     81
     82        SINGLE_TOKENS = {
     83            **tokens.Tokenizer.SINGLE_TOKENS,
     84            "$": TokenType.HEREDOC_STRING,
     85        }
     86
     87    class Parser(parser.Parser):
     88        FUNCTIONS = {
     89            **parser.Parser.FUNCTIONS,
     90            "ANY": exp.AnyValue.from_arg_list,
     91            "DATE_ADD": lambda args: exp.DateAdd(
     92                this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0)
     93            ),
     94            "DATEADD": lambda args: exp.DateAdd(
     95                this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0)
     96            ),
     97            "DATE_DIFF": lambda args: exp.DateDiff(
     98                this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0)
     99            ),
    100            "DATEDIFF": lambda args: exp.DateDiff(
    101                this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0)
    102            ),
    103            "MAP": parse_var_map,
    104            "MATCH": exp.RegexpLike.from_arg_list,
    105            "UNIQ": exp.ApproxDistinct.from_arg_list,
    106            "XOR": lambda args: exp.Xor(expressions=args),
    107        }
    108
    109        FUNCTIONS_WITH_ALIASED_ARGS = {*parser.Parser.FUNCTIONS_WITH_ALIASED_ARGS, "TUPLE"}
    110
    111        FUNCTION_PARSERS = {
    112            **parser.Parser.FUNCTION_PARSERS,
    113            "QUANTILE": lambda self: self._parse_quantile(),
    114        }
    115
    116        FUNCTION_PARSERS.pop("MATCH")
    117
    118        NO_PAREN_FUNCTION_PARSERS = parser.Parser.NO_PAREN_FUNCTION_PARSERS.copy()
    119        NO_PAREN_FUNCTION_PARSERS.pop("ANY")
    120
    121        RANGE_PARSERS = {
    122            **parser.Parser.RANGE_PARSERS,
    123            TokenType.GLOBAL: lambda self, this: self._match(TokenType.IN)
    124            and self._parse_in(this, is_global=True),
    125        }
    126
    127        # The PLACEHOLDER entry is popped because 1) it doesn't affect Clickhouse (it corresponds to
    128        # the postgres-specific JSONBContains parser) and 2) it makes parsing the ternary op simpler.
    129        COLUMN_OPERATORS = parser.Parser.COLUMN_OPERATORS.copy()
    130        COLUMN_OPERATORS.pop(TokenType.PLACEHOLDER)
    131
    132        JOIN_KINDS = {
    133            *parser.Parser.JOIN_KINDS,
    134            TokenType.ANY,
    135            TokenType.ASOF,
    136            TokenType.ARRAY,
    137        }
    138
    139        TABLE_ALIAS_TOKENS = parser.Parser.TABLE_ALIAS_TOKENS - {
    140            TokenType.ANY,
    141            TokenType.SETTINGS,
    142            TokenType.FORMAT,
    143            TokenType.ARRAY,
    144        }
    145
    146        LOG_DEFAULTS_TO_LN = True
    147
    148        QUERY_MODIFIER_PARSERS = {
    149            **parser.Parser.QUERY_MODIFIER_PARSERS,
    150            TokenType.SETTINGS: lambda self: (
    151                "settings",
    152                self._advance() or self._parse_csv(self._parse_conjunction),
    153            ),
    154            TokenType.FORMAT: lambda self: ("format", self._advance() or self._parse_id_var()),
    155        }
    156
    157        def _parse_conjunction(self) -> t.Optional[exp.Expression]:
    158            this = super()._parse_conjunction()
    159
    160            if self._match(TokenType.PLACEHOLDER):
    161                return self.expression(
    162                    exp.If,
    163                    this=this,
    164                    true=self._parse_conjunction(),
    165                    false=self._match(TokenType.COLON) and self._parse_conjunction(),
    166                )
    167
    168            return this
    169
    170        def _parse_placeholder(self) -> t.Optional[exp.Expression]:
    171            """
    172            Parse a placeholder expression like SELECT {abc: UInt32} or FROM {table: Identifier}
    173            https://clickhouse.com/docs/en/sql-reference/syntax#defining-and-using-query-parameters
    174            """
    175            if not self._match(TokenType.L_BRACE):
    176                return None
    177
    178            this = self._parse_id_var()
    179            self._match(TokenType.COLON)
    180            kind = self._parse_types(check_func=False, allow_identifiers=False) or (
    181                self._match_text_seq("IDENTIFIER") and "Identifier"
    182            )
    183
    184            if not kind:
    185                self.raise_error("Expecting a placeholder type or 'Identifier' for tables")
    186            elif not self._match(TokenType.R_BRACE):
    187                self.raise_error("Expecting }")
    188
    189            return self.expression(exp.Placeholder, this=this, kind=kind)
    190
    191        def _parse_in(self, this: t.Optional[exp.Expression], is_global: bool = False) -> exp.In:
    192            this = super()._parse_in(this)
    193            this.set("is_global", is_global)
    194            return this
    195
    196        def _parse_table(
    197            self,
    198            schema: bool = False,
    199            joins: bool = False,
    200            alias_tokens: t.Optional[t.Collection[TokenType]] = None,
    201            parse_bracket: bool = False,
    202        ) -> t.Optional[exp.Expression]:
    203            this = super()._parse_table(
    204                schema=schema, joins=joins, alias_tokens=alias_tokens, parse_bracket=parse_bracket
    205            )
    206
    207            if self._match(TokenType.FINAL):
    208                this = self.expression(exp.Final, this=this)
    209
    210            return this
    211
    212        def _parse_position(self, haystack_first: bool = False) -> exp.StrPosition:
    213            return super()._parse_position(haystack_first=True)
    214
    215        # https://clickhouse.com/docs/en/sql-reference/statements/select/with/
    216        def _parse_cte(self) -> exp.CTE:
    217            index = self._index
    218            try:
    219                # WITH <identifier> AS <subquery expression>
    220                return super()._parse_cte()
    221            except ParseError:
    222                # WITH <expression> AS <identifier>
    223                self._retreat(index)
    224
    225                return self.expression(
    226                    exp.CTE,
    227                    this=self._parse_field(),
    228                    alias=self._parse_table_alias(),
    229                    scalar=True,
    230                )
    231
    232        def _parse_join_parts(
    233            self,
    234        ) -> t.Tuple[t.Optional[Token], t.Optional[Token], t.Optional[Token]]:
    235            is_global = self._match(TokenType.GLOBAL) and self._prev
    236            kind_pre = self._match_set(self.JOIN_KINDS, advance=False) and self._prev
    237
    238            if kind_pre:
    239                kind = self._match_set(self.JOIN_KINDS) and self._prev
    240                side = self._match_set(self.JOIN_SIDES) and self._prev
    241                return is_global, side, kind
    242
    243            return (
    244                is_global,
    245                self._match_set(self.JOIN_SIDES) and self._prev,
    246                self._match_set(self.JOIN_KINDS) and self._prev,
    247            )
    248
    249        def _parse_join(
    250            self, skip_join_token: bool = False, parse_bracket: bool = False
    251        ) -> t.Optional[exp.Join]:
    252            join = super()._parse_join(skip_join_token=skip_join_token, parse_bracket=True)
    253
    254            if join:
    255                join.set("global", join.args.pop("method", None))
    256            return join
    257
    258        def _parse_function(
    259            self,
    260            functions: t.Optional[t.Dict[str, t.Callable]] = None,
    261            anonymous: bool = False,
    262            optional_parens: bool = True,
    263        ) -> t.Optional[exp.Expression]:
    264            func = super()._parse_function(
    265                functions=functions, anonymous=anonymous, optional_parens=optional_parens
    266            )
    267
    268            if isinstance(func, exp.Anonymous):
    269                params = self._parse_func_params(func)
    270
    271                if params:
    272                    return self.expression(
    273                        exp.ParameterizedAgg,
    274                        this=func.this,
    275                        expressions=func.expressions,
    276                        params=params,
    277                    )
    278
    279            return func
    280
    281        def _parse_func_params(
    282            self, this: t.Optional[exp.Func] = None
    283        ) -> t.Optional[t.List[exp.Expression]]:
    284            if self._match_pair(TokenType.R_PAREN, TokenType.L_PAREN):
    285                return self._parse_csv(self._parse_lambda)
    286
    287            if self._match(TokenType.L_PAREN):
    288                params = self._parse_csv(self._parse_lambda)
    289                self._match_r_paren(this)
    290                return params
    291
    292            return None
    293
    294        def _parse_quantile(self) -> exp.Quantile:
    295            this = self._parse_lambda()
    296            params = self._parse_func_params()
    297            if params:
    298                return self.expression(exp.Quantile, this=params[0], quantile=this)
    299            return self.expression(exp.Quantile, this=this, quantile=exp.Literal.number(0.5))
    300
    301        def _parse_wrapped_id_vars(self, optional: bool = False) -> t.List[exp.Expression]:
    302            return super()._parse_wrapped_id_vars(optional=True)
    303
    304        def _parse_primary_key(
    305            self, wrapped_optional: bool = False, in_props: bool = False
    306        ) -> exp.PrimaryKeyColumnConstraint | exp.PrimaryKey:
    307            return super()._parse_primary_key(
    308                wrapped_optional=wrapped_optional or in_props, in_props=in_props
    309            )
    310
    311        def _parse_on_property(self) -> t.Optional[exp.Expression]:
    312            index = self._index
    313            if self._match_text_seq("CLUSTER"):
    314                this = self._parse_id_var()
    315                if this:
    316                    return self.expression(exp.OnCluster, this=this)
    317                else:
    318                    self._retreat(index)
    319            return None
    320
    321    class Generator(generator.Generator):
    322        QUERY_HINTS = False
    323        STRUCT_DELIMITER = ("(", ")")
    324        NVL2_SUPPORTED = False
    325        TABLESAMPLE_REQUIRES_PARENS = False
    326
    327        STRING_TYPE_MAPPING = {
    328            exp.DataType.Type.CHAR: "String",
    329            exp.DataType.Type.LONGBLOB: "String",
    330            exp.DataType.Type.LONGTEXT: "String",
    331            exp.DataType.Type.MEDIUMBLOB: "String",
    332            exp.DataType.Type.MEDIUMTEXT: "String",
    333            exp.DataType.Type.TINYBLOB: "String",
    334            exp.DataType.Type.TINYTEXT: "String",
    335            exp.DataType.Type.TEXT: "String",
    336            exp.DataType.Type.VARBINARY: "String",
    337            exp.DataType.Type.VARCHAR: "String",
    338        }
    339
    340        TYPE_MAPPING = {
    341            **generator.Generator.TYPE_MAPPING,
    342            **STRING_TYPE_MAPPING,
    343            exp.DataType.Type.ARRAY: "Array",
    344            exp.DataType.Type.BIGINT: "Int64",
    345            exp.DataType.Type.DATETIME64: "DateTime64",
    346            exp.DataType.Type.DOUBLE: "Float64",
    347            exp.DataType.Type.ENUM: "Enum",
    348            exp.DataType.Type.ENUM8: "Enum8",
    349            exp.DataType.Type.ENUM16: "Enum16",
    350            exp.DataType.Type.FIXEDSTRING: "FixedString",
    351            exp.DataType.Type.FLOAT: "Float32",
    352            exp.DataType.Type.INT: "Int32",
    353            exp.DataType.Type.MEDIUMINT: "Int32",
    354            exp.DataType.Type.INT128: "Int128",
    355            exp.DataType.Type.INT256: "Int256",
    356            exp.DataType.Type.LOWCARDINALITY: "LowCardinality",
    357            exp.DataType.Type.MAP: "Map",
    358            exp.DataType.Type.NESTED: "Nested",
    359            exp.DataType.Type.NULLABLE: "Nullable",
    360            exp.DataType.Type.SMALLINT: "Int16",
    361            exp.DataType.Type.STRUCT: "Tuple",
    362            exp.DataType.Type.TINYINT: "Int8",
    363            exp.DataType.Type.UBIGINT: "UInt64",
    364            exp.DataType.Type.UINT: "UInt32",
    365            exp.DataType.Type.UINT128: "UInt128",
    366            exp.DataType.Type.UINT256: "UInt256",
    367            exp.DataType.Type.USMALLINT: "UInt16",
    368            exp.DataType.Type.UTINYINT: "UInt8",
    369        }
    370
    371        TRANSFORMS = {
    372            **generator.Generator.TRANSFORMS,
    373            exp.Select: transforms.preprocess([transforms.eliminate_qualify]),
    374            exp.AnyValue: rename_func("any"),
    375            exp.ApproxDistinct: rename_func("uniq"),
    376            exp.ArgMax: arg_max_or_min_no_count("argMax"),
    377            exp.ArgMin: arg_max_or_min_no_count("argMin"),
    378            exp.Array: inline_array_sql,
    379            exp.CastToStrType: rename_func("CAST"),
    380            exp.CurrentDate: lambda self, e: self.func("CURRENT_DATE"),
    381            exp.DateAdd: lambda self, e: self.func(
    382                "DATE_ADD", exp.Literal.string(e.text("unit") or "day"), e.expression, e.this
    383            ),
    384            exp.DateDiff: lambda self, e: self.func(
    385                "DATE_DIFF", exp.Literal.string(e.text("unit") or "day"), e.expression, e.this
    386            ),
    387            exp.Final: lambda self, e: f"{self.sql(e, 'this')} FINAL",
    388            exp.IsNan: rename_func("isNaN"),
    389            exp.Map: lambda self, e: _lower_func(var_map_sql(self, e)),
    390            exp.Nullif: rename_func("nullIf"),
    391            exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}",
    392            exp.Pivot: no_pivot_sql,
    393            exp.Quantile: _quantile_sql,
    394            exp.RegexpLike: lambda self, e: f"match({self.format_args(e.this, e.expression)})",
    395            exp.StartsWith: rename_func("startsWith"),
    396            exp.StrPosition: lambda self, e: f"position({self.format_args(e.this, e.args.get('substr'), e.args.get('position'))})",
    397            exp.VarMap: lambda self, e: _lower_func(var_map_sql(self, e)),
    398            exp.Xor: lambda self, e: self.func("xor", e.this, e.expression, *e.expressions),
    399        }
    400
    401        PROPERTIES_LOCATION = {
    402            **generator.Generator.PROPERTIES_LOCATION,
    403            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    404            exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA,
    405            exp.OnCluster: exp.Properties.Location.POST_NAME,
    406        }
    407
    408        JOIN_HINTS = False
    409        TABLE_HINTS = False
    410        EXPLICIT_UNION = True
    411        GROUPINGS_SEP = ""
    412
    413        # there's no list in docs, but it can be found in Clickhouse code
    414        # see `ClickHouse/src/Parsers/ParserCreate*.cpp`
    415        ON_CLUSTER_TARGETS = {
    416            "DATABASE",
    417            "TABLE",
    418            "VIEW",
    419            "DICTIONARY",
    420            "INDEX",
    421            "FUNCTION",
    422            "NAMED COLLECTION",
    423        }
    424
    425        def _any_to_has(
    426            self,
    427            expression: exp.EQ | exp.NEQ,
    428            default: t.Callable[[t.Any], str],
    429            prefix: str = "",
    430        ) -> str:
    431            if isinstance(expression.left, exp.Any):
    432                arr = expression.left
    433                this = expression.right
    434            elif isinstance(expression.right, exp.Any):
    435                arr = expression.right
    436                this = expression.left
    437            else:
    438                return default(expression)
    439            return prefix + self.func("has", arr.this.unnest(), this)
    440
    441        def eq_sql(self, expression: exp.EQ) -> str:
    442            return self._any_to_has(expression, super().eq_sql)
    443
    444        def neq_sql(self, expression: exp.NEQ) -> str:
    445            return self._any_to_has(expression, super().neq_sql, "NOT ")
    446
    447        def regexpilike_sql(self, expression: exp.RegexpILike) -> str:
    448            # Manually add a flag to make the search case-insensitive
    449            regex = self.func("CONCAT", "'(?i)'", expression.expression)
    450            return f"match({self.format_args(expression.this, regex)})"
    451
    452        def datatype_sql(self, expression: exp.DataType) -> str:
    453            # String is the standard ClickHouse type, every other variant is just an alias.
    454            # Additionally, any supplied length parameter will be ignored.
    455            #
    456            # https://clickhouse.com/docs/en/sql-reference/data-types/string
    457            if expression.this in self.STRING_TYPE_MAPPING:
    458                return "String"
    459
    460            return super().datatype_sql(expression)
    461
    462        def concat_sql(self, expression: exp.Concat) -> str:
    463            # Clickhouse errors out if we try to cast a NULL value to TEXT
    464            if expression.args.get("safe"):
    465                return self.func(
    466                    "CONCAT",
    467                    *[
    468                        exp.func("if", e.is_(exp.null()), e, exp.cast(e, "text"))
    469                        for e in expression.expressions
    470                    ],
    471                )
    472            return super().concat_sql(expression)
    473
    474        def cte_sql(self, expression: exp.CTE) -> str:
    475            if expression.args.get("scalar"):
    476                this = self.sql(expression, "this")
    477                alias = self.sql(expression, "alias")
    478                return f"{this} AS {alias}"
    479
    480            return super().cte_sql(expression)
    481
    482        def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
    483            return super().after_limit_modifiers(expression) + [
    484                self.seg("SETTINGS ") + self.expressions(expression, key="settings", flat=True)
    485                if expression.args.get("settings")
    486                else "",
    487                self.seg("FORMAT ") + self.sql(expression, "format")
    488                if expression.args.get("format")
    489                else "",
    490            ]
    491
    492        def parameterizedagg_sql(self, expression: exp.Anonymous) -> str:
    493            params = self.expressions(expression, key="params", flat=True)
    494            return self.func(expression.name, *expression.expressions) + f"({params})"
    495
    496        def placeholder_sql(self, expression: exp.Placeholder) -> str:
    497            return f"{{{expression.name}: {self.sql(expression, 'kind')}}}"
    498
    499        def oncluster_sql(self, expression: exp.OnCluster) -> str:
    500            return f"ON CLUSTER {self.sql(expression, 'this')}"
    501
    502        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
    503            kind = self.sql(expression, "kind").upper()
    504            if kind in self.ON_CLUSTER_TARGETS and locations.get(exp.Properties.Location.POST_NAME):
    505                this_name = self.sql(expression.this, "this")
    506                this_properties = " ".join(
    507                    [self.sql(prop) for prop in locations[exp.Properties.Location.POST_NAME]]
    508                )
    509                this_schema = self.schema_columns_sql(expression.this)
    510                return f"{this_name}{self.sep()}{this_properties}{self.sep()}{this_schema}"
    511
    512            return super().createable_sql(expression, locations)

NORMALIZE_FUNCTIONS: bool | str = False
NULL_ORDERING = 'nulls_are_last'
STRICT_STRING_CONCAT = True
SUPPORTS_USER_DEFINED_TYPES = False
SAFE_DIVISION = True
ESCAPE_SEQUENCES = {'\\0': '\x00'}
tokenizer_class = <class 'ClickHouse.Tokenizer'>
parser_class = <class 'ClickHouse.Parser'>
generator_class = <class 'ClickHouse.Generator'>
TIME_TRIE: Dict = {}
FORMAT_TRIE: Dict = {}
INVERSE_TIME_MAPPING: Dict[str, str] = {}
INVERSE_TIME_TRIE: Dict = {}
INVERSE_ESCAPE_SEQUENCES: Dict[str, str] = {'\x00': '\\0'}
QUOTE_START = "'"
QUOTE_END = "'"
IDENTIFIER_START = '"'
IDENTIFIER_END = '"'
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.dialects.dialect.Dialect
  Dialect
  INDEX_OFFSET
  UNNEST_COLUMN_ONLY
  ALIAS_POST_TABLESAMPLE
  NORMALIZATION_STRATEGY
  IDENTIFIERS_CAN_START_WITH_DIGIT
  DPIPE_IS_STRING_CONCAT
  SUPPORTS_SEMI_ANTI_JOIN
  LOG_BASE_FIRST
  TYPED_DIVISION
  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

    47    class Tokenizer(tokens.Tokenizer):
    48        COMMENTS = ["--", "#", "#!", ("/*", "*/")]
    49        IDENTIFIERS = ['"', "`"]
    50        STRING_ESCAPES = ["'", "\\"]
    51        BIT_STRINGS = [("0b", "")]
    52        HEX_STRINGS = [("0x", ""), ("0X", "")]
    53        HEREDOC_STRINGS = ["$"]
    54
    55        KEYWORDS = {
    56            **tokens.Tokenizer.KEYWORDS,
    57            "ATTACH": TokenType.COMMAND,
    58            "DATETIME64": TokenType.DATETIME64,
    59            "DICTIONARY": TokenType.DICTIONARY,
    60            "ENUM": TokenType.ENUM,
    61            "ENUM8": TokenType.ENUM8,
    62            "ENUM16": TokenType.ENUM16,
    63            "FINAL": TokenType.FINAL,
    64            "FIXEDSTRING": TokenType.FIXEDSTRING,
    65            "FLOAT32": TokenType.FLOAT,
    66            "FLOAT64": TokenType.DOUBLE,
    67            "GLOBAL": TokenType.GLOBAL,
    68            "INT256": TokenType.INT256,
    69            "LOWCARDINALITY": TokenType.LOWCARDINALITY,
    70            "MAP": TokenType.MAP,
    71            "NESTED": TokenType.NESTED,
    72            "SAMPLE": TokenType.TABLE_SAMPLE,
    73            "TUPLE": TokenType.STRUCT,
    74            "UINT128": TokenType.UINT128,
    75            "UINT16": TokenType.USMALLINT,
    76            "UINT256": TokenType.UINT256,
    77            "UINT32": TokenType.UINT,
    78            "UINT64": TokenType.UBIGINT,
    79            "UINT8": TokenType.UTINYINT,
    80        }
    81
    82        SINGLE_TOKENS = {
    83            **tokens.Tokenizer.SINGLE_TOKENS,
    84            "$": TokenType.HEREDOC_STRING,
    85        }

COMMENTS = ['--', '#', '#!', ('/*', '*/')]
IDENTIFIERS = ['"', '`']
STRING_ESCAPES = ["'", '\\']
BIT_STRINGS = [('0b', '')]
HEX_STRINGS = [('0x', ''), ('0X', '')]
HEREDOC_STRINGS = ['$']
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.COLON_EQ: 'COLON_EQ'>, '<=>': <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'>, '??': <TokenType.DQMARK: 'DQMARK'>, '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'>, 'CONNECT BY': <TokenType.CONNECT_BY: 'CONNECT_BY'>, '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'>, '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'>, 'KILL': <TokenType.KILL: 'KILL'>, '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'>, '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'>, 'START WITH': <TokenType.START_WITH: 'START_WITH'>, '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'>, 'UNKNOWN': <TokenType.UNKNOWN: 'UNKNOWN'>, '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'>, 'MEDIUMINT': <TokenType.MEDIUMINT: 'MEDIUMINT'>, 'INT1': <TokenType.TINYINT: 'TINYINT'>, 'TINYINT': <TokenType.TINYINT: 'TINYINT'>, 'INT16': <TokenType.SMALLINT: 'SMALLINT'>, 'SHORT': <TokenType.SMALLINT: 'SMALLINT'>, 'SMALLINT': <TokenType.SMALLINT: 'SMALLINT'>, 'INT128': <TokenType.INT128: 'INT128'>, 'HUGEINT': <TokenType.INT128: 'INT128'>, 'INT2': <TokenType.SMALLINT: 'SMALLINT'>, 'INTEGER': <TokenType.INT: 'INT'>, 'INT': <TokenType.INT: 'INT'>, 'INT4': <TokenType.INT: 'INT'>, 'INT32': <TokenType.INT: 'INT'>, 'INT64': <TokenType.BIGINT: 'BIGINT'>, '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'>, 'LONGTEXT': <TokenType.LONGTEXT: 'LONGTEXT'>, 'MEDIUMTEXT': <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, 'TINYTEXT': <TokenType.TINYTEXT: 'TINYTEXT'>, 'CLOB': <TokenType.TEXT: 'TEXT'>, 'LONGVARCHAR': <TokenType.TEXT: 'TEXT'>, 'BINARY': <TokenType.BINARY: 'BINARY'>, 'BLOB': <TokenType.VARBINARY: 'VARBINARY'>, 'LONGBLOB': <TokenType.LONGBLOB: 'LONGBLOB'>, 'MEDIUMBLOB': <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, 'TINYBLOB': <TokenType.TINYBLOB: 'TINYBLOB'>, 'BYTEA': <TokenType.VARBINARY: 'VARBINARY'>, 'VARBINARY': <TokenType.VARBINARY: 'VARBINARY'>, 'TIME': <TokenType.TIME: 'TIME'>, 'TIMETZ': <TokenType.TIMETZ: 'TIMETZ'>, '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'>, 'FOR VERSION': <TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>, 'FOR TIMESTAMP': <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>, 'ATTACH': <TokenType.COMMAND: 'COMMAND'>, 'DATETIME64': <TokenType.DATETIME64: 'DATETIME64'>, 'DICTIONARY': <TokenType.DICTIONARY: 'DICTIONARY'>, 'ENUM': <TokenType.ENUM: 'ENUM'>, 'ENUM8': <TokenType.ENUM8: 'ENUM8'>, 'ENUM16': <TokenType.ENUM16: 'ENUM16'>, 'FINAL': <TokenType.FINAL: 'FINAL'>, 'FIXEDSTRING': <TokenType.FIXEDSTRING: 'FIXEDSTRING'>, 'FLOAT32': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT64': <TokenType.DOUBLE: 'DOUBLE'>, 'GLOBAL': <TokenType.GLOBAL: 'GLOBAL'>, 'INT256': <TokenType.INT256: 'INT256'>, 'LOWCARDINALITY': <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>, 'NESTED': <TokenType.NESTED: 'NESTED'>, 'SAMPLE': <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>, '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'>}
SINGLE_TOKENS = {'(': <TokenType.L_PAREN: 'L_PAREN'>, ')': <TokenType.R_PAREN: 'R_PAREN'>, '[': <TokenType.L_BRACKET: 'L_BRACKET'>, ']': <TokenType.R_BRACKET: 'R_BRACKET'>, '{': <TokenType.L_BRACE: 'L_BRACE'>, '}': <TokenType.R_BRACE: 'R_BRACE'>, '&': <TokenType.AMP: 'AMP'>, '^': <TokenType.CARET: 'CARET'>, ':': <TokenType.COLON: 'COLON'>, ',': <TokenType.COMMA: 'COMMA'>, '.': <TokenType.DOT: 'DOT'>, '-': <TokenType.DASH: 'DASH'>, '=': <TokenType.EQ: 'EQ'>, '>': <TokenType.GT: 'GT'>, '<': <TokenType.LT: 'LT'>, '%': <TokenType.MOD: 'MOD'>, '!': <TokenType.NOT: 'NOT'>, '|': <TokenType.PIPE: 'PIPE'>, '+': <TokenType.PLUS: 'PLUS'>, ';': <TokenType.SEMICOLON: 'SEMICOLON'>, '/': <TokenType.SLASH: 'SLASH'>, '\\': <TokenType.BACKSLASH: 'BACKSLASH'>, '*': <TokenType.STAR: 'STAR'>, '~': <TokenType.TILDA: 'TILDA'>, '?': <TokenType.PLACEHOLDER: 'PLACEHOLDER'>, '@': <TokenType.PARAMETER: 'PARAMETER'>, "'": <TokenType.QUOTE: 'QUOTE'>, '`': <TokenType.IDENTIFIER: 'IDENTIFIER'>, '"': <TokenType.IDENTIFIER: 'IDENTIFIER'>, '#': <TokenType.HASH: 'HASH'>, '$': <TokenType.HEREDOC_STRING: 'HEREDOC_STRING'>}

##### Inherited Members

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

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

     87    class Parser(parser.Parser):
     88        FUNCTIONS = {
     89            **parser.Parser.FUNCTIONS,
     90            "ANY": exp.AnyValue.from_arg_list,
     91            "DATE_ADD": lambda args: exp.DateAdd(
     92                this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0)
     93            ),
     94            "DATEADD": lambda args: exp.DateAdd(
     95                this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0)
     96            ),
     97            "DATE_DIFF": lambda args: exp.DateDiff(
     98                this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0)
     99            ),
    100            "DATEDIFF": lambda args: exp.DateDiff(
    101                this=seq_get(args, 2), expression=seq_get(args, 1), unit=seq_get(args, 0)
    102            ),
    103            "MAP": parse_var_map,
    104            "MATCH": exp.RegexpLike.from_arg_list,
    105            "UNIQ": exp.ApproxDistinct.from_arg_list,
    106            "XOR": lambda args: exp.Xor(expressions=args),
    107        }
    108
    109        FUNCTIONS_WITH_ALIASED_ARGS = {*parser.Parser.FUNCTIONS_WITH_ALIASED_ARGS, "TUPLE"}
    110
    111        FUNCTION_PARSERS = {
    112            **parser.Parser.FUNCTION_PARSERS,
    113            "QUANTILE": lambda self: self._parse_quantile(),
    114        }
    115
    116        FUNCTION_PARSERS.pop("MATCH")
    117
    118        NO_PAREN_FUNCTION_PARSERS = parser.Parser.NO_PAREN_FUNCTION_PARSERS.copy()
    119        NO_PAREN_FUNCTION_PARSERS.pop("ANY")
    120
    121        RANGE_PARSERS = {
    122            **parser.Parser.RANGE_PARSERS,
    123            TokenType.GLOBAL: lambda self, this: self._match(TokenType.IN)
    124            and self._parse_in(this, is_global=True),
    125        }
    126
    127        # The PLACEHOLDER entry is popped because 1) it doesn't affect Clickhouse (it corresponds to
    128        # the postgres-specific JSONBContains parser) and 2) it makes parsing the ternary op simpler.
    129        COLUMN_OPERATORS = parser.Parser.COLUMN_OPERATORS.copy()
    130        COLUMN_OPERATORS.pop(TokenType.PLACEHOLDER)
    131
    132        JOIN_KINDS = {
    133            *parser.Parser.JOIN_KINDS,
    134            TokenType.ANY,
    135            TokenType.ASOF,
    136            TokenType.ARRAY,
    137        }
    138
    139        TABLE_ALIAS_TOKENS = parser.Parser.TABLE_ALIAS_TOKENS - {
    140            TokenType.ANY,
    141            TokenType.SETTINGS,
    142            TokenType.FORMAT,
    143            TokenType.ARRAY,
    144        }
    145
    146        LOG_DEFAULTS_TO_LN = True
    147
    148        QUERY_MODIFIER_PARSERS = {
    149            **parser.Parser.QUERY_MODIFIER_PARSERS,
    150            TokenType.SETTINGS: lambda self: (
    151                "settings",
    152                self._advance() or self._parse_csv(self._parse_conjunction),
    153            ),
    154            TokenType.FORMAT: lambda self: ("format", self._advance() or self._parse_id_var()),
    155        }
    156
    157        def _parse_conjunction(self) -> t.Optional[exp.Expression]:
    158            this = super()._parse_conjunction()
    159
    160            if self._match(TokenType.PLACEHOLDER):
    161                return self.expression(
    162                    exp.If,
    163                    this=this,
    164                    true=self._parse_conjunction(),
    165                    false=self._match(TokenType.COLON) and self._parse_conjunction(),
    166                )
    167
    168            return this
    169
    170        def _parse_placeholder(self) -> t.Optional[exp.Expression]:
    171            """
    172            Parse a placeholder expression like SELECT {abc: UInt32} or FROM {table: Identifier}
    173            https://clickhouse.com/docs/en/sql-reference/syntax#defining-and-using-query-parameters
    174            """
    175            if not self._match(TokenType.L_BRACE):
    176                return None
    177
    178            this = self._parse_id_var()
    179            self._match(TokenType.COLON)
    180            kind = self._parse_types(check_func=False, allow_identifiers=False) or (
    181                self._match_text_seq("IDENTIFIER") and "Identifier"
    182            )
    183
    184            if not kind:
    185                self.raise_error("Expecting a placeholder type or 'Identifier' for tables")
    186            elif not self._match(TokenType.R_BRACE):
    187                self.raise_error("Expecting }")
    188
    189            return self.expression(exp.Placeholder, this=this, kind=kind)
    190
    191        def _parse_in(self, this: t.Optional[exp.Expression], is_global: bool = False) -> exp.In:
    192            this = super()._parse_in(this)
    193            this.set("is_global", is_global)
    194            return this
    195
    196        def _parse_table(
    197            self,
    198            schema: bool = False,
    199            joins: bool = False,
    200            alias_tokens: t.Optional[t.Collection[TokenType]] = None,
    201            parse_bracket: bool = False,
    202        ) -> t.Optional[exp.Expression]:
    203            this = super()._parse_table(
    204                schema=schema, joins=joins, alias_tokens=alias_tokens, parse_bracket=parse_bracket
    205            )
    206
    207            if self._match(TokenType.FINAL):
    208                this = self.expression(exp.Final, this=this)
    209
    210            return this
    211
    212        def _parse_position(self, haystack_first: bool = False) -> exp.StrPosition:
    213            return super()._parse_position(haystack_first=True)
    214
    215        # https://clickhouse.com/docs/en/sql-reference/statements/select/with/
    216        def _parse_cte(self) -> exp.CTE:
    217            index = self._index
    218            try:
    219                # WITH <identifier> AS <subquery expression>
    220                return super()._parse_cte()
    221            except ParseError:
    222                # WITH <expression> AS <identifier>
    223                self._retreat(index)
    224
    225                return self.expression(
    226                    exp.CTE,
    227                    this=self._parse_field(),
    228                    alias=self._parse_table_alias(),
    229                    scalar=True,
    230                )
    231
    232        def _parse_join_parts(
    233            self,
    234        ) -> t.Tuple[t.Optional[Token], t.Optional[Token], t.Optional[Token]]:
    235            is_global = self._match(TokenType.GLOBAL) and self._prev
    236            kind_pre = self._match_set(self.JOIN_KINDS, advance=False) and self._prev
    237
    238            if kind_pre:
    239                kind = self._match_set(self.JOIN_KINDS) and self._prev
    240                side = self._match_set(self.JOIN_SIDES) and self._prev
    241                return is_global, side, kind
    242
    243            return (
    244                is_global,
    245                self._match_set(self.JOIN_SIDES) and self._prev,
    246                self._match_set(self.JOIN_KINDS) and self._prev,
    247            )
    248
    249        def _parse_join(
    250            self, skip_join_token: bool = False, parse_bracket: bool = False
    251        ) -> t.Optional[exp.Join]:
    252            join = super()._parse_join(skip_join_token=skip_join_token, parse_bracket=True)
    253
    254            if join:
    255                join.set("global", join.args.pop("method", None))
    256            return join
    257
    258        def _parse_function(
    259            self,
    260            functions: t.Optional[t.Dict[str, t.Callable]] = None,
    261            anonymous: bool = False,
    262            optional_parens: bool = True,
    263        ) -> t.Optional[exp.Expression]:
    264            func = super()._parse_function(
    265                functions=functions, anonymous=anonymous, optional_parens=optional_parens
    266            )
    267
    268            if isinstance(func, exp.Anonymous):
    269                params = self._parse_func_params(func)
    270
    271                if params:
    272                    return self.expression(
    273                        exp.ParameterizedAgg,
    274                        this=func.this,
    275                        expressions=func.expressions,
    276                        params=params,
    277                    )
    278
    279            return func
    280
    281        def _parse_func_params(
    282            self, this: t.Optional[exp.Func] = None
    283        ) -> t.Optional[t.List[exp.Expression]]:
    284            if self._match_pair(TokenType.R_PAREN, TokenType.L_PAREN):
    285                return self._parse_csv(self._parse_lambda)
    286
    287            if self._match(TokenType.L_PAREN):
    288                params = self._parse_csv(self._parse_lambda)
    289                self._match_r_paren(this)
    290                return params
    291
    292            return None
    293
    294        def _parse_quantile(self) -> exp.Quantile:
    295            this = self._parse_lambda()
    296            params = self._parse_func_params()
    297            if params:
    298                return self.expression(exp.Quantile, this=params[0], quantile=this)
    299            return self.expression(exp.Quantile, this=this, quantile=exp.Literal.number(0.5))
    300
    301        def _parse_wrapped_id_vars(self, optional: bool = False) -> t.List[exp.Expression]:
    302            return super()._parse_wrapped_id_vars(optional=True)
    303
    304        def _parse_primary_key(
    305            self, wrapped_optional: bool = False, in_props: bool = False
    306        ) -> exp.PrimaryKeyColumnConstraint | exp.PrimaryKey:
    307            return super()._parse_primary_key(
    308                wrapped_optional=wrapped_optional or in_props, in_props=in_props
    309            )
    310
    311        def _parse_on_property(self) -> t.Optional[exp.Expression]:
    312            index = self._index
    313            if self._match_text_seq("CLUSTER"):
    314                this = self._parse_id_var()
    315                if this:
    316                    return self.expression(exp.OnCluster, this=this)
    317                else:
    318                    self._retreat(index)
    319            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'>>, 'APPROX_TOP_K': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxTopK'>>, 'ARG_MAX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMax'>>, 'ARGMAX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMax'>>, 'MAX_BY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMax'>>, 'ARG_MIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMin'>>, 'ARGMIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMin'>>, 'MIN_BY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMin'>>, '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_CAT': <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'>>, 'ARRAY_UNIQUE_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayUniqueAgg'>>, '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'>>, 'CHR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Chr'>>, 'CHAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Chr'>>, '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'>>, 'COLLATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Collate'>>, 'CONCAT': <function parse_concat>, 'CONCAT_WS': <function parse_concat_ws>, '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': <function ClickHouse.Parser.<lambda>>, 'DATEDIFF': <function ClickHouse.Parser.<lambda>>, 'DATE_DIFF': <function ClickHouse.Parser.<lambda>>, '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'>>, 'EXPLODE_OUTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ExplodeOuter'>>, 'EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Extract'>>, 'FIRST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.First'>>, 'FLATTEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Flatten'>>, '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_INF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.IsInf'>>, 'ISINF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.IsInf'>>, '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'>>, 'J_S_O_N_ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONArray'>>, 'J_S_O_N_ARRAY_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONArrayAgg'>>, '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'>>, 'J_S_O_N_TABLE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONTable'>>, 'LAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Last'>>, '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': <function parse_logarithm>, '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'>>, 'NULLIF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Nullif'>>, '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'>>, 'PARSE_JSON': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ParseJSON'>>, 'JSON_PARSE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ParseJSON'>>, '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'>>, 'POSEXPLODE_OUTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PosexplodeOuter'>>, 'POWER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, 'POW': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, 'PREDICT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Predict'>>, '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_DIVIDE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SafeDivide'>>, '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_MAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToMap'>>, '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'>>, 'STUFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Stuff'>>, 'INSERT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Stuff'>>, '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': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Timestamp'>>, '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'>>, 'TO_DAYS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToDays'>>, '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_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsDiff'>>, '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'>>, 'DATEADD': <function ClickHouse.Parser.<lambda>>, '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>>, 'CONVERT': <function Parser.<lambda>>, 'DECODE': <function Parser.<lambda>>, 'EXTRACT': <function Parser.<lambda>>, 'JSON_OBJECT': <function Parser.<lambda>>, 'JSON_TABLE': <function Parser.<lambda>>, 'OPENJSON': <function Parser.<lambda>>, 'POSITION': <function Parser.<lambda>>, 'PREDICT': <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 = {'CASE': <function Parser.<lambda>>, 'IF': <function Parser.<lambda>>, 'NEXT': <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.FOR: 'FOR'>: <function Parser.<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.ASOF: 'ASOF'>, <TokenType.INNER: 'INNER'>, <TokenType.CROSS: 'CROSS'>, <TokenType.ANTI: 'ANTI'>, <TokenType.ARRAY: 'ARRAY'>, <TokenType.SEMI: 'SEMI'>, <TokenType.OUTER: 'OUTER'>, <TokenType.ANY: 'ANY'>}
TABLE_ALIAS_TOKENS = {<TokenType.VARCHAR: 'VARCHAR'>, <TokenType.OVERLAPS: 'OVERLAPS'>, <TokenType.MERGE: 'MERGE'>, <TokenType.TEXT: 'TEXT'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.DESC: 'DESC'>, <TokenType.FILTER: 'FILTER'>, <TokenType.END: 'END'>, <TokenType.ASC: 'ASC'>, <TokenType.SOME: 'SOME'>, <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, <TokenType.ENUM16: 'ENUM16'>, <TokenType.TABLE: 'TABLE'>, <TokenType.FLOAT: 'FLOAT'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.ENUM8: 'ENUM8'>, <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <TokenType.YEAR: 'YEAR'>, <TokenType.ENUM: 'ENUM'>, <TokenType.HSTORE: 'HSTORE'>, <TokenType.DIV: 'DIV'>, <TokenType.FALSE: 'FALSE'>, <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, <TokenType.IPADDRESS: 'IPADDRESS'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.KEEP: 'KEEP'>, <TokenType.KILL: 'KILL'>, <TokenType.TINYBLOB: 'TINYBLOB'>, <TokenType.NUMRANGE: 'NUMRANGE'>, <TokenType.UNIQUE: 'UNIQUE'>, <TokenType.REPLACE: 'REPLACE'>, <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, <TokenType.USE: 'USE'>, <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, <TokenType.JSONB: 'JSONB'>, <TokenType.TOP: 'TOP'>, <TokenType.RECURSIVE: 'RECURSIVE'>, <TokenType.INT128: 'INT128'>, <TokenType.OPERATOR: 'OPERATOR'>, <TokenType.OVERWRITE: 'OVERWRITE'>, <TokenType.SMALLSERIAL: 'SMALLSERIAL'>, <TokenType.UUID: 'UUID'>, <TokenType.SET: 'SET'>, <TokenType.USERDEFINED: 'USERDEFINED'>, <TokenType.VARBINARY: 'VARBINARY'>, <TokenType.SMALLMONEY: 'SMALLMONEY'>, <TokenType.BIGSERIAL: 'BIGSERIAL'>, <TokenType.CONSTRAINT: 'CONSTRAINT'>, <TokenType.DICTIONARY: 'DICTIONARY'>, <TokenType.INT: 'INT'>, <TokenType.INDEX: 'INDEX'>, <TokenType.BIGINT: 'BIGINT'>, <TokenType.NCHAR: 'NCHAR'>, <TokenType.ROW: 'ROW'>, <TokenType.DEFAULT: 'DEFAULT'>, <TokenType.REFERENCES: 'REFERENCES'>, <TokenType.UNPIVOT: 'UNPIVOT'>, <TokenType.LOAD: 'LOAD'>, <TokenType.NESTED: 'NESTED'>, <TokenType.NULLABLE: 'NULLABLE'>, <TokenType.BEGIN: 'BEGIN'>, <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, <TokenType.UNKNOWN: 'UNKNOWN'>, <TokenType.ESCAPE: 'ESCAPE'>, <TokenType.FUNCTION: 'FUNCTION'>, <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.OBJECT_IDENTIFIER: 'OBJECT_IDENTIFIER'>, <TokenType.INT8RANGE: 'INT8RANGE'>, <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>, <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>, <TokenType.UMEDIUMINT: 'UMEDIUMINT'>, <TokenType.TIME: 'TIME'>, <TokenType.TINYINT: 'TINYINT'>, <TokenType.PERCENT: 'PERCENT'>, <TokenType.STRUCT: 'STRUCT'>, <TokenType.BOOLEAN: 'BOOLEAN'>, <TokenType.CHAR: 'CHAR'>, <TokenType.HLLSKETCH: 'HLLSKETCH'>, <TokenType.VARIANT: 'VARIANT'>, <TokenType.UINT128: 'UINT128'>, <TokenType.LONGTEXT: 'LONGTEXT'>, <TokenType.JSON: 'JSON'>, <TokenType.DECIMAL: 'DECIMAL'>, <TokenType.INTERVAL: 'INTERVAL'>, <TokenType.INT256: 'INT256'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.ALL: 'ALL'>, <TokenType.DATERANGE: 'DATERANGE'>, <TokenType.DESCRIBE: 'DESCRIBE'>, <TokenType.PIVOT: 'PIVOT'>, <TokenType.OBJECT: 'OBJECT'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <TokenType.MONEY: 'MONEY'>, <TokenType.PARTITION: 'PARTITION'>, <TokenType.ROWS: 'ROWS'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.DATE: 'DATE'>, <TokenType.SERIAL: 'SERIAL'>, <TokenType.MAP: 'MAP'>, <TokenType.NEXT: 'NEXT'>, <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, <TokenType.COMMIT: 'COMMIT'>, <TokenType.BINARY: 'BINARY'>, <TokenType.IPPREFIX: 'IPPREFIX'>, <TokenType.INET: 'INET'>, <TokenType.IS: 'IS'>, <TokenType.MODEL: 'MODEL'>, <TokenType.TIMESTAMP_NS: 'TIMESTAMP_NS'>, <TokenType.UTINYINT: 'UTINYINT'>, <TokenType.SMALLINT: 'SMALLINT'>, <TokenType.UDECIMAL: 'UDECIMAL'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, <TokenType.DOUBLE: 'DOUBLE'>, <TokenType.FIXEDSTRING: 'FIXEDSTRING'>, <TokenType.SHOW: 'SHOW'>, <TokenType.TEMPORARY: 'TEMPORARY'>, <TokenType.NVARCHAR: 'NVARCHAR'>, <TokenType.COMMENT: 'COMMENT'>, <TokenType.XML: 'XML'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.DATETIME: 'DATETIME'>, <TokenType.IMAGE: 'IMAGE'>, <TokenType.TIMETZ: 'TIMETZ'>, <TokenType.LONGBLOB: 'LONGBLOB'>, <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, <TokenType.ORDINALITY: 'ORDINALITY'>, <TokenType.REFRESH: 'REFRESH'>, <TokenType.TSTZRANGE: 'TSTZRANGE'>, <TokenType.COLUMN: 'COLUMN'>, <TokenType.USMALLINT: 'USMALLINT'>, <TokenType.VAR: 'VAR'>, <TokenType.NULL: 'NULL'>, <TokenType.CASE: 'CASE'>, <TokenType.PROCEDURE: 'PROCEDURE'>, <TokenType.UINT: 'UINT'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.TSRANGE: 'TSRANGE'>, <TokenType.TINYTEXT: 'TINYTEXT'>, <TokenType.DELETE: 'DELETE'>, <TokenType.MEDIUMINT: 'MEDIUMINT'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.TIMESTAMP_S: 'TIMESTAMP_S'>, <TokenType.GEOMETRY: 'GEOMETRY'>, <TokenType.RANGE: 'RANGE'>, <TokenType.TIMESTAMP: 'TIMESTAMP'>, <TokenType.CACHE: 'CACHE'>, <TokenType.VIEW: 'VIEW'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.VOLATILE: 'VOLATILE'>, <TokenType.ROWVERSION: 'ROWVERSION'>, <TokenType.TIMESTAMP_MS: 'TIMESTAMP_MS'>, <TokenType.BIT: 'BIT'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, <TokenType.FIRST: 'FIRST'>, <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, <TokenType.SUPER: 'SUPER'>, <TokenType.UBIGINT: 'UBIGINT'>, <TokenType.TRUE: 'TRUE'>, <TokenType.PRAGMA: 'PRAGMA'>, <TokenType.DATETIME64: 'DATETIME64'>, <TokenType.UINT256: 'UINT256'>, <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, <TokenType.INT4RANGE: 'INT4RANGE'>}
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.CONNECT_BY: 'CONNECT_BY'>: <function Parser.<lambda>>, <TokenType.START_WITH: 'START_WITH'>: <function Parser.<lambda>>, <TokenType.SETTINGS: 'SETTINGS'>: <function ClickHouse.Parser.<lambda>>, <TokenType.FORMAT: 'FORMAT'>: <function ClickHouse.Parser.<lambda>>}
SHOW_TRIE: Dict = {}
SET_TRIE: Dict = {'GLOBAL': {0: True}, 'LOCAL': {0: True}, 'SESSION': {0: True}, 'TRANSACTION': {0: True}}

##### Inherited Members

sqlglot.parser.Parser
  Parser
  NO_PAREN_FUNCTIONS
  STRUCT_TYPE_TOKENS
  NESTED_TYPE_TOKENS
  ENUM_TYPE_TOKENS
  TYPE_TOKENS
  SIGNED_TO_UNSIGNED_TYPE_TOKEN
  SUBQUERY_PREDICATES
  RESERVED_TOKENS
  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
  EXPONENT
  TIMES
  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
  INVALID_FUNC_NAME_TOKENS
  SET_PARSERS
  SHOW_PARSERS
  TYPE_LITERAL_PARSERS
  MODIFIABLES
  DDL_SELECT_TOKENS
  PRE_VOLATILE_TOKENS
  TRANSACTION_KIND
  TRANSACTION_CHARACTERISTICS
  INSERT_ALTERNATIVES
  CLONE_KEYWORDS
  CLONE_KINDS
  OPCLASS_FOLLOW_KEYWORDS
  OPTYPE_FOLLOW_TOKENS
  TABLE_INDEX_HINT_TOKENS
  WINDOW_ALIAS_TOKENS
  WINDOW_BEFORE_PAREN_TOKENS
  WINDOW_SIDES
  FETCH_TOKENS
  ADD_CONSTRAINT_TOKENS
  DISTINCT_TOKENS
  NULL_TOKENS
  UNNEST_OFFSET_ALIAS_TOKENS
  STRICT_CAST
  CONCAT_NULL_OUTPUTS_STRING
  PREFIXED_PIVOT_COLUMNS
  IDENTIFY_PIVOT_STRINGS
  ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN
  TABLESAMPLE_CSV
  SET_REQUIRES_ASSIGNMENT_DELIMITER
  TRIM_PATTERN_FIRST
  error_level
  error_message_context
  max_errors
  dialect
  reset
  parse
  parse_into
  check_errors
  raise_error
  expression
  validate_expression
  errors
  sql

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

    321    class Generator(generator.Generator):
    322        QUERY_HINTS = False
    323        STRUCT_DELIMITER = ("(", ")")
    324        NVL2_SUPPORTED = False
    325        TABLESAMPLE_REQUIRES_PARENS = False
    326
    327        STRING_TYPE_MAPPING = {
    328            exp.DataType.Type.CHAR: "String",
    329            exp.DataType.Type.LONGBLOB: "String",
    330            exp.DataType.Type.LONGTEXT: "String",
    331            exp.DataType.Type.MEDIUMBLOB: "String",
    332            exp.DataType.Type.MEDIUMTEXT: "String",
    333            exp.DataType.Type.TINYBLOB: "String",
    334            exp.DataType.Type.TINYTEXT: "String",
    335            exp.DataType.Type.TEXT: "String",
    336            exp.DataType.Type.VARBINARY: "String",
    337            exp.DataType.Type.VARCHAR: "String",
    338        }
    339
    340        TYPE_MAPPING = {
    341            **generator.Generator.TYPE_MAPPING,
    342            **STRING_TYPE_MAPPING,
    343            exp.DataType.Type.ARRAY: "Array",
    344            exp.DataType.Type.BIGINT: "Int64",
    345            exp.DataType.Type.DATETIME64: "DateTime64",
    346            exp.DataType.Type.DOUBLE: "Float64",
    347            exp.DataType.Type.ENUM: "Enum",
    348            exp.DataType.Type.ENUM8: "Enum8",
    349            exp.DataType.Type.ENUM16: "Enum16",
    350            exp.DataType.Type.FIXEDSTRING: "FixedString",
    351            exp.DataType.Type.FLOAT: "Float32",
    352            exp.DataType.Type.INT: "Int32",
    353            exp.DataType.Type.MEDIUMINT: "Int32",
    354            exp.DataType.Type.INT128: "Int128",
    355            exp.DataType.Type.INT256: "Int256",
    356            exp.DataType.Type.LOWCARDINALITY: "LowCardinality",
    357            exp.DataType.Type.MAP: "Map",
    358            exp.DataType.Type.NESTED: "Nested",
    359            exp.DataType.Type.NULLABLE: "Nullable",
    360            exp.DataType.Type.SMALLINT: "Int16",
    361            exp.DataType.Type.STRUCT: "Tuple",
    362            exp.DataType.Type.TINYINT: "Int8",
    363            exp.DataType.Type.UBIGINT: "UInt64",
    364            exp.DataType.Type.UINT: "UInt32",
    365            exp.DataType.Type.UINT128: "UInt128",
    366            exp.DataType.Type.UINT256: "UInt256",
    367            exp.DataType.Type.USMALLINT: "UInt16",
    368            exp.DataType.Type.UTINYINT: "UInt8",
    369        }
    370
    371        TRANSFORMS = {
    372            **generator.Generator.TRANSFORMS,
    373            exp.Select: transforms.preprocess([transforms.eliminate_qualify]),
    374            exp.AnyValue: rename_func("any"),
    375            exp.ApproxDistinct: rename_func("uniq"),
    376            exp.ArgMax: arg_max_or_min_no_count("argMax"),
    377            exp.ArgMin: arg_max_or_min_no_count("argMin"),
    378            exp.Array: inline_array_sql,
    379            exp.CastToStrType: rename_func("CAST"),
    380            exp.CurrentDate: lambda self, e: self.func("CURRENT_DATE"),
    381            exp.DateAdd: lambda self, e: self.func(
    382                "DATE_ADD", exp.Literal.string(e.text("unit") or "day"), e.expression, e.this
    383            ),
    384            exp.DateDiff: lambda self, e: self.func(
    385                "DATE_DIFF", exp.Literal.string(e.text("unit") or "day"), e.expression, e.this
    386            ),
    387            exp.Final: lambda self, e: f"{self.sql(e, 'this')} FINAL",
    388            exp.IsNan: rename_func("isNaN"),
    389            exp.Map: lambda self, e: _lower_func(var_map_sql(self, e)),
    390            exp.Nullif: rename_func("nullIf"),
    391            exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}",
    392            exp.Pivot: no_pivot_sql,
    393            exp.Quantile: _quantile_sql,
    394            exp.RegexpLike: lambda self, e: f"match({self.format_args(e.this, e.expression)})",
    395            exp.StartsWith: rename_func("startsWith"),
    396            exp.StrPosition: lambda self, e: f"position({self.format_args(e.this, e.args.get('substr'), e.args.get('position'))})",
    397            exp.VarMap: lambda self, e: _lower_func(var_map_sql(self, e)),
    398            exp.Xor: lambda self, e: self.func("xor", e.this, e.expression, *e.expressions),
    399        }
    400
    401        PROPERTIES_LOCATION = {
    402            **generator.Generator.PROPERTIES_LOCATION,
    403            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    404            exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA,
    405            exp.OnCluster: exp.Properties.Location.POST_NAME,
    406        }
    407
    408        JOIN_HINTS = False
    409        TABLE_HINTS = False
    410        EXPLICIT_UNION = True
    411        GROUPINGS_SEP = ""
    412
    413        # there's no list in docs, but it can be found in Clickhouse code
    414        # see `ClickHouse/src/Parsers/ParserCreate*.cpp`
    415        ON_CLUSTER_TARGETS = {
    416            "DATABASE",
    417            "TABLE",
    418            "VIEW",
    419            "DICTIONARY",
    420            "INDEX",
    421            "FUNCTION",
    422            "NAMED COLLECTION",
    423        }
    424
    425        def _any_to_has(
    426            self,
    427            expression: exp.EQ | exp.NEQ,
    428            default: t.Callable[[t.Any], str],
    429            prefix: str = "",
    430        ) -> str:
    431            if isinstance(expression.left, exp.Any):
    432                arr = expression.left
    433                this = expression.right
    434            elif isinstance(expression.right, exp.Any):
    435                arr = expression.right
    436                this = expression.left
    437            else:
    438                return default(expression)
    439            return prefix + self.func("has", arr.this.unnest(), this)
    440
    441        def eq_sql(self, expression: exp.EQ) -> str:
    442            return self._any_to_has(expression, super().eq_sql)
    443
    444        def neq_sql(self, expression: exp.NEQ) -> str:
    445            return self._any_to_has(expression, super().neq_sql, "NOT ")
    446
    447        def regexpilike_sql(self, expression: exp.RegexpILike) -> str:
    448            # Manually add a flag to make the search case-insensitive
    449            regex = self.func("CONCAT", "'(?i)'", expression.expression)
    450            return f"match({self.format_args(expression.this, regex)})"
    451
    452        def datatype_sql(self, expression: exp.DataType) -> str:
    453            # String is the standard ClickHouse type, every other variant is just an alias.
    454            # Additionally, any supplied length parameter will be ignored.
    455            #
    456            # https://clickhouse.com/docs/en/sql-reference/data-types/string
    457            if expression.this in self.STRING_TYPE_MAPPING:
    458                return "String"
    459
    460            return super().datatype_sql(expression)
    461
    462        def concat_sql(self, expression: exp.Concat) -> str:
    463            # Clickhouse errors out if we try to cast a NULL value to TEXT
    464            if expression.args.get("safe"):
    465                return self.func(
    466                    "CONCAT",
    467                    *[
    468                        exp.func("if", e.is_(exp.null()), e, exp.cast(e, "text"))
    469                        for e in expression.expressions
    470                    ],
    471                )
    472            return super().concat_sql(expression)
    473
    474        def cte_sql(self, expression: exp.CTE) -> str:
    475            if expression.args.get("scalar"):
    476                this = self.sql(expression, "this")
    477                alias = self.sql(expression, "alias")
    478                return f"{this} AS {alias}"
    479
    480            return super().cte_sql(expression)
    481
    482        def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
    483            return super().after_limit_modifiers(expression) + [
    484                self.seg("SETTINGS ") + self.expressions(expression, key="settings", flat=True)
    485                if expression.args.get("settings")
    486                else "",
    487                self.seg("FORMAT ") + self.sql(expression, "format")
    488                if expression.args.get("format")
    489                else "",
    490            ]
    491
    492        def parameterizedagg_sql(self, expression: exp.Anonymous) -> str:
    493            params = self.expressions(expression, key="params", flat=True)
    494            return self.func(expression.name, *expression.expressions) + f"({params})"
    495
    496        def placeholder_sql(self, expression: exp.Placeholder) -> str:
    497            return f"{{{expression.name}: {self.sql(expression, 'kind')}}}"
    498
    499        def oncluster_sql(self, expression: exp.OnCluster) -> str:
    500            return f"ON CLUSTER {self.sql(expression, 'this')}"
    501
    502        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
    503            kind = self.sql(expression, "kind").upper()
    504            if kind in self.ON_CLUSTER_TARGETS and locations.get(exp.Properties.Location.POST_NAME):
    505                this_name = self.sql(expression.this, "this")
    506                this_properties = " ".join(
    507                    [self.sql(prop) for prop in locations[exp.Properties.Location.POST_NAME]]
    508                )
    509                this_schema = self.schema_columns_sql(expression.this)
    510                return f"{this_name}{self.sep()}{this_properties}{self.sep()}{this_schema}"
    511
    512            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 = ('(', ')')
NVL2_SUPPORTED = False
TABLESAMPLE_REQUIRES_PARENS = False
STRING_TYPE_MAPPING = {<Type.CHAR: 'CHAR'>: 'String', <Type.LONGBLOB: 'LONGBLOB'>: 'String', <Type.LONGTEXT: 'LONGTEXT'>: 'String', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'String', <Type.MEDIUMTEXT: 'MEDIUMTEXT'>: 'String', <Type.TINYBLOB: 'TINYBLOB'>: 'String', <Type.TINYTEXT: 'TINYTEXT'>: 'String', <Type.TEXT: 'TEXT'>: 'String', <Type.VARBINARY: 'VARBINARY'>: 'String', <Type.VARCHAR: 'VARCHAR'>: 'String'}
TYPE_MAPPING = {<Type.NCHAR: 'NCHAR'>: 'CHAR', <Type.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <Type.MEDIUMTEXT: 'MEDIUMTEXT'>: 'String', <Type.LONGTEXT: 'LONGTEXT'>: 'String', <Type.TINYTEXT: 'TINYTEXT'>: 'String', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'String', <Type.LONGBLOB: 'LONGBLOB'>: 'String', <Type.TINYBLOB: 'TINYBLOB'>: 'String', <Type.INET: 'INET'>: 'INET', <Type.CHAR: 'CHAR'>: 'String', <Type.TEXT: 'TEXT'>: 'String', <Type.VARBINARY: 'VARBINARY'>: 'String', <Type.VARCHAR: 'VARCHAR'>: 'String', <Type.ARRAY: 'ARRAY'>: 'Array', <Type.BIGINT: 'BIGINT'>: 'Int64', <Type.DATETIME64: 'DATETIME64'>: 'DateTime64', <Type.DOUBLE: 'DOUBLE'>: 'Float64', <Type.ENUM: 'ENUM'>: 'Enum', <Type.ENUM8: 'ENUM8'>: 'Enum8', <Type.ENUM16: 'ENUM16'>: 'Enum16', <Type.FIXEDSTRING: 'FIXEDSTRING'>: 'FixedString', <Type.FLOAT: 'FLOAT'>: 'Float32', <Type.INT: 'INT'>: 'Int32', <Type.MEDIUMINT: 'MEDIUMINT'>: 'Int32', <Type.INT128: 'INT128'>: 'Int128', <Type.INT256: 'INT256'>: 'Int256', <Type.LOWCARDINALITY: 'LOWCARDINALITY'>: 'LowCardinality', <Type.MAP: 'MAP'>: 'Map', <Type.NESTED: 'NESTED'>: 'Nested', <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 ClickHouse.Generator.<lambda>>, <class 'sqlglot.expressions.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CheckColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function ClickHouse.Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Select'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.AnyValue'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.ApproxDistinct'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.ArgMax'>: <function arg_max_or_min_no_count.<locals>._arg_max_or_min_sql>, <class 'sqlglot.expressions.ArgMin'>: <function arg_max_or_min_no_count.<locals>._arg_max_or_min_sql>, <class 'sqlglot.expressions.Array'>: <function inline_array_sql>, <class 'sqlglot.expressions.CastToStrType'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.CurrentDate'>: <function ClickHouse.Generator.<lambda>>, <class 'sqlglot.expressions.DateDiff'>: <function ClickHouse.Generator.<lambda>>, <class 'sqlglot.expressions.Final'>: <function ClickHouse.Generator.<lambda>>, <class 'sqlglot.expressions.IsNan'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.Map'>: <function ClickHouse.Generator.<lambda>>, <class 'sqlglot.expressions.Nullif'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.PartitionedByProperty'>: <function ClickHouse.Generator.<lambda>>, <class 'sqlglot.expressions.Pivot'>: <function no_pivot_sql>, <class 'sqlglot.expressions.Quantile'>: <function _quantile_sql>, <class 'sqlglot.expressions.RegexpLike'>: <function ClickHouse.Generator.<lambda>>, <class 'sqlglot.expressions.StartsWith'>: <function rename_func.<locals>.<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.InputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IsolatedLoadingProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.JournalProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.LanguageProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LikeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LocationProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockingProperty'>: <Location.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.LogProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.MaterializedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeBlockRatioProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.OnProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OnCommitProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.Order'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OutputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PartitionedByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PartitionedOfProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ReturnsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatDelimitedProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatSerdeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SampleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SchemaCommentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SerdeProperties'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Set'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SettingsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SetProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SortKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StabilityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TemporaryProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ToTableProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TransientProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.TransformModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.MergeTreeTTL'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.WithSystemVersioningProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OnCluster'>: <Location.POST_NAME: 'POST_NAME'>}
JOIN_HINTS = False
TABLE_HINTS = False
EXPLICIT_UNION = True
GROUPINGS_SEP = ''
ON_CLUSTER_TARGETS = {'TABLE', 'INDEX', 'VIEW', 'DICTIONARY', 'FUNCTION', 'DATABASE', 'NAMED COLLECTION'}
def eq_sql(self, expression: sqlglot.expressions.EQ) -> str: View Source

    441        def eq_sql(self, expression: exp.EQ) -> str:
    442            return self._any_to_has(expression, super().eq_sql)

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

    444        def neq_sql(self, expression: exp.NEQ) -> str:
    445            return self._any_to_has(expression, super().neq_sql, "NOT ")

def regexpilike_sql(self, expression: sqlglot.expressions.RegexpILike) -> str: View Source

    447        def regexpilike_sql(self, expression: exp.RegexpILike) -> str:
    448            # Manually add a flag to make the search case-insensitive
    449            regex = self.func("CONCAT", "'(?i)'", expression.expression)
    450            return f"match({self.format_args(expression.this, regex)})"

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

    452        def datatype_sql(self, expression: exp.DataType) -> str:
    453            # String is the standard ClickHouse type, every other variant is just an alias.
    454            # Additionally, any supplied length parameter will be ignored.
    455            #
    456            # https://clickhouse.com/docs/en/sql-reference/data-types/string
    457            if expression.this in self.STRING_TYPE_MAPPING:
    458                return "String"
    459
    460            return super().datatype_sql(expression)

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

    462        def concat_sql(self, expression: exp.Concat) -> str:
    463            # Clickhouse errors out if we try to cast a NULL value to TEXT
    464            if expression.args.get("safe"):
    465                return self.func(
    466                    "CONCAT",
    467                    *[
    468                        exp.func("if", e.is_(exp.null()), e, exp.cast(e, "text"))
    469                        for e in expression.expressions
    470                    ],
    471                )
    472            return super().concat_sql(expression)

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

    474        def cte_sql(self, expression: exp.CTE) -> str:
    475            if expression.args.get("scalar"):
    476                this = self.sql(expression, "this")
    477                alias = self.sql(expression, "alias")
    478                return f"{this} AS {alias}"
    479
    480            return super().cte_sql(expression)

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

    482        def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
    483            return super().after_limit_modifiers(expression) + [
    484                self.seg("SETTINGS ") + self.expressions(expression, key="settings", flat=True)
    485                if expression.args.get("settings")
    486                else "",
    487                self.seg("FORMAT ") + self.sql(expression, "format")
    488                if expression.args.get("format")
    489                else "",
    490            ]

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

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

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

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

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

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

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

    502        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
    503            kind = self.sql(expression, "kind").upper()
    504            if kind in self.ON_CLUSTER_TARGETS and locations.get(exp.Properties.Location.POST_NAME):
    505                this_name = self.sql(expression.this, "this")
    506                this_properties = " ".join(
    507                    [self.sql(prop) for prop in locations[exp.Properties.Location.POST_NAME]]
    508                )
    509                this_schema = self.schema_columns_sql(expression.this)
    510                return f"{this_name}{self.sep()}{this_properties}{self.sep()}{this_schema}"
    511
    512            return super().createable_sql(expression, locations)

SELECT_KINDS: Tuple[str, ...] = ()

##### 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
  LIMIT_ONLY_LITERALS
  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
  TZ_TO_WITH_TIME_ZONE
  VALUES_AS_TABLE
  ALTER_TABLE_INCLUDE_COLUMN_KEYWORD
  UNNEST_WITH_ORDINALITY
  AGGREGATE_FILTER_SUPPORTED
  SEMI_ANTI_JOIN_WITH_SIDE
  COMPUTED_COLUMN_WITH_TYPE
  SUPPORTS_TABLE_COPY
  COLLATE_IS_FUNC
  DATA_TYPE_SPECIFIERS_ALLOWED
  ENSURE_BOOLS
  CTE_RECURSIVE_KEYWORD_REQUIRED
  STAR_MAPPING
  TIME_PART_SINGULARS
  TOKEN_MAPPING
  PARAMETER_TOKEN
  RESERVED_KEYWORDS
  WITH_SEPARATED_COMMENTS
  EXCLUDE_COMMENTS
  UNWRAPPED_INTERVAL_VALUES
  EXPRESSIONS_WITHOUT_NESTED_CTES
  KEY_VALUE_DEFINITONS
  SENTINEL_LINE_BREAK
  pretty
  identify
  normalize
  pad
  unsupported_level
  max_unsupported
  leading_comma
  max_text_width
  comments
  dialect
  normalize_functions
  unsupported_messages
  generate
  preprocess
  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
  computedcolumnconstraint_sql
  autoincrementcolumnconstraint_sql
  compresscolumnconstraint_sql
  generatedasidentitycolumnconstraint_sql
  generatedasrowcolumnconstraint_sql
  periodforsystemtimeconstraint_sql
  notnullcolumnconstraint_sql
  transformcolumnconstraint_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
  datatypeparam_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_name
  property_sql
  likeproperty_sql
  fallbackproperty_sql
  journalproperty_sql
  freespaceproperty_sql
  checksumproperty_sql
  mergeblockratioproperty_sql
  datablocksizeproperty_sql
  blockcompressionproperty_sql
  isolatedloadingproperty_sql
  partitionboundspec_sql
  partitionedofproperty_sql
  lockingproperty_sql
  withdataproperty_sql
  withsystemversioningproperty_sql
  insert_sql
  intersect_sql
  intersect_op
  introducer_sql
  kill_sql
  pseudotype_sql
  objectidentifier_sql
  onconflict_sql
  returning_sql
  rowformatdelimitedproperty_sql
  withtablehint_sql
  indextablehint_sql
  table_sql
  tablesample_sql
  pivot_sql
  version_sql
  tuple_sql
  update_sql
  values_sql
  var_sql
  into_sql
  from_sql
  group_sql
  having_sql
  connect_sql
  prior_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
  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
  formatjson_sql
  jsonobject_sql
  jsonarray_sql
  jsonarrayagg_sql
  jsoncolumndef_sql
  jsonschema_sql
  jsontable_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
  add_column_sql
  droppartition_sql
  addconstraint_sql
  distinct_sql
  ignorenulls_sql
  respectnulls_sql
  intdiv_sql
  dpipe_sql
  div_sql
  overlaps_sql
  distance_sql
  dot_sql
  propertyeq_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
  nullsafeeq_sql
  nullsafeneq_sql
  or_sql
  slice_sql
  sub_sql
  trycast_sql
  log_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
  nvl2_sql
  comprehension_sql
  columnprefix_sql
  opclass_sql
  predict_sql
  forin_sql
  refresh_sql
  operator_sql