Edit on GitHub

sqlglot.dialects.clickhouse

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

Parser consumes a list of tokens produced by the sqlglot.tokens.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: 50.
  • index_offset: Index offset for arrays eg ARRAY[0] vs ARRAY[1] as the head of a list. Default: 0
  • alias_post_tablesample: If the table alias comes after tablesample. Default: False
  • 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
  • null_ordering: Indicates the default null ordering method to use if not explicitly set. Options are "nulls_are_small", "nulls_are_large", "nulls_are_last". Default: "nulls_are_small"
class ClickHouse.Generator(sqlglot.generator.Generator):
266    class Generator(generator.Generator):
267        STRUCT_DELIMITER = ("(", ")")
268
269        TYPE_MAPPING = {
270            **generator.Generator.TYPE_MAPPING,
271            exp.DataType.Type.ARRAY: "Array",
272            exp.DataType.Type.BIGINT: "Int64",
273            exp.DataType.Type.DATETIME64: "DateTime64",
274            exp.DataType.Type.DOUBLE: "Float64",
275            exp.DataType.Type.FLOAT: "Float32",
276            exp.DataType.Type.INT: "Int32",
277            exp.DataType.Type.INT128: "Int128",
278            exp.DataType.Type.INT256: "Int256",
279            exp.DataType.Type.MAP: "Map",
280            exp.DataType.Type.NULLABLE: "Nullable",
281            exp.DataType.Type.SMALLINT: "Int16",
282            exp.DataType.Type.STRUCT: "Tuple",
283            exp.DataType.Type.TINYINT: "Int8",
284            exp.DataType.Type.UBIGINT: "UInt64",
285            exp.DataType.Type.UINT: "UInt32",
286            exp.DataType.Type.UINT128: "UInt128",
287            exp.DataType.Type.UINT256: "UInt256",
288            exp.DataType.Type.USMALLINT: "UInt16",
289            exp.DataType.Type.UTINYINT: "UInt8",
290        }
291
292        TRANSFORMS = {
293            **generator.Generator.TRANSFORMS,
294            exp.AnyValue: rename_func("any"),
295            exp.ApproxDistinct: rename_func("uniq"),
296            exp.Array: inline_array_sql,
297            exp.CastToStrType: rename_func("CAST"),
298            exp.Final: lambda self, e: f"{self.sql(e, 'this')} FINAL",
299            exp.Map: lambda self, e: _lower_func(var_map_sql(self, e)),
300            exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}",
301            exp.Pivot: no_pivot_sql,
302            exp.Quantile: lambda self, e: self.func("quantile", e.args.get("quantile"))
303            + f"({self.sql(e, 'this')})",
304            exp.RegexpLike: lambda self, e: f"match({self.format_args(e.this, e.expression)})",
305            exp.StrPosition: lambda self, e: f"position({self.format_args(e.this, e.args.get('substr'), e.args.get('position'))})",
306            exp.VarMap: lambda self, e: _lower_func(var_map_sql(self, e)),
307        }
308
309        PROPERTIES_LOCATION = {
310            **generator.Generator.PROPERTIES_LOCATION,
311            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
312            exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA,
313            exp.OnCluster: exp.Properties.Location.POST_NAME,
314        }
315
316        JOIN_HINTS = False
317        TABLE_HINTS = False
318        EXPLICIT_UNION = True
319        GROUPINGS_SEP = ""
320
321        # there's no list in docs, but it can be found in Clickhouse code
322        # see `ClickHouse/src/Parsers/ParserCreate*.cpp`
323        ON_CLUSTER_TARGETS = {
324            "DATABASE",
325            "TABLE",
326            "VIEW",
327            "DICTIONARY",
328            "INDEX",
329            "FUNCTION",
330            "NAMED COLLECTION",
331        }
332
333        def cte_sql(self, expression: exp.CTE) -> str:
334            if isinstance(expression.this, exp.Alias):
335                return self.sql(expression, "this")
336
337            return super().cte_sql(expression)
338
339        def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
340            return super().after_limit_modifiers(expression) + [
341                self.seg("SETTINGS ") + self.expressions(expression, key="settings", flat=True)
342                if expression.args.get("settings")
343                else "",
344                self.seg("FORMAT ") + self.sql(expression, "format")
345                if expression.args.get("format")
346                else "",
347            ]
348
349        def parameterizedagg_sql(self, expression: exp.Anonymous) -> str:
350            params = self.expressions(expression, "params", flat=True)
351            return self.func(expression.name, *expression.expressions) + f"({params})"
352
353        def placeholder_sql(self, expression: exp.Placeholder) -> str:
354            return f"{{{expression.name}: {self.sql(expression, 'kind')}}}"
355
356        def oncluster_sql(self, expression: exp.OnCluster) -> str:
357            return f"ON CLUSTER {self.sql(expression, 'this')}"
358
359        def createable_sql(
360            self,
361            expression: exp.Create,
362            locations: dict[exp.Properties.Location, list[exp.Property]],
363        ) -> str:
364            kind = self.sql(expression, "kind").upper()
365            if kind in self.ON_CLUSTER_TARGETS and locations.get(exp.Properties.Location.POST_NAME):
366                this_name = self.sql(expression.this, "this")
367                this_properties = " ".join(
368                    [self.sql(prop) for prop in locations[exp.Properties.Location.POST_NAME]]
369                )
370                this_schema = self.schema_columns_sql(expression.this)
371                return f"{this_name}{self.sep()}{this_properties}{self.sep()}{this_schema}"
372            return super().createable_sql(expression, locations)

Generator interprets the given syntax tree and produces a SQL string as an output.

Arguments:
  • time_mapping (dict): the dictionary of custom time mappings in which the key represents a python time format and the output the target time format
  • time_trie (trie): a trie of the time_mapping keys
  • pretty (bool): if set to True the returned string will be formatted. Default: False.
  • quote_start (str): specifies which starting character to use to delimit quotes. Default: '.
  • quote_end (str): specifies which ending character to use to delimit quotes. Default: '.
  • identifier_start (str): specifies which starting character to use to delimit identifiers. Default: ".
  • identifier_end (str): specifies which ending character to use to delimit identifiers. Default: ".
  • bit_start (str): specifies which starting character to use to delimit bit literals. Default: None.
  • bit_end (str): specifies which ending character to use to delimit bit literals. Default: None.
  • hex_start (str): specifies which starting character to use to delimit hex literals. Default: None.
  • hex_end (str): specifies which ending character to use to delimit hex literals. Default: None.
  • byte_start (str): specifies which starting character to use to delimit byte literals. Default: None.
  • byte_end (str): specifies which ending character to use to delimit byte literals. Default: None.
  • raw_start (str): specifies which starting character to use to delimit raw literals. Default: None.
  • raw_end (str): specifies which ending character to use to delimit raw literals. Default: None.
  • identify (bool | str): 'always': always quote, 'safe': quote identifiers if they don't contain an upcase, True defaults to always.
  • normalize (bool): if set to True all identifiers will lower cased
  • string_escape (str): specifies a string escape character. Default: '.
  • identifier_escape (str): specifies an identifier escape character. Default: ".
  • pad (int): determines padding in a formatted string. Default: 2.
  • indent (int): determines the size of indentation in a formatted string. Default: 4.
  • unnest_column_only (bool): if true unnest table aliases are considered only as column aliases
  • normalize_functions (str): normalize function names, "upper", "lower", or None Default: "upper"
  • alias_post_tablesample (bool): if the table alias comes after tablesample Default: False
  • identifiers_can_start_with_digit (bool): if an unquoted identifier can start with digit Default: False
  • unsupported_level (ErrorLevel): determines the generator's behavior when it encounters unsupported expressions. Default ErrorLevel.WARN.
  • null_ordering (str): Indicates the default null ordering method to use if not explicitly set. Options are "nulls_are_small", "nulls_are_large", "nulls_are_last". Default: "nulls_are_small"
  • max_unsupported (int): 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 (bool): if the the comma is leading or trailing in select statements 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
def cte_sql(self, expression: sqlglot.expressions.CTE) -> str:
333        def cte_sql(self, expression: exp.CTE) -> str:
334            if isinstance(expression.this, exp.Alias):
335                return self.sql(expression, "this")
336
337            return super().cte_sql(expression)
def after_limit_modifiers(self, expression: sqlglot.expressions.Expression) -> List[str]:
339        def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
340            return super().after_limit_modifiers(expression) + [
341                self.seg("SETTINGS ") + self.expressions(expression, key="settings", flat=True)
342                if expression.args.get("settings")
343                else "",
344                self.seg("FORMAT ") + self.sql(expression, "format")
345                if expression.args.get("format")
346                else "",
347            ]
def parameterizedagg_sql(self, expression: sqlglot.expressions.Anonymous) -> str:
349        def parameterizedagg_sql(self, expression: exp.Anonymous) -> str:
350            params = self.expressions(expression, "params", flat=True)
351            return self.func(expression.name, *expression.expressions) + f"({params})"
def placeholder_sql(self, expression: sqlglot.expressions.Placeholder) -> str:
353        def placeholder_sql(self, expression: exp.Placeholder) -> str:
354            return f"{{{expression.name}: {self.sql(expression, 'kind')}}}"
def oncluster_sql(self, expression: sqlglot.expressions.OnCluster) -> str:
356        def oncluster_sql(self, expression: exp.OnCluster) -> str:
357            return f"ON CLUSTER {self.sql(expression, 'this')}"
def createable_sql( self, expression: sqlglot.expressions.Create, locations: dict[sqlglot.expressions.Properties.Location, list[sqlglot.expressions.Property]]) -> str:
359        def createable_sql(
360            self,
361            expression: exp.Create,
362            locations: dict[exp.Properties.Location, list[exp.Property]],
363        ) -> str:
364            kind = self.sql(expression, "kind").upper()
365            if kind in self.ON_CLUSTER_TARGETS and locations.get(exp.Properties.Location.POST_NAME):
366                this_name = self.sql(expression.this, "this")
367                this_properties = " ".join(
368                    [self.sql(prop) for prop in locations[exp.Properties.Location.POST_NAME]]
369                )
370                this_schema = self.schema_columns_sql(expression.this)
371                return f"{this_name}{self.sep()}{this_properties}{self.sep()}{this_schema}"
372            return super().createable_sql(expression, locations)
Inherited Members
sqlglot.generator.Generator
Generator
generate
unsupported
sep
seg
pad_comment
maybe_comment
wrap
no_identify
normalize_func
indent
sql
uncache_sql
cache_sql
characterset_sql
column_sql
columnposition_sql
columndef_sql
columnconstraint_sql
autoincrementcolumnconstraint_sql
compresscolumnconstraint_sql
generatedasidentitycolumnconstraint_sql
notnullcolumnconstraint_sql
primarykeycolumnconstraint_sql
uniquecolumnconstraint_sql
create_sql
clone_sql
describe_sql
prepend_ctes
with_sql
tablealias_sql
bitstring_sql
hexstring_sql
bytestring_sql
rawstring_sql
datatypesize_sql
datatype_sql
directory_sql
delete_sql
drop_sql
except_sql
except_op
fetch_sql
filter_sql
hint_sql
index_sql
identifier_sql
inputoutputformat_sql
national_sql
partition_sql
properties_sql
root_properties
properties
with_properties
locate_properties
property_sql
likeproperty_sql
fallbackproperty_sql
journalproperty_sql
freespaceproperty_sql
checksumproperty_sql
mergeblockratioproperty_sql
datablocksizeproperty_sql
blockcompressionproperty_sql
isolatedloadingproperty_sql
lockingproperty_sql
withdataproperty_sql
insert_sql
intersect_sql
intersect_op
introducer_sql
pseudotype_sql
onconflict_sql
returning_sql
rowformatdelimitedproperty_sql
table_sql
tablesample_sql
pivot_sql
tuple_sql
update_sql
values_sql
var_sql
into_sql
from_sql
group_sql
having_sql
join_sql
lambda_sql
lateral_sql
limit_sql
offset_sql
setitem_sql
set_sql
pragma_sql
lock_sql
literal_sql
loaddata_sql
null_sql
boolean_sql
order_sql
cluster_sql
distribute_sql
sort_sql
ordered_sql
matchrecognize_sql
query_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
concat_sql
check_sql
foreignkey_sql
primarykey_sql
if_sql
matchagainst_sql
jsonkeyvalue_sql
jsonobject_sql
openjsoncolumndef_sql
openjson_sql
in_sql
in_unnest_op
interval_sql
return_sql
reference_sql
anonymous_sql
paren_sql
neg_sql
not_sql
alias_sql
aliases_sql
attimezone_sql
add_sql
and_sql
connector_sql
bitwiseand_sql
bitwiseleftshift_sql
bitwisenot_sql
bitwiseor_sql
bitwiserightshift_sql
bitwisexor_sql
cast_sql
currentdate_sql
collate_sql
command_sql
comment_sql
mergetreettlaction_sql
mergetreettl_sql
transaction_sql
commit_sql
rollback_sql
altercolumn_sql
renametable_sql
altertable_sql
droppartition_sql
addconstraint_sql
distinct_sql
ignorenulls_sql
respectnulls_sql
intdiv_sql
dpipe_sql
div_sql
overlaps_sql
distance_sql
dot_sql
eq_sql
escape_sql
glob_sql
gt_sql
gte_sql
ilike_sql
ilikeany_sql
is_sql
like_sql
likeany_sql
similarto_sql
lt_sql
lte_sql
mod_sql
mul_sql
neq_sql
nullsafeeq_sql
nullsafeneq_sql
or_sql
slice_sql
sub_sql
trycast_sql
use_sql
binary
function_fallback_sql
func
format_args
text_width
format_time
expressions
op_expressions
naked_property
set_operation
tag_sql
token_sql
userdefinedfunction_sql
joinhint_sql
kwarg_sql
when_sql
merge_sql
tochar_sql
dictproperty_sql
dictrange_sql
dictsubproperty_sql