sqlglot.generators.clickhouse
1from __future__ import annotations 2 3import datetime 4import typing as t 5 6from sqlglot import exp, generator 7from sqlglot.dialects.dialect import ( 8 arg_max_or_min_no_count, 9 array_sort_order, 10 inline_array_sql, 11 jarowinkler_similarity, 12 json_extract_segments, 13 json_path_key_only_name, 14 length_or_char_length_sql, 15 no_pivot_sql, 16 rename_func, 17 remove_from_array_using_filter, 18 sha256_sql, 19 strposition_sql, 20 var_map_sql, 21 weekstart_unit_to_str, 22 unit_to_var, 23 trim_sql, 24 sha2_digest_sql, 25) 26from sqlglot.generator import unsupported_args 27from sqlglot.helper import is_int 28from sqlglot.optimizer.simplify import simplify_parens 29from collections import defaultdict 30 31DATETIME_DELTA = t.Union[exp.DateAdd, exp.DateDiff, exp.DateSub, exp.TimestampSub, exp.TimestampAdd] 32 33 34@unsupported_args(("expression", "ClickHouse's arraySort does not support a comparator.")) 35def _array_sort_sql(self: ClickHouseGenerator, expression: exp.ArraySort) -> str: 36 order = array_sort_order(expression) 37 if order is None: 38 self.unsupported("arraySort only takes literal orders") 39 return self.func("arraySort", expression.this) 40 41 asc, nulls_first = order 42 if nulls_first: 43 self.unsupported("arraySort and arrayReverseSort put NULLs last") 44 return self.func("arraySort" if asc else "arrayReverseSort", expression.this) 45 46 47def _unix_to_time_sql(self: ClickHouseGenerator, expression: exp.UnixToTime) -> str: 48 scale = expression.args.get("scale") 49 timestamp = expression.this 50 51 if scale in (None, exp.UnixToTime.SECONDS): 52 return self.func("fromUnixTimestamp", exp.cast(timestamp, exp.DType.BIGINT)) 53 if scale == exp.UnixToTime.MILLIS: 54 return self.func("fromUnixTimestamp64Milli", exp.cast(timestamp, exp.DType.BIGINT)) 55 if scale == exp.UnixToTime.MICROS: 56 return self.func("fromUnixTimestamp64Micro", exp.cast(timestamp, exp.DType.BIGINT)) 57 if scale == exp.UnixToTime.NANOS: 58 return self.func("fromUnixTimestamp64Nano", exp.cast(timestamp, exp.DType.BIGINT)) 59 60 return self.func( 61 "fromUnixTimestamp", 62 exp.cast(exp.Div(this=timestamp, expression=exp.func("POW", 10, scale)), exp.DType.BIGINT), 63 ) 64 65 66def _lower_func(sql: str) -> str: 67 index = sql.index("(") 68 return sql[:index].lower() + sql[index:] 69 70 71def _quantile_sql(self: ClickHouseGenerator, expression: exp.Quantile) -> str: 72 quantile = expression.args["quantile"] 73 approx = isinstance(expression, exp.ApproxQuantile) 74 args = f"({self.sql(expression, 'this')})" 75 76 if isinstance(quantile, exp.Array): 77 func = self.func("quantiles" if approx else "quantilesExact", *quantile) 78 else: 79 func = self.func("quantile" if approx else "quantileExact", quantile) 80 81 return func + args 82 83 84def _datetime_delta_sql(name: str) -> t.Callable[[generator.Generator, DATETIME_DELTA], str]: 85 def _delta_sql(self: generator.Generator, expression: DATETIME_DELTA) -> str: 86 if not expression.unit: 87 return rename_func(name)(self, expression) 88 89 return self.func( 90 name, 91 unit_to_var(expression), 92 expression.expression, 93 expression.this, 94 expression.args.get("zone"), 95 ) 96 97 return _delta_sql 98 99 100def _timestrtotime_sql(self: ClickHouseGenerator, expression: exp.TimeStrToTime): 101 ts = expression.this 102 103 tz = expression.args.get("zone") 104 if tz and isinstance(ts, exp.Literal): 105 # Clickhouse will not accept timestamps that include a UTC offset, so we must remove them. 106 # The first step to removing is parsing the string with `datetime.datetime.fromisoformat`. 107 # 108 # In python <3.11, `fromisoformat()` can only parse timestamps of millisecond (3 digit) 109 # or microsecond (6 digit) precision. It will error if passed any other number of fractional 110 # digits, so we extract the fractional seconds and pad to 6 digits before parsing. 111 ts_string = ts.name.strip() 112 113 # separate [date and time] from [fractional seconds and UTC offset] 114 ts_parts = ts_string.split(".") 115 if len(ts_parts) == 2: 116 # separate fractional seconds and UTC offset 117 offset_sep = "+" if "+" in ts_parts[1] else "-" 118 ts_frac_parts = ts_parts[1].split(offset_sep) 119 num_frac_parts = len(ts_frac_parts) 120 121 # pad to 6 digits if fractional seconds present 122 ts_frac_parts[0] = ts_frac_parts[0].ljust(6, "0") 123 ts_string = "".join( 124 [ 125 ts_parts[0], # date and time 126 ".", 127 ts_frac_parts[0], # fractional seconds 128 offset_sep if num_frac_parts > 1 else "", 129 ts_frac_parts[1] if num_frac_parts > 1 else "", # utc offset (if present) 130 ] 131 ) 132 133 # return literal with no timezone, eg turn '2020-01-01 12:13:14-08:00' into '2020-01-01 12:13:14' 134 # this is because Clickhouse encodes the timezone as a data type parameter and throws an error if 135 # it's part of the timestamp string 136 ts_without_tz = ( 137 datetime.datetime.fromisoformat(ts_string).replace(tzinfo=None).isoformat(sep=" ") 138 ) 139 ts = exp.Literal.string(ts_without_tz) 140 141 # Non-nullable DateTime64 with microsecond precision 142 expressions = [exp.DataTypeParam(this=tz)] if tz else [] 143 datatype = exp.DType.DATETIME64.into_expr( 144 expressions=[exp.DataTypeParam(this=exp.Literal.number(6)), *expressions], 145 nullable=False, 146 ) 147 148 return self.sql(exp.cast(ts, datatype, dialect=self.dialect)) 149 150 151def _map_sql(self: ClickHouseGenerator, expression: exp.Map | exp.VarMap) -> str: 152 if not (expression.parent and expression.parent.arg_key == "settings"): 153 return _lower_func(var_map_sql(self, expression)) 154 155 keys = expression.args.get("keys") 156 values = expression.args.get("values") 157 158 if not isinstance(keys, exp.Array) or not isinstance(values, exp.Array): 159 self.unsupported("Cannot convert array columns into map.") 160 return "" 161 162 args = [] 163 for key, value in zip(keys.expressions, values.expressions): 164 args.append(f"{self.sql(key)}: {self.sql(value)}") 165 166 csv_args = ", ".join(args) 167 168 return f"{{{csv_args}}}" 169 170 171def _json_cast_sql(self: ClickHouseGenerator, expression: exp.JSONCast) -> str: 172 this = self.sql(expression, "this") 173 to = expression.to 174 to_sql = self.sql(to) 175 176 if to.expressions: 177 to_sql = self.sql(exp.to_identifier(to_sql)) 178 179 return f"{this}.:{to_sql}" 180 181 182class ClickHouseGenerator(generator.Generator): 183 BYTE_STRING_FUNCTION = "unhex" 184 SELECT_KINDS = () 185 TRY_SUPPORTED = False 186 SUPPORTS_UESCAPE = False 187 SUPPORTS_DECODE_CASE = False 188 SUPPORTS_NESTED_JSON_SELECT = True 189 190 AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS 191 192 QUERY_HINTS = False 193 STRUCT_DELIMITER = ("(", ")") 194 NVL2_SUPPORTED = False 195 ALTER_SET_TYPE = "TYPE" 196 SUPPORTS_ALTER_COLUMN_IF_EXISTS = True 197 TABLESAMPLE_REQUIRES_PARENS = False 198 TABLESAMPLE_SIZE_IS_ROWS = False 199 TABLESAMPLE_KEYWORDS = "SAMPLE" 200 LAST_DAY_SUPPORTS_DATE_PART = False 201 CAN_IMPLEMENT_ARRAY_ANY = True 202 SUPPORTS_TO_NUMBER = False 203 JOIN_HINTS = False 204 TABLE_HINTS = False 205 MATCH_CONDITION_IN_ON = True 206 GROUPINGS_SEP = "" 207 SET_OP_MODIFIERS = False 208 SET_OP_LIMITS = True 209 ARRAY_SIZE_NAME = "LENGTH" 210 VARIANCE_NAME = "varSamp" 211 WRAP_DERIVED_VALUES = False 212 AUTO_REFRESH_BARE_INTERVALS = True 213 214 STRING_TYPE_MAPPING: t.ClassVar = { 215 exp.DType.BLOB: "String", 216 exp.DType.CHAR: "String", 217 exp.DType.LONGBLOB: "String", 218 exp.DType.LONGTEXT: "String", 219 exp.DType.MEDIUMBLOB: "String", 220 exp.DType.MEDIUMTEXT: "String", 221 exp.DType.TINYBLOB: "String", 222 exp.DType.TINYTEXT: "String", 223 exp.DType.TEXT: "String", 224 exp.DType.VARBINARY: "String", 225 exp.DType.VARCHAR: "String", 226 } 227 228 SUPPORTED_JSON_PATH_PARTS = { 229 exp.JSONPathKey, 230 exp.JSONPathRoot, 231 exp.JSONPathSubscript, 232 } 233 234 TYPE_MAPPING = { 235 **generator.Generator.TYPE_MAPPING, 236 exp.DType.BLOB: "String", 237 exp.DType.CHAR: "String", 238 exp.DType.LONGBLOB: "String", 239 exp.DType.LONGTEXT: "String", 240 exp.DType.MEDIUMBLOB: "String", 241 exp.DType.MEDIUMTEXT: "String", 242 exp.DType.TINYBLOB: "String", 243 exp.DType.TINYTEXT: "String", 244 exp.DType.TEXT: "String", 245 exp.DType.VARBINARY: "String", 246 exp.DType.VARCHAR: "String", 247 exp.DType.ARRAY: "Array", 248 exp.DType.BOOLEAN: "Bool", 249 exp.DType.BIGINT: "Int64", 250 exp.DType.DATE32: "Date32", 251 exp.DType.DATETIME: "DateTime", 252 exp.DType.DATETIME2: "DateTime", 253 exp.DType.SMALLDATETIME: "DateTime", 254 exp.DType.DATETIME64: "DateTime64", 255 exp.DType.DECIMAL: "Decimal", 256 exp.DType.DECIMAL32: "Decimal32", 257 exp.DType.DECIMAL64: "Decimal64", 258 exp.DType.DECIMAL128: "Decimal128", 259 exp.DType.DECIMAL256: "Decimal256", 260 exp.DType.TIMESTAMP: "DateTime", 261 exp.DType.TIMESTAMPNTZ: "DateTime", 262 exp.DType.TIMESTAMPTZ: "DateTime", 263 exp.DType.DOUBLE: "Float64", 264 exp.DType.ENUM: "Enum", 265 exp.DType.ENUM8: "Enum8", 266 exp.DType.ENUM16: "Enum16", 267 exp.DType.FIXEDSTRING: "FixedString", 268 exp.DType.FLOAT: "Float32", 269 exp.DType.INT: "Int32", 270 exp.DType.MEDIUMINT: "Int32", 271 exp.DType.INT128: "Int128", 272 exp.DType.INT256: "Int256", 273 exp.DType.LOWCARDINALITY: "LowCardinality", 274 exp.DType.MAP: "Map", 275 exp.DType.NESTED: "Nested", 276 exp.DType.NOTHING: "Nothing", 277 exp.DType.SMALLINT: "Int16", 278 exp.DType.STRUCT: "Tuple", 279 exp.DType.TINYINT: "Int8", 280 exp.DType.UBIGINT: "UInt64", 281 exp.DType.UINT: "UInt32", 282 exp.DType.UINT128: "UInt128", 283 exp.DType.UINT256: "UInt256", 284 exp.DType.USMALLINT: "UInt16", 285 exp.DType.UTINYINT: "UInt8", 286 exp.DType.IPV4: "IPv4", 287 exp.DType.IPV6: "IPv6", 288 exp.DType.POINT: "Point", 289 exp.DType.RING: "Ring", 290 exp.DType.LINESTRING: "LineString", 291 exp.DType.MULTILINESTRING: "MultiLineString", 292 exp.DType.POLYGON: "Polygon", 293 exp.DType.MULTIPOLYGON: "MultiPolygon", 294 exp.DType.AGGREGATEFUNCTION: "AggregateFunction", 295 exp.DType.SIMPLEAGGREGATEFUNCTION: "SimpleAggregateFunction", 296 exp.DType.DYNAMIC: "Dynamic", 297 } 298 299 TRANSFORMS = { 300 **{k: v for k, v in generator.Generator.TRANSFORMS.items() if k != exp.AutoRefreshProperty}, 301 exp.AnyValue: rename_func("any"), 302 exp.ApproxDistinct: rename_func("uniq"), 303 exp.ApproxQuantile: unsupported_args("accuracy", "weight", "error_tolerance")( 304 _quantile_sql 305 ), 306 exp.ArrayDistinct: rename_func("arrayDistinct"), 307 exp.ArrayConcat: rename_func("arrayConcat"), 308 exp.ArrayContains: rename_func("has"), 309 exp.ArrayFilter: lambda self, e: self.func("arrayFilter", e.expression, e.this), 310 exp.Transform: lambda self, e: self.func("arrayMap", e.expression, e.this), 311 exp.ArrayReverse: rename_func("arrayReverse"), 312 exp.ArraySort: _array_sort_sql, 313 exp.ArraySlice: rename_func("arraySlice"), 314 exp.ArraySum: rename_func("arraySum"), 315 exp.ArrayMax: rename_func("arrayMax"), 316 exp.ArrayMin: rename_func("arrayMin"), 317 exp.ArgMax: arg_max_or_min_no_count("argMax"), 318 exp.ArgMin: arg_max_or_min_no_count("argMin"), 319 exp.Array: inline_array_sql, 320 exp.BitwiseAndAgg: rename_func("groupBitAnd"), 321 exp.BitwiseOrAgg: rename_func("groupBitOr"), 322 exp.BitwiseXorAgg: rename_func("groupBitXor"), 323 exp.CityHash64: rename_func("cityHash64"), 324 exp.CastToStrType: rename_func("CAST"), 325 exp.CurrentDatabase: rename_func("CURRENT_DATABASE"), 326 exp.CurrentSchemas: rename_func("CURRENT_SCHEMAS"), 327 exp.CountIf: rename_func("countIf"), 328 exp.CosineDistance: rename_func("cosineDistance"), 329 exp.CompressColumnConstraint: lambda self, e: ( 330 f"CODEC({self.expressions(e, key='this', flat=True)})" 331 ), 332 exp.ComputedColumnConstraint: lambda self, e: ( 333 f"{'MATERIALIZED' if e.args.get('persisted') else 'ALIAS'} {self.sql(e, 'this')}" 334 ), 335 exp.CurrentDate: lambda self, e: self.func("CURRENT_DATE"), 336 exp.CurrentVersion: rename_func("VERSION"), 337 exp.DateAdd: _datetime_delta_sql("DATE_ADD"), 338 exp.DateDiff: _datetime_delta_sql("DATE_DIFF"), 339 exp.DateStrToDate: rename_func("toDate"), 340 exp.DateSub: _datetime_delta_sql("DATE_SUB"), 341 exp.DayOfMonth: rename_func("toDayOfMonth"), 342 exp.DayOfWeekIso: rename_func("toDayOfWeek"), 343 exp.DayOfYear: rename_func("toDayOfYear"), 344 exp.Explode: rename_func("arrayJoin"), 345 exp.FarmFingerprint: rename_func("farmFingerprint64"), 346 exp.Final: lambda self, e: f"{self.sql(e, 'this')} FINAL", 347 exp.IsInf: rename_func("isInfinite"), 348 exp.IsNan: rename_func("isNaN"), 349 exp.JarowinklerSimilarity: jarowinkler_similarity("jaroWinklerSimilarity"), 350 exp.JSONCast: _json_cast_sql, 351 exp.JSONExtract: json_extract_segments("JSONExtractRaw", quoted_index=False), 352 exp.JSONExtractScalar: json_extract_segments("JSONExtractString", quoted_index=False), 353 exp.JSONPathKey: json_path_key_only_name, 354 exp.JSONPathRoot: lambda *_: "", 355 exp.Length: length_or_char_length_sql, 356 exp.LogicalAnd: lambda self, e: self.func("minOrNull", e.this.neq(0)), 357 exp.LogicalOr: lambda self, e: self.func("maxOrNull", e.this.neq(0)), 358 exp.Map: _map_sql, 359 exp.Median: rename_func("median"), 360 exp.Nullif: rename_func("nullIf"), 361 exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}", 362 exp.Pivot: no_pivot_sql, 363 exp.Quantile: _quantile_sql, 364 exp.RegexpLike: lambda self, e: self.func("match", e.this, e.expression), 365 exp.Rand: rename_func("randCanonical"), 366 exp.StartsWith: rename_func("startsWith"), 367 exp.Struct: rename_func("tuple"), 368 exp.Trunc: rename_func("trunc"), 369 exp.EndsWith: rename_func("endsWith"), 370 exp.EuclideanDistance: rename_func("L2Distance"), 371 exp.StrPosition: lambda self, e: strposition_sql( 372 self, 373 e, 374 func_name="POSITION", 375 supports_position=True, 376 use_ansi_position=False, 377 ), 378 exp.TimeToStr: lambda self, e: self.func( 379 "formatDateTime", 380 e.this.this if isinstance(e.this, exp.TsOrDsToTimestamp) else e.this, 381 self.format_time(e), 382 e.args.get("zone"), 383 ), 384 exp.TimeStrToTime: _timestrtotime_sql, 385 exp.TimestampAdd: _datetime_delta_sql("TIMESTAMP_ADD"), 386 exp.TimestampSub: _datetime_delta_sql("TIMESTAMP_SUB"), 387 exp.Typeof: rename_func("toTypeName"), 388 exp.VarMap: _map_sql, 389 exp.Xor: lambda self, e: self.func("xor", e.this, e.expression), 390 exp.MD5Digest: rename_func("MD5"), 391 exp.MD5: lambda self, e: self.func("LOWER", self.func("HEX", self.func("MD5", e.this))), 392 exp.SHA: lambda self, e: self.func("LOWER", self.func("HEX", self.func("SHA1", e.this))), 393 exp.SHA1Digest: rename_func("SHA1"), 394 exp.SHA2: lambda self, e: self.func("LOWER", self.func("HEX", sha256_sql(self, e))), 395 exp.SHA2Digest: sha2_digest_sql, 396 exp.Split: lambda self, e: self.func( 397 "splitByString", e.args.get("expression"), e.this, e.args.get("limit") 398 ), 399 exp.RegexpSplit: lambda self, e: self.func( 400 "splitByRegexp", e.args.get("expression"), e.this, e.args.get("limit") 401 ), 402 exp.UnixToTime: _unix_to_time_sql, 403 exp.Trim: lambda self, e: trim_sql(self, e, default_trim_type="BOTH"), 404 exp.VariancePop: rename_func("varPop"), 405 exp.WeekOfYear: rename_func("toISOWeek"), 406 exp.YearOfWeekIso: rename_func("toISOYear"), 407 exp.SchemaCommentProperty: lambda self, e: self.naked_property(e), 408 exp.Stddev: rename_func("stddevSamp"), 409 exp.Chr: rename_func("CHAR"), 410 exp.Lag: rename_func("lag"), 411 exp.Lead: rename_func("lead"), 412 exp.Levenshtein: unsupported_args("ins_cost", "del_cost", "sub_cost", "max_dist")( 413 rename_func("editDistance") 414 ), 415 exp.ParseDatetime: lambda self, e: self.func( 416 "parseDateTime", e.this, self.format_time(e), e.args.get("zone") 417 ), 418 } 419 420 PROPERTIES_LOCATION = { 421 **generator.Generator.PROPERTIES_LOCATION, 422 exp.AutoRefreshProperty: exp.Properties.Location.POST_NAME, 423 exp.DefinerProperty: exp.Properties.Location.POST_SCHEMA, 424 exp.OnCluster: exp.Properties.Location.POST_NAME, 425 exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA, 426 exp.ToTableProperty: exp.Properties.Location.POST_NAME, 427 exp.UuidProperty: exp.Properties.Location.POST_NAME, 428 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 429 } 430 431 # There's no list in docs, but it can be found in Clickhouse code 432 # see `ClickHouse/src/Parsers/ParserCreate*.cpp` 433 ON_CLUSTER_TARGETS: t.ClassVar = { 434 "SCHEMA", # Transpiled CREATE SCHEMA may have OnCluster property set 435 "DATABASE", 436 "TABLE", 437 "VIEW", 438 "DICTIONARY", 439 "INDEX", 440 "FUNCTION", 441 "NAMED COLLECTION", 442 } 443 444 # https://clickhouse.com/docs/en/sql-reference/data-types/nullable 445 NON_NULLABLE_TYPES: t.ClassVar = { 446 exp.DType.ARRAY, 447 exp.DType.MAP, 448 exp.DType.STRUCT, 449 exp.DType.POINT, 450 exp.DType.RING, 451 exp.DType.LINESTRING, 452 exp.DType.MULTILINESTRING, 453 exp.DType.POLYGON, 454 exp.DType.MULTIPOLYGON, 455 } 456 457 def dayofweek_sql(self, expression: exp.DayOfWeek) -> str: 458 return self.func( 459 "toDayOfWeek", expression.this, "2" if expression.args.get("zero_based") else "3" 460 ) 461 462 def arrayremove_sql(self, expression: exp.ArrayRemove) -> str: 463 return remove_from_array_using_filter( 464 self, 465 expression, 466 keep=lambda element, target: exp.ArrayContains( 467 this=exp.array(target), expression=element 468 ).not_(), 469 supports_nullable_arrays=False, 470 ) 471 472 def dot_sql(self, expression: exp.Dot) -> str: 473 if depth := expression.args.get("subcolumn_depth"): 474 root: exp.Expr = expression 475 fields: list[str] = [] 476 while isinstance(root, exp.Dot) and len(fields) < depth: 477 fields.append(root.expression.name) 478 root = root.this 479 480 # expr.a.b performs two lookups, while a column path resolves the entire subcolumn. 481 if len(fields) == depth and not isinstance(root, exp.Column): 482 return self.func( 483 "getSubcolumn", root, exp.Literal.string(".".join(reversed(fields))) 484 ) 485 486 return super().dot_sql(expression) 487 488 @unsupported_args("json_scope") 489 def contains_sql(self, expression: exp.Contains) -> str: 490 # ClickHouse has no CONTAINS; keep the parentheses only where the parent needs them 491 result = exp.paren( 492 exp.StrPosition(this=expression.this, substr=expression.expression) > 0, copy=False 493 ) 494 result.parent = expression.parent 495 return self.sql(simplify_parens(result, self.dialect)) 496 497 def groupconcat_sql(self, expression: exp.GroupConcat) -> str: 498 this = expression.this 499 separator = expression.args.get("separator") 500 501 if isinstance(this, exp.Limit) and this.this: 502 limit = this 503 this = limit.this.pop() 504 return self.sql( 505 exp.ParameterizedAgg( 506 this="groupConcat", 507 params=[this], 508 expressions=[separator, limit.expression], 509 ) 510 ) 511 512 if separator: 513 return self.sql( 514 exp.ParameterizedAgg( 515 this="groupConcat", 516 params=[this], 517 expressions=[separator], 518 ) 519 ) 520 521 return self.func("groupConcat", this) 522 523 def select_sql(self, expression: exp.Select) -> str: 524 limit = expression.args.get("limit") 525 if isinstance(limit, exp.Fetch) and not expression.args.get("order"): 526 count = limit.args.get("count") 527 expression.set( 528 "limit", exp.Limit(expression=count if count is not None else exp.Literal.number(1)) 529 ) 530 return super().select_sql(expression) 531 532 def offset_sql(self, expression: exp.Offset) -> str: 533 offset = super().offset_sql(expression) 534 535 # OFFSET ... FETCH syntax requires a "ROW" or "ROWS" keyword 536 # https://clickhouse.com/docs/sql-reference/statements/select/offset 537 parent = expression.parent 538 if isinstance(parent, exp.Select) and isinstance(parent.args.get("limit"), exp.Fetch): 539 offset = f"{offset} ROWS" 540 541 return offset 542 543 def strtodate_sql(self, expression: exp.StrToDate) -> str: 544 strtodate_sql = self.function_fallback_sql(expression) 545 546 if not isinstance(expression.parent, exp.Cast): 547 # StrToDate returns DATEs in other dialects (eg. postgres), so 548 # this branch aims to improve the transpilation to clickhouse 549 return self.cast_sql(exp.cast(expression, "DATE")) 550 551 return strtodate_sql 552 553 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 554 this = expression.this 555 556 if isinstance(this, exp.StrToDate) and expression.to == exp.DType.DATETIME.into_expr(): 557 return self.sql(this) 558 559 this = this.unnest() 560 if ( 561 isinstance(this, exp.JSONExtract) 562 and this.args.get("requires_json") 563 and expression.to.is_type(*exp.DataType.TEXT_TYPES) 564 ): 565 return self.func("JSONExtract", this, exp.Literal.string("Nullable(String)")) 566 567 return super().cast_sql(expression, safe_prefix=safe_prefix) 568 569 def trycast_sql(self, expression: exp.TryCast) -> str: 570 dtype = expression.to 571 if not dtype.is_type(*self.NON_NULLABLE_TYPES, check_nullable=True): 572 # Casting x into Nullable(T) appears to behave similarly to TRY_CAST(x AS T) 573 dtype.set("nullable", True) 574 575 return super().cast_sql(expression) 576 577 def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str: 578 this = self.json_path_part(expression.this) 579 return str(int(this) + 1) if is_int(this) else this 580 581 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 582 return f"AS {self.sql(expression, 'this')}" 583 584 def _any_to_has( 585 self, 586 expression: exp.EQ | exp.NEQ, 587 default: t.Callable[[t.Any], str], 588 prefix: str = "", 589 ) -> str: 590 if isinstance(expression.left, exp.Any): 591 arr = expression.left 592 this = expression.right 593 elif isinstance(expression.right, exp.Any): 594 arr = expression.right 595 this = expression.left 596 else: 597 return default(expression) 598 599 if isinstance(arr.this, exp.Query): 600 return default(expression) 601 602 return prefix + self.func("has", arr.this.unnest(), this) 603 604 def eq_sql(self, expression: exp.EQ) -> str: 605 return self._any_to_has(expression, super().eq_sql) 606 607 def neq_sql(self, expression: exp.NEQ) -> str: 608 return self._any_to_has(expression, super().neq_sql, "NOT ") 609 610 def regexpcount_sql(self, expression: exp.RegexpCount) -> str: 611 this = expression.this 612 pattern = expression.expression 613 position = expression.args.get("position") 614 parameters = expression.args.get("parameters") 615 616 if position: 617 # SUBSTRING counts bytes in ClickHouse, the position counts characters 618 this = self.func("substringUTF8", this, position) 619 620 if parameters: 621 flags = parameters.name if parameters.is_string else "" 622 if not parameters.is_string or set(flags) - set("cims"): 623 self.unsupported("Only literal 'c', 'i', 'm' and 's' regexp flags are supported") 624 # "c" (case-sensitive) is the default, and the last of "c" and "i" wins 625 if flags.rfind("c") > flags.rfind("i"): 626 flags = flags.replace("i", "") 627 flags = "".join(f for f in flags if f in "ims") 628 if flags: 629 # countMatches has no flags argument, so they are embedded in the pattern 630 pattern = self.func("CONCAT", exp.Literal.string(f"(?{flags})"), pattern) 631 632 return self.func("countMatches", this, pattern) 633 634 def regexpilike_sql(self, expression: exp.RegexpILike) -> str: 635 # Manually add a flag to make the search case-insensitive 636 regex = self.func("CONCAT", "'(?i)'", expression.expression) 637 return self.func("match", expression.this, regex) 638 639 def datatype_sql(self, expression: exp.DataType) -> str: 640 # String is the standard ClickHouse type, every other variant is just an alias. 641 # Additionally, any supplied length parameter will be ignored. 642 # 643 # https://clickhouse.com/docs/en/sql-reference/data-types/string 644 if expression.this in self.STRING_TYPE_MAPPING: 645 dtype = "String" 646 else: 647 dtype = super().datatype_sql(expression) 648 649 # This section changes the type to `Nullable(...)` if the following conditions hold: 650 # - It's marked as nullable - this ensures we won't wrap ClickHouse types with `Nullable` 651 # and change their semantics 652 # - It's not the key type of a `Map`. This is because ClickHouse enforces the following 653 # constraint: "Type of Map key must be a type, that can be represented by integer or 654 # String or FixedString (possibly LowCardinality) or UUID or IPv6" 655 # - It's not a composite type, e.g. `Nullable(Array(...))` is not a valid type 656 parent = expression.parent 657 nullable = expression.args.get("nullable") 658 if nullable is True or ( 659 nullable is None 660 and not ( 661 isinstance(parent, exp.DataType) 662 and parent.is_type(exp.DType.MAP, check_nullable=True) 663 and expression.index in (None, 0) 664 ) 665 and not expression.is_type(*self.NON_NULLABLE_TYPES, check_nullable=True) 666 ): 667 dtype = f"Nullable({dtype})" 668 669 return dtype 670 671 def cte_sql(self, expression: exp.CTE) -> str: 672 if expression.args.get("scalar"): 673 this = self.sql(expression, "this") 674 alias = self.sql(expression, "alias") 675 return f"{this} AS {alias}" 676 677 return super().cte_sql(expression) 678 679 def after_limit_modifiers(self, expression: exp.Expr) -> list[str]: 680 return super().after_limit_modifiers(expression) + [ 681 ( 682 self.seg("SETTINGS ") + self.expressions(expression, key="settings", flat=True) 683 if expression.args.get("settings") 684 else "" 685 ), 686 ( 687 self.seg("FORMAT ") + self.sql(expression, "format") 688 if expression.args.get("format") 689 else "" 690 ), 691 ] 692 693 def placeholder_sql(self, expression: exp.Placeholder) -> str: 694 return f"{{{expression.name}: {self.sql(expression, 'kind')}}}" 695 696 def oncluster_sql(self, expression: exp.OnCluster) -> str: 697 return f"ON CLUSTER {self.sql(expression, 'this')}" 698 699 def _refresh_interval_sql(self, expression: exp.Expr) -> str: 700 if isinstance(expression, exp.Add): 701 return f"{self._refresh_interval_sql(expression.this)} {self._refresh_interval_sql(expression.expression)}" 702 return self.sql(expression.assert_is(exp.Interval)) 703 704 def autorefreshproperty_sql(self, expression: exp.AutoRefreshProperty) -> str: 705 cadence = self.sql(expression, "cadence") 706 interval = expression.this 707 schedule = ( 708 f" {cadence} {self._refresh_interval_sql(interval)}" if cadence and interval else "" 709 ) 710 offset = expression.args.get("offset") 711 offset = f" OFFSET {self._refresh_interval_sql(offset)}" if offset else "" 712 randomize = expression.args.get("randomize") 713 randomize = f" RANDOMIZE FOR {self._refresh_interval_sql(randomize)}" if randomize else "" 714 dependencies = self.expressions(expression, flat=True) 715 dependencies = f" DEPENDS ON {dependencies}" if dependencies else "" 716 settings = self.sql(expression, "settings") 717 settings = f" {settings}" if settings else "" 718 append = " APPEND" if expression.args.get("append") else "" 719 720 return f"REFRESH{schedule}{offset}{randomize}{dependencies}{settings}{append}" 721 722 def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str: 723 if expression.kind in self.ON_CLUSTER_TARGETS and locations.get( 724 exp.Properties.Location.POST_NAME 725 ): 726 this_name = self.sql( 727 expression.this if isinstance(expression.this, exp.Schema) else expression, 728 "this", 729 ) 730 this_properties = " ".join( 731 [self.sql(prop) for prop in locations[exp.Properties.Location.POST_NAME]] 732 ) 733 this_schema = self.schema_columns_sql(expression.this) 734 this_schema = f"{self.sep()}{this_schema}" if this_schema else "" 735 736 return f"{this_name}{self.sep()}{this_properties}{this_schema}" 737 738 return super().createable_sql(expression, locations) 739 740 def create_sql(self, expression: exp.Create) -> str: 741 # The comment property comes last in CTAS statements, i.e. after the query 742 query = expression.expression 743 if isinstance(query, exp.Query): 744 comment_prop = expression.find(exp.SchemaCommentProperty) 745 if comment_prop: 746 comment_prop.pop() 747 if not isinstance(query, exp.Subquery): 748 query.replace(exp.paren(query)) 749 else: 750 comment_prop = None 751 752 create_sql = super().create_sql(expression) 753 754 comment_sql = self.sql(comment_prop) 755 comment_sql = f" {comment_sql}" if comment_sql else "" 756 757 return f"{create_sql}{comment_sql}" 758 759 def prewhere_sql(self, expression: exp.PreWhere) -> str: 760 this = self.indent(self.sql(expression, "this")) 761 return f"{self.seg('PREWHERE')}{self.sep()}{this}" 762 763 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 764 this = self.sql(expression, "this") 765 this = f" {this}" if this else "" 766 expr = self.sql(expression, "expression") 767 expr = f" {expr}" if expr else "" 768 index_type = self.sql(expression, "index_type") 769 index_type = f" TYPE {index_type}" if index_type else "" 770 granularity = self.sql(expression, "granularity") 771 granularity = f" GRANULARITY {granularity}" if granularity else "" 772 773 return f"INDEX{this}{expr}{index_type}{granularity}" 774 775 def partition_sql(self, expression: exp.Partition) -> str: 776 return f"PARTITION {self.expressions(expression, flat=True)}" 777 778 def partitionid_sql(self, expression: exp.PartitionId) -> str: 779 return f"ID {self.sql(expression.this)}" 780 781 def replacepartition_sql(self, expression: exp.ReplacePartition) -> str: 782 return f"REPLACE {self.sql(expression.expression)} FROM {self.sql(expression, 'source')}" 783 784 def projectiondef_sql(self, expression: exp.ProjectionDef) -> str: 785 return f"PROJECTION {self.sql(expression.this)} {self.wrap(expression.expression)}" 786 787 def is_sql(self, expression: exp.Is) -> str: 788 is_sql = super().is_sql(expression) 789 790 if isinstance(expression.parent, exp.Not): 791 # value IS NOT NULL -> NOT (value IS NULL) 792 is_sql = self.wrap(is_sql) 793 794 return is_sql 795 796 def in_sql(self, expression: exp.In) -> str: 797 in_sql = super().in_sql(expression) 798 799 if isinstance(expression.parent, exp.Not) and expression.args.get("is_global"): 800 in_sql = in_sql.replace("GLOBAL IN", "GLOBAL NOT IN", 1) 801 802 return in_sql 803 804 def not_sql(self, expression: exp.Not) -> str: 805 if isinstance(expression.this, exp.In): 806 if expression.this.args.get("is_global"): 807 # let `GLOBAL IN` child interpose `NOT` 808 return self.sql(expression, "this") 809 810 expression.set("this", exp.paren(expression.this, copy=False)) 811 812 return super().not_sql(expression) 813 814 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 815 # If the VALUES clause contains tuples of expressions, we need to treat it 816 # as a table since Clickhouse will automatically alias it as such. 817 alias = expression.args.get("alias") 818 819 if alias and alias.args.get("columns") and expression.expressions: 820 values = expression.expressions[0].expressions 821 values_as_table = any(isinstance(value, exp.Tuple) for value in values) 822 else: 823 values_as_table = True 824 825 # An unparenthesized VALUES in FROM is the values() table function, which takes a single 826 # argument list, so a multi-row VALUES relation must be parenthesized to parse 827 if ( 828 values_as_table 829 and len(expression.expressions) > 1 830 and (alias or isinstance(expression.parent, (exp.From, exp.Join, exp.Table))) 831 ): 832 values = f"(VALUES{self.seg('')}{self.expressions(expression)})" 833 values = self.query_modifiers(expression, values) 834 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 835 alias_sql = self.sql(alias) 836 return f"{values} AS {alias_sql}{pivots}" if alias_sql else f"{values}{pivots}" 837 838 return super().values_sql(expression, values_as_table=values_as_table) 839 840 def timestamptrunc_sql(self, expression: exp.DateTrunc | exp.TimestampTrunc) -> str: 841 unit = weekstart_unit_to_str(self, expression) 842 # https://clickhouse.com/docs/whats-new/changelog/2023#improvement 843 if self.dialect.version < (23, 12) and unit and unit.is_string: 844 unit = exp.Literal.string(unit.name.lower()) 845 return self.func("dateTrunc", unit, expression.this, expression.args.get("zone")) 846 847 def datetrunc_sql(self, expression: exp.DateTrunc) -> str: 848 return self.timestamptrunc_sql(expression)
183class ClickHouseGenerator(generator.Generator): 184 BYTE_STRING_FUNCTION = "unhex" 185 SELECT_KINDS = () 186 TRY_SUPPORTED = False 187 SUPPORTS_UESCAPE = False 188 SUPPORTS_DECODE_CASE = False 189 SUPPORTS_NESTED_JSON_SELECT = True 190 191 AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS 192 193 QUERY_HINTS = False 194 STRUCT_DELIMITER = ("(", ")") 195 NVL2_SUPPORTED = False 196 ALTER_SET_TYPE = "TYPE" 197 SUPPORTS_ALTER_COLUMN_IF_EXISTS = True 198 TABLESAMPLE_REQUIRES_PARENS = False 199 TABLESAMPLE_SIZE_IS_ROWS = False 200 TABLESAMPLE_KEYWORDS = "SAMPLE" 201 LAST_DAY_SUPPORTS_DATE_PART = False 202 CAN_IMPLEMENT_ARRAY_ANY = True 203 SUPPORTS_TO_NUMBER = False 204 JOIN_HINTS = False 205 TABLE_HINTS = False 206 MATCH_CONDITION_IN_ON = True 207 GROUPINGS_SEP = "" 208 SET_OP_MODIFIERS = False 209 SET_OP_LIMITS = True 210 ARRAY_SIZE_NAME = "LENGTH" 211 VARIANCE_NAME = "varSamp" 212 WRAP_DERIVED_VALUES = False 213 AUTO_REFRESH_BARE_INTERVALS = True 214 215 STRING_TYPE_MAPPING: t.ClassVar = { 216 exp.DType.BLOB: "String", 217 exp.DType.CHAR: "String", 218 exp.DType.LONGBLOB: "String", 219 exp.DType.LONGTEXT: "String", 220 exp.DType.MEDIUMBLOB: "String", 221 exp.DType.MEDIUMTEXT: "String", 222 exp.DType.TINYBLOB: "String", 223 exp.DType.TINYTEXT: "String", 224 exp.DType.TEXT: "String", 225 exp.DType.VARBINARY: "String", 226 exp.DType.VARCHAR: "String", 227 } 228 229 SUPPORTED_JSON_PATH_PARTS = { 230 exp.JSONPathKey, 231 exp.JSONPathRoot, 232 exp.JSONPathSubscript, 233 } 234 235 TYPE_MAPPING = { 236 **generator.Generator.TYPE_MAPPING, 237 exp.DType.BLOB: "String", 238 exp.DType.CHAR: "String", 239 exp.DType.LONGBLOB: "String", 240 exp.DType.LONGTEXT: "String", 241 exp.DType.MEDIUMBLOB: "String", 242 exp.DType.MEDIUMTEXT: "String", 243 exp.DType.TINYBLOB: "String", 244 exp.DType.TINYTEXT: "String", 245 exp.DType.TEXT: "String", 246 exp.DType.VARBINARY: "String", 247 exp.DType.VARCHAR: "String", 248 exp.DType.ARRAY: "Array", 249 exp.DType.BOOLEAN: "Bool", 250 exp.DType.BIGINT: "Int64", 251 exp.DType.DATE32: "Date32", 252 exp.DType.DATETIME: "DateTime", 253 exp.DType.DATETIME2: "DateTime", 254 exp.DType.SMALLDATETIME: "DateTime", 255 exp.DType.DATETIME64: "DateTime64", 256 exp.DType.DECIMAL: "Decimal", 257 exp.DType.DECIMAL32: "Decimal32", 258 exp.DType.DECIMAL64: "Decimal64", 259 exp.DType.DECIMAL128: "Decimal128", 260 exp.DType.DECIMAL256: "Decimal256", 261 exp.DType.TIMESTAMP: "DateTime", 262 exp.DType.TIMESTAMPNTZ: "DateTime", 263 exp.DType.TIMESTAMPTZ: "DateTime", 264 exp.DType.DOUBLE: "Float64", 265 exp.DType.ENUM: "Enum", 266 exp.DType.ENUM8: "Enum8", 267 exp.DType.ENUM16: "Enum16", 268 exp.DType.FIXEDSTRING: "FixedString", 269 exp.DType.FLOAT: "Float32", 270 exp.DType.INT: "Int32", 271 exp.DType.MEDIUMINT: "Int32", 272 exp.DType.INT128: "Int128", 273 exp.DType.INT256: "Int256", 274 exp.DType.LOWCARDINALITY: "LowCardinality", 275 exp.DType.MAP: "Map", 276 exp.DType.NESTED: "Nested", 277 exp.DType.NOTHING: "Nothing", 278 exp.DType.SMALLINT: "Int16", 279 exp.DType.STRUCT: "Tuple", 280 exp.DType.TINYINT: "Int8", 281 exp.DType.UBIGINT: "UInt64", 282 exp.DType.UINT: "UInt32", 283 exp.DType.UINT128: "UInt128", 284 exp.DType.UINT256: "UInt256", 285 exp.DType.USMALLINT: "UInt16", 286 exp.DType.UTINYINT: "UInt8", 287 exp.DType.IPV4: "IPv4", 288 exp.DType.IPV6: "IPv6", 289 exp.DType.POINT: "Point", 290 exp.DType.RING: "Ring", 291 exp.DType.LINESTRING: "LineString", 292 exp.DType.MULTILINESTRING: "MultiLineString", 293 exp.DType.POLYGON: "Polygon", 294 exp.DType.MULTIPOLYGON: "MultiPolygon", 295 exp.DType.AGGREGATEFUNCTION: "AggregateFunction", 296 exp.DType.SIMPLEAGGREGATEFUNCTION: "SimpleAggregateFunction", 297 exp.DType.DYNAMIC: "Dynamic", 298 } 299 300 TRANSFORMS = { 301 **{k: v for k, v in generator.Generator.TRANSFORMS.items() if k != exp.AutoRefreshProperty}, 302 exp.AnyValue: rename_func("any"), 303 exp.ApproxDistinct: rename_func("uniq"), 304 exp.ApproxQuantile: unsupported_args("accuracy", "weight", "error_tolerance")( 305 _quantile_sql 306 ), 307 exp.ArrayDistinct: rename_func("arrayDistinct"), 308 exp.ArrayConcat: rename_func("arrayConcat"), 309 exp.ArrayContains: rename_func("has"), 310 exp.ArrayFilter: lambda self, e: self.func("arrayFilter", e.expression, e.this), 311 exp.Transform: lambda self, e: self.func("arrayMap", e.expression, e.this), 312 exp.ArrayReverse: rename_func("arrayReverse"), 313 exp.ArraySort: _array_sort_sql, 314 exp.ArraySlice: rename_func("arraySlice"), 315 exp.ArraySum: rename_func("arraySum"), 316 exp.ArrayMax: rename_func("arrayMax"), 317 exp.ArrayMin: rename_func("arrayMin"), 318 exp.ArgMax: arg_max_or_min_no_count("argMax"), 319 exp.ArgMin: arg_max_or_min_no_count("argMin"), 320 exp.Array: inline_array_sql, 321 exp.BitwiseAndAgg: rename_func("groupBitAnd"), 322 exp.BitwiseOrAgg: rename_func("groupBitOr"), 323 exp.BitwiseXorAgg: rename_func("groupBitXor"), 324 exp.CityHash64: rename_func("cityHash64"), 325 exp.CastToStrType: rename_func("CAST"), 326 exp.CurrentDatabase: rename_func("CURRENT_DATABASE"), 327 exp.CurrentSchemas: rename_func("CURRENT_SCHEMAS"), 328 exp.CountIf: rename_func("countIf"), 329 exp.CosineDistance: rename_func("cosineDistance"), 330 exp.CompressColumnConstraint: lambda self, e: ( 331 f"CODEC({self.expressions(e, key='this', flat=True)})" 332 ), 333 exp.ComputedColumnConstraint: lambda self, e: ( 334 f"{'MATERIALIZED' if e.args.get('persisted') else 'ALIAS'} {self.sql(e, 'this')}" 335 ), 336 exp.CurrentDate: lambda self, e: self.func("CURRENT_DATE"), 337 exp.CurrentVersion: rename_func("VERSION"), 338 exp.DateAdd: _datetime_delta_sql("DATE_ADD"), 339 exp.DateDiff: _datetime_delta_sql("DATE_DIFF"), 340 exp.DateStrToDate: rename_func("toDate"), 341 exp.DateSub: _datetime_delta_sql("DATE_SUB"), 342 exp.DayOfMonth: rename_func("toDayOfMonth"), 343 exp.DayOfWeekIso: rename_func("toDayOfWeek"), 344 exp.DayOfYear: rename_func("toDayOfYear"), 345 exp.Explode: rename_func("arrayJoin"), 346 exp.FarmFingerprint: rename_func("farmFingerprint64"), 347 exp.Final: lambda self, e: f"{self.sql(e, 'this')} FINAL", 348 exp.IsInf: rename_func("isInfinite"), 349 exp.IsNan: rename_func("isNaN"), 350 exp.JarowinklerSimilarity: jarowinkler_similarity("jaroWinklerSimilarity"), 351 exp.JSONCast: _json_cast_sql, 352 exp.JSONExtract: json_extract_segments("JSONExtractRaw", quoted_index=False), 353 exp.JSONExtractScalar: json_extract_segments("JSONExtractString", quoted_index=False), 354 exp.JSONPathKey: json_path_key_only_name, 355 exp.JSONPathRoot: lambda *_: "", 356 exp.Length: length_or_char_length_sql, 357 exp.LogicalAnd: lambda self, e: self.func("minOrNull", e.this.neq(0)), 358 exp.LogicalOr: lambda self, e: self.func("maxOrNull", e.this.neq(0)), 359 exp.Map: _map_sql, 360 exp.Median: rename_func("median"), 361 exp.Nullif: rename_func("nullIf"), 362 exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}", 363 exp.Pivot: no_pivot_sql, 364 exp.Quantile: _quantile_sql, 365 exp.RegexpLike: lambda self, e: self.func("match", e.this, e.expression), 366 exp.Rand: rename_func("randCanonical"), 367 exp.StartsWith: rename_func("startsWith"), 368 exp.Struct: rename_func("tuple"), 369 exp.Trunc: rename_func("trunc"), 370 exp.EndsWith: rename_func("endsWith"), 371 exp.EuclideanDistance: rename_func("L2Distance"), 372 exp.StrPosition: lambda self, e: strposition_sql( 373 self, 374 e, 375 func_name="POSITION", 376 supports_position=True, 377 use_ansi_position=False, 378 ), 379 exp.TimeToStr: lambda self, e: self.func( 380 "formatDateTime", 381 e.this.this if isinstance(e.this, exp.TsOrDsToTimestamp) else e.this, 382 self.format_time(e), 383 e.args.get("zone"), 384 ), 385 exp.TimeStrToTime: _timestrtotime_sql, 386 exp.TimestampAdd: _datetime_delta_sql("TIMESTAMP_ADD"), 387 exp.TimestampSub: _datetime_delta_sql("TIMESTAMP_SUB"), 388 exp.Typeof: rename_func("toTypeName"), 389 exp.VarMap: _map_sql, 390 exp.Xor: lambda self, e: self.func("xor", e.this, e.expression), 391 exp.MD5Digest: rename_func("MD5"), 392 exp.MD5: lambda self, e: self.func("LOWER", self.func("HEX", self.func("MD5", e.this))), 393 exp.SHA: lambda self, e: self.func("LOWER", self.func("HEX", self.func("SHA1", e.this))), 394 exp.SHA1Digest: rename_func("SHA1"), 395 exp.SHA2: lambda self, e: self.func("LOWER", self.func("HEX", sha256_sql(self, e))), 396 exp.SHA2Digest: sha2_digest_sql, 397 exp.Split: lambda self, e: self.func( 398 "splitByString", e.args.get("expression"), e.this, e.args.get("limit") 399 ), 400 exp.RegexpSplit: lambda self, e: self.func( 401 "splitByRegexp", e.args.get("expression"), e.this, e.args.get("limit") 402 ), 403 exp.UnixToTime: _unix_to_time_sql, 404 exp.Trim: lambda self, e: trim_sql(self, e, default_trim_type="BOTH"), 405 exp.VariancePop: rename_func("varPop"), 406 exp.WeekOfYear: rename_func("toISOWeek"), 407 exp.YearOfWeekIso: rename_func("toISOYear"), 408 exp.SchemaCommentProperty: lambda self, e: self.naked_property(e), 409 exp.Stddev: rename_func("stddevSamp"), 410 exp.Chr: rename_func("CHAR"), 411 exp.Lag: rename_func("lag"), 412 exp.Lead: rename_func("lead"), 413 exp.Levenshtein: unsupported_args("ins_cost", "del_cost", "sub_cost", "max_dist")( 414 rename_func("editDistance") 415 ), 416 exp.ParseDatetime: lambda self, e: self.func( 417 "parseDateTime", e.this, self.format_time(e), e.args.get("zone") 418 ), 419 } 420 421 PROPERTIES_LOCATION = { 422 **generator.Generator.PROPERTIES_LOCATION, 423 exp.AutoRefreshProperty: exp.Properties.Location.POST_NAME, 424 exp.DefinerProperty: exp.Properties.Location.POST_SCHEMA, 425 exp.OnCluster: exp.Properties.Location.POST_NAME, 426 exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA, 427 exp.ToTableProperty: exp.Properties.Location.POST_NAME, 428 exp.UuidProperty: exp.Properties.Location.POST_NAME, 429 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 430 } 431 432 # There's no list in docs, but it can be found in Clickhouse code 433 # see `ClickHouse/src/Parsers/ParserCreate*.cpp` 434 ON_CLUSTER_TARGETS: t.ClassVar = { 435 "SCHEMA", # Transpiled CREATE SCHEMA may have OnCluster property set 436 "DATABASE", 437 "TABLE", 438 "VIEW", 439 "DICTIONARY", 440 "INDEX", 441 "FUNCTION", 442 "NAMED COLLECTION", 443 } 444 445 # https://clickhouse.com/docs/en/sql-reference/data-types/nullable 446 NON_NULLABLE_TYPES: t.ClassVar = { 447 exp.DType.ARRAY, 448 exp.DType.MAP, 449 exp.DType.STRUCT, 450 exp.DType.POINT, 451 exp.DType.RING, 452 exp.DType.LINESTRING, 453 exp.DType.MULTILINESTRING, 454 exp.DType.POLYGON, 455 exp.DType.MULTIPOLYGON, 456 } 457 458 def dayofweek_sql(self, expression: exp.DayOfWeek) -> str: 459 return self.func( 460 "toDayOfWeek", expression.this, "2" if expression.args.get("zero_based") else "3" 461 ) 462 463 def arrayremove_sql(self, expression: exp.ArrayRemove) -> str: 464 return remove_from_array_using_filter( 465 self, 466 expression, 467 keep=lambda element, target: exp.ArrayContains( 468 this=exp.array(target), expression=element 469 ).not_(), 470 supports_nullable_arrays=False, 471 ) 472 473 def dot_sql(self, expression: exp.Dot) -> str: 474 if depth := expression.args.get("subcolumn_depth"): 475 root: exp.Expr = expression 476 fields: list[str] = [] 477 while isinstance(root, exp.Dot) and len(fields) < depth: 478 fields.append(root.expression.name) 479 root = root.this 480 481 # expr.a.b performs two lookups, while a column path resolves the entire subcolumn. 482 if len(fields) == depth and not isinstance(root, exp.Column): 483 return self.func( 484 "getSubcolumn", root, exp.Literal.string(".".join(reversed(fields))) 485 ) 486 487 return super().dot_sql(expression) 488 489 @unsupported_args("json_scope") 490 def contains_sql(self, expression: exp.Contains) -> str: 491 # ClickHouse has no CONTAINS; keep the parentheses only where the parent needs them 492 result = exp.paren( 493 exp.StrPosition(this=expression.this, substr=expression.expression) > 0, copy=False 494 ) 495 result.parent = expression.parent 496 return self.sql(simplify_parens(result, self.dialect)) 497 498 def groupconcat_sql(self, expression: exp.GroupConcat) -> str: 499 this = expression.this 500 separator = expression.args.get("separator") 501 502 if isinstance(this, exp.Limit) and this.this: 503 limit = this 504 this = limit.this.pop() 505 return self.sql( 506 exp.ParameterizedAgg( 507 this="groupConcat", 508 params=[this], 509 expressions=[separator, limit.expression], 510 ) 511 ) 512 513 if separator: 514 return self.sql( 515 exp.ParameterizedAgg( 516 this="groupConcat", 517 params=[this], 518 expressions=[separator], 519 ) 520 ) 521 522 return self.func("groupConcat", this) 523 524 def select_sql(self, expression: exp.Select) -> str: 525 limit = expression.args.get("limit") 526 if isinstance(limit, exp.Fetch) and not expression.args.get("order"): 527 count = limit.args.get("count") 528 expression.set( 529 "limit", exp.Limit(expression=count if count is not None else exp.Literal.number(1)) 530 ) 531 return super().select_sql(expression) 532 533 def offset_sql(self, expression: exp.Offset) -> str: 534 offset = super().offset_sql(expression) 535 536 # OFFSET ... FETCH syntax requires a "ROW" or "ROWS" keyword 537 # https://clickhouse.com/docs/sql-reference/statements/select/offset 538 parent = expression.parent 539 if isinstance(parent, exp.Select) and isinstance(parent.args.get("limit"), exp.Fetch): 540 offset = f"{offset} ROWS" 541 542 return offset 543 544 def strtodate_sql(self, expression: exp.StrToDate) -> str: 545 strtodate_sql = self.function_fallback_sql(expression) 546 547 if not isinstance(expression.parent, exp.Cast): 548 # StrToDate returns DATEs in other dialects (eg. postgres), so 549 # this branch aims to improve the transpilation to clickhouse 550 return self.cast_sql(exp.cast(expression, "DATE")) 551 552 return strtodate_sql 553 554 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 555 this = expression.this 556 557 if isinstance(this, exp.StrToDate) and expression.to == exp.DType.DATETIME.into_expr(): 558 return self.sql(this) 559 560 this = this.unnest() 561 if ( 562 isinstance(this, exp.JSONExtract) 563 and this.args.get("requires_json") 564 and expression.to.is_type(*exp.DataType.TEXT_TYPES) 565 ): 566 return self.func("JSONExtract", this, exp.Literal.string("Nullable(String)")) 567 568 return super().cast_sql(expression, safe_prefix=safe_prefix) 569 570 def trycast_sql(self, expression: exp.TryCast) -> str: 571 dtype = expression.to 572 if not dtype.is_type(*self.NON_NULLABLE_TYPES, check_nullable=True): 573 # Casting x into Nullable(T) appears to behave similarly to TRY_CAST(x AS T) 574 dtype.set("nullable", True) 575 576 return super().cast_sql(expression) 577 578 def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str: 579 this = self.json_path_part(expression.this) 580 return str(int(this) + 1) if is_int(this) else this 581 582 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 583 return f"AS {self.sql(expression, 'this')}" 584 585 def _any_to_has( 586 self, 587 expression: exp.EQ | exp.NEQ, 588 default: t.Callable[[t.Any], str], 589 prefix: str = "", 590 ) -> str: 591 if isinstance(expression.left, exp.Any): 592 arr = expression.left 593 this = expression.right 594 elif isinstance(expression.right, exp.Any): 595 arr = expression.right 596 this = expression.left 597 else: 598 return default(expression) 599 600 if isinstance(arr.this, exp.Query): 601 return default(expression) 602 603 return prefix + self.func("has", arr.this.unnest(), this) 604 605 def eq_sql(self, expression: exp.EQ) -> str: 606 return self._any_to_has(expression, super().eq_sql) 607 608 def neq_sql(self, expression: exp.NEQ) -> str: 609 return self._any_to_has(expression, super().neq_sql, "NOT ") 610 611 def regexpcount_sql(self, expression: exp.RegexpCount) -> str: 612 this = expression.this 613 pattern = expression.expression 614 position = expression.args.get("position") 615 parameters = expression.args.get("parameters") 616 617 if position: 618 # SUBSTRING counts bytes in ClickHouse, the position counts characters 619 this = self.func("substringUTF8", this, position) 620 621 if parameters: 622 flags = parameters.name if parameters.is_string else "" 623 if not parameters.is_string or set(flags) - set("cims"): 624 self.unsupported("Only literal 'c', 'i', 'm' and 's' regexp flags are supported") 625 # "c" (case-sensitive) is the default, and the last of "c" and "i" wins 626 if flags.rfind("c") > flags.rfind("i"): 627 flags = flags.replace("i", "") 628 flags = "".join(f for f in flags if f in "ims") 629 if flags: 630 # countMatches has no flags argument, so they are embedded in the pattern 631 pattern = self.func("CONCAT", exp.Literal.string(f"(?{flags})"), pattern) 632 633 return self.func("countMatches", this, pattern) 634 635 def regexpilike_sql(self, expression: exp.RegexpILike) -> str: 636 # Manually add a flag to make the search case-insensitive 637 regex = self.func("CONCAT", "'(?i)'", expression.expression) 638 return self.func("match", expression.this, regex) 639 640 def datatype_sql(self, expression: exp.DataType) -> str: 641 # String is the standard ClickHouse type, every other variant is just an alias. 642 # Additionally, any supplied length parameter will be ignored. 643 # 644 # https://clickhouse.com/docs/en/sql-reference/data-types/string 645 if expression.this in self.STRING_TYPE_MAPPING: 646 dtype = "String" 647 else: 648 dtype = super().datatype_sql(expression) 649 650 # This section changes the type to `Nullable(...)` if the following conditions hold: 651 # - It's marked as nullable - this ensures we won't wrap ClickHouse types with `Nullable` 652 # and change their semantics 653 # - It's not the key type of a `Map`. This is because ClickHouse enforces the following 654 # constraint: "Type of Map key must be a type, that can be represented by integer or 655 # String or FixedString (possibly LowCardinality) or UUID or IPv6" 656 # - It's not a composite type, e.g. `Nullable(Array(...))` is not a valid type 657 parent = expression.parent 658 nullable = expression.args.get("nullable") 659 if nullable is True or ( 660 nullable is None 661 and not ( 662 isinstance(parent, exp.DataType) 663 and parent.is_type(exp.DType.MAP, check_nullable=True) 664 and expression.index in (None, 0) 665 ) 666 and not expression.is_type(*self.NON_NULLABLE_TYPES, check_nullable=True) 667 ): 668 dtype = f"Nullable({dtype})" 669 670 return dtype 671 672 def cte_sql(self, expression: exp.CTE) -> str: 673 if expression.args.get("scalar"): 674 this = self.sql(expression, "this") 675 alias = self.sql(expression, "alias") 676 return f"{this} AS {alias}" 677 678 return super().cte_sql(expression) 679 680 def after_limit_modifiers(self, expression: exp.Expr) -> list[str]: 681 return super().after_limit_modifiers(expression) + [ 682 ( 683 self.seg("SETTINGS ") + self.expressions(expression, key="settings", flat=True) 684 if expression.args.get("settings") 685 else "" 686 ), 687 ( 688 self.seg("FORMAT ") + self.sql(expression, "format") 689 if expression.args.get("format") 690 else "" 691 ), 692 ] 693 694 def placeholder_sql(self, expression: exp.Placeholder) -> str: 695 return f"{{{expression.name}: {self.sql(expression, 'kind')}}}" 696 697 def oncluster_sql(self, expression: exp.OnCluster) -> str: 698 return f"ON CLUSTER {self.sql(expression, 'this')}" 699 700 def _refresh_interval_sql(self, expression: exp.Expr) -> str: 701 if isinstance(expression, exp.Add): 702 return f"{self._refresh_interval_sql(expression.this)} {self._refresh_interval_sql(expression.expression)}" 703 return self.sql(expression.assert_is(exp.Interval)) 704 705 def autorefreshproperty_sql(self, expression: exp.AutoRefreshProperty) -> str: 706 cadence = self.sql(expression, "cadence") 707 interval = expression.this 708 schedule = ( 709 f" {cadence} {self._refresh_interval_sql(interval)}" if cadence and interval else "" 710 ) 711 offset = expression.args.get("offset") 712 offset = f" OFFSET {self._refresh_interval_sql(offset)}" if offset else "" 713 randomize = expression.args.get("randomize") 714 randomize = f" RANDOMIZE FOR {self._refresh_interval_sql(randomize)}" if randomize else "" 715 dependencies = self.expressions(expression, flat=True) 716 dependencies = f" DEPENDS ON {dependencies}" if dependencies else "" 717 settings = self.sql(expression, "settings") 718 settings = f" {settings}" if settings else "" 719 append = " APPEND" if expression.args.get("append") else "" 720 721 return f"REFRESH{schedule}{offset}{randomize}{dependencies}{settings}{append}" 722 723 def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str: 724 if expression.kind in self.ON_CLUSTER_TARGETS and locations.get( 725 exp.Properties.Location.POST_NAME 726 ): 727 this_name = self.sql( 728 expression.this if isinstance(expression.this, exp.Schema) else expression, 729 "this", 730 ) 731 this_properties = " ".join( 732 [self.sql(prop) for prop in locations[exp.Properties.Location.POST_NAME]] 733 ) 734 this_schema = self.schema_columns_sql(expression.this) 735 this_schema = f"{self.sep()}{this_schema}" if this_schema else "" 736 737 return f"{this_name}{self.sep()}{this_properties}{this_schema}" 738 739 return super().createable_sql(expression, locations) 740 741 def create_sql(self, expression: exp.Create) -> str: 742 # The comment property comes last in CTAS statements, i.e. after the query 743 query = expression.expression 744 if isinstance(query, exp.Query): 745 comment_prop = expression.find(exp.SchemaCommentProperty) 746 if comment_prop: 747 comment_prop.pop() 748 if not isinstance(query, exp.Subquery): 749 query.replace(exp.paren(query)) 750 else: 751 comment_prop = None 752 753 create_sql = super().create_sql(expression) 754 755 comment_sql = self.sql(comment_prop) 756 comment_sql = f" {comment_sql}" if comment_sql else "" 757 758 return f"{create_sql}{comment_sql}" 759 760 def prewhere_sql(self, expression: exp.PreWhere) -> str: 761 this = self.indent(self.sql(expression, "this")) 762 return f"{self.seg('PREWHERE')}{self.sep()}{this}" 763 764 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 765 this = self.sql(expression, "this") 766 this = f" {this}" if this else "" 767 expr = self.sql(expression, "expression") 768 expr = f" {expr}" if expr else "" 769 index_type = self.sql(expression, "index_type") 770 index_type = f" TYPE {index_type}" if index_type else "" 771 granularity = self.sql(expression, "granularity") 772 granularity = f" GRANULARITY {granularity}" if granularity else "" 773 774 return f"INDEX{this}{expr}{index_type}{granularity}" 775 776 def partition_sql(self, expression: exp.Partition) -> str: 777 return f"PARTITION {self.expressions(expression, flat=True)}" 778 779 def partitionid_sql(self, expression: exp.PartitionId) -> str: 780 return f"ID {self.sql(expression.this)}" 781 782 def replacepartition_sql(self, expression: exp.ReplacePartition) -> str: 783 return f"REPLACE {self.sql(expression.expression)} FROM {self.sql(expression, 'source')}" 784 785 def projectiondef_sql(self, expression: exp.ProjectionDef) -> str: 786 return f"PROJECTION {self.sql(expression.this)} {self.wrap(expression.expression)}" 787 788 def is_sql(self, expression: exp.Is) -> str: 789 is_sql = super().is_sql(expression) 790 791 if isinstance(expression.parent, exp.Not): 792 # value IS NOT NULL -> NOT (value IS NULL) 793 is_sql = self.wrap(is_sql) 794 795 return is_sql 796 797 def in_sql(self, expression: exp.In) -> str: 798 in_sql = super().in_sql(expression) 799 800 if isinstance(expression.parent, exp.Not) and expression.args.get("is_global"): 801 in_sql = in_sql.replace("GLOBAL IN", "GLOBAL NOT IN", 1) 802 803 return in_sql 804 805 def not_sql(self, expression: exp.Not) -> str: 806 if isinstance(expression.this, exp.In): 807 if expression.this.args.get("is_global"): 808 # let `GLOBAL IN` child interpose `NOT` 809 return self.sql(expression, "this") 810 811 expression.set("this", exp.paren(expression.this, copy=False)) 812 813 return super().not_sql(expression) 814 815 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 816 # If the VALUES clause contains tuples of expressions, we need to treat it 817 # as a table since Clickhouse will automatically alias it as such. 818 alias = expression.args.get("alias") 819 820 if alias and alias.args.get("columns") and expression.expressions: 821 values = expression.expressions[0].expressions 822 values_as_table = any(isinstance(value, exp.Tuple) for value in values) 823 else: 824 values_as_table = True 825 826 # An unparenthesized VALUES in FROM is the values() table function, which takes a single 827 # argument list, so a multi-row VALUES relation must be parenthesized to parse 828 if ( 829 values_as_table 830 and len(expression.expressions) > 1 831 and (alias or isinstance(expression.parent, (exp.From, exp.Join, exp.Table))) 832 ): 833 values = f"(VALUES{self.seg('')}{self.expressions(expression)})" 834 values = self.query_modifiers(expression, values) 835 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 836 alias_sql = self.sql(alias) 837 return f"{values} AS {alias_sql}{pivots}" if alias_sql else f"{values}{pivots}" 838 839 return super().values_sql(expression, values_as_table=values_as_table) 840 841 def timestamptrunc_sql(self, expression: exp.DateTrunc | exp.TimestampTrunc) -> str: 842 unit = weekstart_unit_to_str(self, expression) 843 # https://clickhouse.com/docs/whats-new/changelog/2023#improvement 844 if self.dialect.version < (23, 12) and unit and unit.is_string: 845 unit = exp.Literal.string(unit.name.lower()) 846 return self.func("dateTrunc", unit, expression.this, expression.args.get("zone")) 847 848 def datetrunc_sql(self, expression: exp.DateTrunc) -> str: 849 return self.timestamptrunc_sql(expression)
Generator converts a given syntax tree to the corresponding SQL string.
Arguments:
- pretty: Whether 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: Always quote except for specials cases. 'safe': Only quote identifiers that are case insensitive.
- normalize: Whether to normalize identifiers to lowercase. Default: False.
- pad: The pad size in a formatted string. For example, this affects the indentation of a projection in a query, relative to its nesting level. Default: 2.
- indent: The indentation size in a formatted string. For example, this affects the
indentation of subqueries and filters under a
WHEREclause. Default: 2. - normalize_functions: How to normalize 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: Whether 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 to preserve comments in the output SQL code. Default: True
STRING_TYPE_MAPPING: ClassVar =
{<DType.BLOB: 'BLOB'>: 'String', <DType.CHAR: 'CHAR'>: 'String', <DType.LONGBLOB: 'LONGBLOB'>: 'String', <DType.LONGTEXT: 'LONGTEXT'>: 'String', <DType.MEDIUMBLOB: 'MEDIUMBLOB'>: 'String', <DType.MEDIUMTEXT: 'MEDIUMTEXT'>: 'String', <DType.TINYBLOB: 'TINYBLOB'>: 'String', <DType.TINYTEXT: 'TINYTEXT'>: 'String', <DType.TEXT: 'TEXT'>: 'String', <DType.VARBINARY: 'VARBINARY'>: 'String', <DType.VARCHAR: 'VARCHAR'>: 'String'}
SUPPORTED_JSON_PATH_PARTS =
{<class 'sqlglot.expressions.query.JSONPathRoot'>, <class 'sqlglot.expressions.query.JSONPathSubscript'>, <class 'sqlglot.expressions.query.JSONPathKey'>}
TYPE_MAPPING =
{<DType.DATETIME2: 'DATETIME2'>: 'DateTime', <DType.NCHAR: 'NCHAR'>: 'CHAR', <DType.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <DType.MEDIUMTEXT: 'MEDIUMTEXT'>: 'String', <DType.LONGTEXT: 'LONGTEXT'>: 'String', <DType.TINYTEXT: 'TINYTEXT'>: 'String', <DType.BLOB: 'BLOB'>: 'String', <DType.MEDIUMBLOB: 'MEDIUMBLOB'>: 'String', <DType.LONGBLOB: 'LONGBLOB'>: 'String', <DType.TINYBLOB: 'TINYBLOB'>: 'String', <DType.INET: 'INET'>: 'INET', <DType.ROWVERSION: 'ROWVERSION'>: 'VARBINARY', <DType.SMALLDATETIME: 'SMALLDATETIME'>: 'DateTime', <DType.CHAR: 'CHAR'>: 'String', <DType.TEXT: 'TEXT'>: 'String', <DType.VARBINARY: 'VARBINARY'>: 'String', <DType.VARCHAR: 'VARCHAR'>: 'String', <DType.ARRAY: 'ARRAY'>: 'Array', <DType.BOOLEAN: 'BOOLEAN'>: 'Bool', <DType.BIGINT: 'BIGINT'>: 'Int64', <DType.DATE32: 'DATE32'>: 'Date32', <DType.DATETIME: 'DATETIME'>: 'DateTime', <DType.DATETIME64: 'DATETIME64'>: 'DateTime64', <DType.DECIMAL: 'DECIMAL'>: 'Decimal', <DType.DECIMAL32: 'DECIMAL32'>: 'Decimal32', <DType.DECIMAL64: 'DECIMAL64'>: 'Decimal64', <DType.DECIMAL128: 'DECIMAL128'>: 'Decimal128', <DType.DECIMAL256: 'DECIMAL256'>: 'Decimal256', <DType.TIMESTAMP: 'TIMESTAMP'>: 'DateTime', <DType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>: 'DateTime', <DType.TIMESTAMPTZ: 'TIMESTAMPTZ'>: 'DateTime', <DType.DOUBLE: 'DOUBLE'>: 'Float64', <DType.ENUM: 'ENUM'>: 'Enum', <DType.ENUM8: 'ENUM8'>: 'Enum8', <DType.ENUM16: 'ENUM16'>: 'Enum16', <DType.FIXEDSTRING: 'FIXEDSTRING'>: 'FixedString', <DType.FLOAT: 'FLOAT'>: 'Float32', <DType.INT: 'INT'>: 'Int32', <DType.MEDIUMINT: 'MEDIUMINT'>: 'Int32', <DType.INT128: 'INT128'>: 'Int128', <DType.INT256: 'INT256'>: 'Int256', <DType.LOWCARDINALITY: 'LOWCARDINALITY'>: 'LowCardinality', <DType.MAP: 'MAP'>: 'Map', <DType.NESTED: 'NESTED'>: 'Nested', <DType.NOTHING: 'NOTHING'>: 'Nothing', <DType.SMALLINT: 'SMALLINT'>: 'Int16', <DType.STRUCT: 'STRUCT'>: 'Tuple', <DType.TINYINT: 'TINYINT'>: 'Int8', <DType.UBIGINT: 'UBIGINT'>: 'UInt64', <DType.UINT: 'UINT'>: 'UInt32', <DType.UINT128: 'UINT128'>: 'UInt128', <DType.UINT256: 'UINT256'>: 'UInt256', <DType.USMALLINT: 'USMALLINT'>: 'UInt16', <DType.UTINYINT: 'UTINYINT'>: 'UInt8', <DType.IPV4: 'IPV4'>: 'IPv4', <DType.IPV6: 'IPV6'>: 'IPv6', <DType.POINT: 'POINT'>: 'Point', <DType.RING: 'RING'>: 'Ring', <DType.LINESTRING: 'LINESTRING'>: 'LineString', <DType.MULTILINESTRING: 'MULTILINESTRING'>: 'MultiLineString', <DType.POLYGON: 'POLYGON'>: 'Polygon', <DType.MULTIPOLYGON: 'MULTIPOLYGON'>: 'MultiPolygon', <DType.AGGREGATEFUNCTION: 'AGGREGATEFUNCTION'>: 'AggregateFunction', <DType.SIMPLEAGGREGATEFUNCTION: 'SIMPLEAGGREGATEFUNCTION'>: 'SimpleAggregateFunction', <DType.DYNAMIC: 'DYNAMIC'>: 'Dynamic'}
TRANSFORMS =
{<class 'sqlglot.expressions.query.JSONPathKey'>: <function json_path_key_only_name>, <class 'sqlglot.expressions.query.JSONPathRoot'>: <function ClickHouseGenerator.<lambda>>, <class 'sqlglot.expressions.query.JSONPathSubscript'>: <function <lambda>>, <class 'sqlglot.expressions.core.Adjacent'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.AllowedValuesProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.AnalyzeColumns'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.AnalyzeWith'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayContainedBy'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayContainsAll'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayOverlaps'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.AssumeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.BinaryColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CalledOnNullInputProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.math.Ceil'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.ConnectByRoot'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.string.ConvertToCharset'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CopyTagsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CredentialsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.CurrentCatalog'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.SessionUser'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ApiProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ApplicationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CatalogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ComputeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.DatabaseProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.DynamicProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.EmptyProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.EndStatement'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.EnviromentProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HandlerProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ParameterStyleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.EphemeralColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ExcludeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Except'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.math.Floor'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Get'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.GlobalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HybridProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.IcebergProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.IgnoreGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Intersect'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.datatypes.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.Int64'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsAnyTopKeys'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsAllTopKeys'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsTopKey'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBDeleteAtPath'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBPathExists'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONObject'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONObjectAgg'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.MaskingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.NetFunc'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.NetworkProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.Operator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ExtendsLeft'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ExtendsRight'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.PartitionedByBucket'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.PartitionByTruncate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.PositionalColumn'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ProjectionPolicyColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.InvisibleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ZeroFillColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Put'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.RowAccessProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.SafeFunc'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SecureProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SecurityIntegrationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SharingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Stream'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StreamingTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StrictProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ddl.SwapTable'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.TableColumn'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.VirtualProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ddl.TriggerExecute'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.UsingTemplateProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.UsingData'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcDate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcTime'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcTimestamp'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Variadic'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.VarMap'>: <function _map_sql>, <class 'sqlglot.expressions.properties.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.WithOperator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithoutRowidProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ForceProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.aggregate.AnyValue'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.ApproxDistinct'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.ApproxQuantile'>: <function _quantile_sql>, <class 'sqlglot.expressions.array.ArrayDistinct'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.ArrayConcat'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.ArrayContains'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.ArrayFilter'>: <function ClickHouseGenerator.<lambda>>, <class 'sqlglot.expressions.array.Transform'>: <function ClickHouseGenerator.<lambda>>, <class 'sqlglot.expressions.array.ArrayReverse'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.ArraySort'>: <function _array_sort_sql>, <class 'sqlglot.expressions.array.ArraySlice'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.ArraySum'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.ArrayMax'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.ArrayMin'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.ArgMax'>: <function arg_max_or_min_no_count.<locals>._arg_max_or_min_sql>, <class 'sqlglot.expressions.aggregate.ArgMin'>: <function arg_max_or_min_no_count.<locals>._arg_max_or_min_sql>, <class 'sqlglot.expressions.array.Array'>: <function inline_array_sql>, <class 'sqlglot.expressions.math.BitwiseAndAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.BitwiseOrAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.BitwiseXorAgg'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.CityHash64'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.functions.CastToStrType'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.functions.CurrentDatabase'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.functions.CurrentSchemas'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.CountIf'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.CosineDistance'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.constraints.CompressColumnConstraint'>: <function ClickHouseGenerator.<lambda>>, <class 'sqlglot.expressions.constraints.ComputedColumnConstraint'>: <function ClickHouseGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.CurrentDate'>: <function ClickHouseGenerator.<lambda>>, <class 'sqlglot.expressions.functions.CurrentVersion'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.DateAdd'>: <function _datetime_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.DateDiff'>: <function _datetime_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.DateStrToDate'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.DateSub'>: <function _datetime_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.DayOfMonth'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.DayOfWeekIso'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.DayOfYear'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.Explode'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.FarmFingerprint'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.query.Final'>: <function ClickHouseGenerator.<lambda>>, <class 'sqlglot.expressions.math.IsInf'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.IsNan'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.JarowinklerSimilarity'>: <function jarowinkler_similarity.<locals>.jarowinklersimilarity_sql>, <class 'sqlglot.expressions.functions.JSONCast'>: <function _json_cast_sql>, <class 'sqlglot.expressions.json.JSONExtract'>: <function json_extract_segments.<locals>._json_extract_segments>, <class 'sqlglot.expressions.json.JSONExtractScalar'>: <function json_extract_segments.<locals>._json_extract_segments>, <class 'sqlglot.expressions.string.Length'>: <function length_or_char_length_sql>, <class 'sqlglot.expressions.aggregate.LogicalAnd'>: <function ClickHouseGenerator.<lambda>>, <class 'sqlglot.expressions.aggregate.LogicalOr'>: <function ClickHouseGenerator.<lambda>>, <class 'sqlglot.expressions.array.Map'>: <function _map_sql>, <class 'sqlglot.expressions.aggregate.Median'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.functions.Nullif'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.properties.PartitionedByProperty'>: <function ClickHouseGenerator.<lambda>>, <class 'sqlglot.expressions.query.Pivot'>: <function no_pivot_sql>, <class 'sqlglot.expressions.aggregate.Quantile'>: <function _quantile_sql>, <class 'sqlglot.expressions.core.RegexpLike'>: <function ClickHouseGenerator.<lambda>>, <class 'sqlglot.expressions.functions.Rand'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.StartsWith'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.array.Struct'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.Trunc'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.EndsWith'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.math.EuclideanDistance'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.StrPosition'>: <function ClickHouseGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.TimeToStr'>: <function ClickHouseGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.TimeStrToTime'>: <function _timestrtotime_sql>, <class 'sqlglot.expressions.temporal.TimestampAdd'>: <function _datetime_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.temporal.TimestampSub'>: <function _datetime_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.core.Typeof'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.Xor'>: <function ClickHouseGenerator.<lambda>>, <class 'sqlglot.expressions.string.MD5Digest'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.MD5'>: <function ClickHouseGenerator.<lambda>>, <class 'sqlglot.expressions.string.SHA'>: <function ClickHouseGenerator.<lambda>>, <class 'sqlglot.expressions.string.SHA1Digest'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.SHA2'>: <function ClickHouseGenerator.<lambda>>, <class 'sqlglot.expressions.string.SHA2Digest'>: <function sha2_digest_sql>, <class 'sqlglot.expressions.string.Split'>: <function ClickHouseGenerator.<lambda>>, <class 'sqlglot.expressions.string.RegexpSplit'>: <function ClickHouseGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.UnixToTime'>: <function _unix_to_time_sql>, <class 'sqlglot.expressions.string.Trim'>: <function ClickHouseGenerator.<lambda>>, <class 'sqlglot.expressions.aggregate.VariancePop'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.WeekOfYear'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.YearOfWeekIso'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.properties.SchemaCommentProperty'>: <function ClickHouseGenerator.<lambda>>, <class 'sqlglot.expressions.aggregate.Stddev'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.Chr'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.Lag'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.Lead'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.Levenshtein'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.ParseDatetime'>: <function ClickHouseGenerator.<lambda>>}
PROPERTIES_LOCATION =
{<class 'sqlglot.expressions.properties.AggregateKeyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AllowedValuesProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AlgorithmProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ApiProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ApplicationProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.AutoIncrementProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AutoRefreshProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.BackupProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.BlockCompressionProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.CalledOnNullInputProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.CatalogProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.CharacterSetProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ChecksumProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.CollateProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ComputeProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.CopyGrantsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.CopyTagsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.query.Cluster'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ClusteredByProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ClusterProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DistributedByProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DuplicateKeyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DataBlocksizeProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.DatabaseProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DataDeletionProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DefinerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DictRange'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DictProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DynamicProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DistKeyProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.DistStyleProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.EmptyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.EncodeProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.EngineProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.EnviromentProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.HandlerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ParameterStyleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ExecuteAsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ExternalProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.FallbackProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.FileFormatProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.FreespaceProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.GlobalProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.HeapProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.HybridProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.InheritsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.IcebergProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.IgnoreGrantsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.IncludeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.InteractiveProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.IsolatedLoadingProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.JournalProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.LanguageProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LikeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LocationProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LockProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LockingProperty'>: <PropertiesLocation.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.properties.LogProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.MaskingProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.MaterializedProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.MergeBlockRatioProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.ModuleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.NetworkProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.NoPrimaryIndexProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.OnProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.OnCommitProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.OptionsProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.query.Order'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.OutputModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.PartitionedByProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.PartitionedOfProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.PhysicalProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.constraints.PrimaryKey'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.Property'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.RefreshTriggerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RemoteWithConnectionModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ReturnsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RollupProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.RowAccessProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.RowFormatProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RowFormatDelimitedProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RowFormatSerdeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SampleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SchemaCommentProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SecureProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.SecurityIntegrationProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.SerdeProperties'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ddl.Set'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SettingsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SetProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.SetConfigProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SharingProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.ddl.SequenceProperties'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.ddl.TriggerProperties'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.SortKeyProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.SqlReadWriteProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SqlSecurityProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StabilityProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StorageHandlerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StorageProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.StreamingTableProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.StrictProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.Tags'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.TableSpaceProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.TemporaryProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ToTableProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.TransientProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.TransformModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ddl.MergeTreeTTL'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.UnloggedProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.UsingProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.UsingTemplateProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ViewAttributeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.VirtualProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.VolatileProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.WithDataProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.WithJournalTableProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.WithProcedureOptions'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithSchemaBindingProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithSystemVersioningProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithoutRowidProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.ForceProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.OnCluster'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.UuidProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>}
ON_CLUSTER_TARGETS: ClassVar =
{'DATABASE', 'SCHEMA', 'INDEX', 'NAMED COLLECTION', 'TABLE', 'FUNCTION', 'DICTIONARY', 'VIEW'}
NON_NULLABLE_TYPES: ClassVar =
{<DType.MAP: 'MAP'>, <DType.POLYGON: 'POLYGON'>, <DType.MULTILINESTRING: 'MULTILINESTRING'>, <DType.POINT: 'POINT'>, <DType.ARRAY: 'ARRAY'>, <DType.MULTIPOLYGON: 'MULTIPOLYGON'>, <DType.LINESTRING: 'LINESTRING'>, <DType.RING: 'RING'>, <DType.STRUCT: 'STRUCT'>}
473 def dot_sql(self, expression: exp.Dot) -> str: 474 if depth := expression.args.get("subcolumn_depth"): 475 root: exp.Expr = expression 476 fields: list[str] = [] 477 while isinstance(root, exp.Dot) and len(fields) < depth: 478 fields.append(root.expression.name) 479 root = root.this 480 481 # expr.a.b performs two lookups, while a column path resolves the entire subcolumn. 482 if len(fields) == depth and not isinstance(root, exp.Column): 483 return self.func( 484 "getSubcolumn", root, exp.Literal.string(".".join(reversed(fields))) 485 ) 486 487 return super().dot_sql(expression)
@unsupported_args('json_scope')
def
contains_sql(self, expression: sqlglot.expressions.string.Contains) -> str:
489 @unsupported_args("json_scope") 490 def contains_sql(self, expression: exp.Contains) -> str: 491 # ClickHouse has no CONTAINS; keep the parentheses only where the parent needs them 492 result = exp.paren( 493 exp.StrPosition(this=expression.this, substr=expression.expression) > 0, copy=False 494 ) 495 result.parent = expression.parent 496 return self.sql(simplify_parens(result, self.dialect))
498 def groupconcat_sql(self, expression: exp.GroupConcat) -> str: 499 this = expression.this 500 separator = expression.args.get("separator") 501 502 if isinstance(this, exp.Limit) and this.this: 503 limit = this 504 this = limit.this.pop() 505 return self.sql( 506 exp.ParameterizedAgg( 507 this="groupConcat", 508 params=[this], 509 expressions=[separator, limit.expression], 510 ) 511 ) 512 513 if separator: 514 return self.sql( 515 exp.ParameterizedAgg( 516 this="groupConcat", 517 params=[this], 518 expressions=[separator], 519 ) 520 ) 521 522 return self.func("groupConcat", this)
524 def select_sql(self, expression: exp.Select) -> str: 525 limit = expression.args.get("limit") 526 if isinstance(limit, exp.Fetch) and not expression.args.get("order"): 527 count = limit.args.get("count") 528 expression.set( 529 "limit", exp.Limit(expression=count if count is not None else exp.Literal.number(1)) 530 ) 531 return super().select_sql(expression)
533 def offset_sql(self, expression: exp.Offset) -> str: 534 offset = super().offset_sql(expression) 535 536 # OFFSET ... FETCH syntax requires a "ROW" or "ROWS" keyword 537 # https://clickhouse.com/docs/sql-reference/statements/select/offset 538 parent = expression.parent 539 if isinstance(parent, exp.Select) and isinstance(parent.args.get("limit"), exp.Fetch): 540 offset = f"{offset} ROWS" 541 542 return offset
544 def strtodate_sql(self, expression: exp.StrToDate) -> str: 545 strtodate_sql = self.function_fallback_sql(expression) 546 547 if not isinstance(expression.parent, exp.Cast): 548 # StrToDate returns DATEs in other dialects (eg. postgres), so 549 # this branch aims to improve the transpilation to clickhouse 550 return self.cast_sql(exp.cast(expression, "DATE")) 551 552 return strtodate_sql
def
cast_sql( self, expression: sqlglot.expressions.functions.Cast, safe_prefix: str | None = None) -> str:
554 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 555 this = expression.this 556 557 if isinstance(this, exp.StrToDate) and expression.to == exp.DType.DATETIME.into_expr(): 558 return self.sql(this) 559 560 this = this.unnest() 561 if ( 562 isinstance(this, exp.JSONExtract) 563 and this.args.get("requires_json") 564 and expression.to.is_type(*exp.DataType.TEXT_TYPES) 565 ): 566 return self.func("JSONExtract", this, exp.Literal.string("Nullable(String)")) 567 568 return super().cast_sql(expression, safe_prefix=safe_prefix)
570 def trycast_sql(self, expression: exp.TryCast) -> str: 571 dtype = expression.to 572 if not dtype.is_type(*self.NON_NULLABLE_TYPES, check_nullable=True): 573 # Casting x into Nullable(T) appears to behave similarly to TRY_CAST(x AS T) 574 dtype.set("nullable", True) 575 576 return super().cast_sql(expression)
611 def regexpcount_sql(self, expression: exp.RegexpCount) -> str: 612 this = expression.this 613 pattern = expression.expression 614 position = expression.args.get("position") 615 parameters = expression.args.get("parameters") 616 617 if position: 618 # SUBSTRING counts bytes in ClickHouse, the position counts characters 619 this = self.func("substringUTF8", this, position) 620 621 if parameters: 622 flags = parameters.name if parameters.is_string else "" 623 if not parameters.is_string or set(flags) - set("cims"): 624 self.unsupported("Only literal 'c', 'i', 'm' and 's' regexp flags are supported") 625 # "c" (case-sensitive) is the default, and the last of "c" and "i" wins 626 if flags.rfind("c") > flags.rfind("i"): 627 flags = flags.replace("i", "") 628 flags = "".join(f for f in flags if f in "ims") 629 if flags: 630 # countMatches has no flags argument, so they are embedded in the pattern 631 pattern = self.func("CONCAT", exp.Literal.string(f"(?{flags})"), pattern) 632 633 return self.func("countMatches", this, pattern)
640 def datatype_sql(self, expression: exp.DataType) -> str: 641 # String is the standard ClickHouse type, every other variant is just an alias. 642 # Additionally, any supplied length parameter will be ignored. 643 # 644 # https://clickhouse.com/docs/en/sql-reference/data-types/string 645 if expression.this in self.STRING_TYPE_MAPPING: 646 dtype = "String" 647 else: 648 dtype = super().datatype_sql(expression) 649 650 # This section changes the type to `Nullable(...)` if the following conditions hold: 651 # - It's marked as nullable - this ensures we won't wrap ClickHouse types with `Nullable` 652 # and change their semantics 653 # - It's not the key type of a `Map`. This is because ClickHouse enforces the following 654 # constraint: "Type of Map key must be a type, that can be represented by integer or 655 # String or FixedString (possibly LowCardinality) or UUID or IPv6" 656 # - It's not a composite type, e.g. `Nullable(Array(...))` is not a valid type 657 parent = expression.parent 658 nullable = expression.args.get("nullable") 659 if nullable is True or ( 660 nullable is None 661 and not ( 662 isinstance(parent, exp.DataType) 663 and parent.is_type(exp.DType.MAP, check_nullable=True) 664 and expression.index in (None, 0) 665 ) 666 and not expression.is_type(*self.NON_NULLABLE_TYPES, check_nullable=True) 667 ): 668 dtype = f"Nullable({dtype})" 669 670 return dtype
680 def after_limit_modifiers(self, expression: exp.Expr) -> list[str]: 681 return super().after_limit_modifiers(expression) + [ 682 ( 683 self.seg("SETTINGS ") + self.expressions(expression, key="settings", flat=True) 684 if expression.args.get("settings") 685 else "" 686 ), 687 ( 688 self.seg("FORMAT ") + self.sql(expression, "format") 689 if expression.args.get("format") 690 else "" 691 ), 692 ]
def
autorefreshproperty_sql( self, expression: sqlglot.expressions.properties.AutoRefreshProperty) -> str:
705 def autorefreshproperty_sql(self, expression: exp.AutoRefreshProperty) -> str: 706 cadence = self.sql(expression, "cadence") 707 interval = expression.this 708 schedule = ( 709 f" {cadence} {self._refresh_interval_sql(interval)}" if cadence and interval else "" 710 ) 711 offset = expression.args.get("offset") 712 offset = f" OFFSET {self._refresh_interval_sql(offset)}" if offset else "" 713 randomize = expression.args.get("randomize") 714 randomize = f" RANDOMIZE FOR {self._refresh_interval_sql(randomize)}" if randomize else "" 715 dependencies = self.expressions(expression, flat=True) 716 dependencies = f" DEPENDS ON {dependencies}" if dependencies else "" 717 settings = self.sql(expression, "settings") 718 settings = f" {settings}" if settings else "" 719 append = " APPEND" if expression.args.get("append") else "" 720 721 return f"REFRESH{schedule}{offset}{randomize}{dependencies}{settings}{append}"
def
createable_sql( self, expression: sqlglot.expressions.ddl.Create, locations: collections.defaultdict) -> str:
723 def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str: 724 if expression.kind in self.ON_CLUSTER_TARGETS and locations.get( 725 exp.Properties.Location.POST_NAME 726 ): 727 this_name = self.sql( 728 expression.this if isinstance(expression.this, exp.Schema) else expression, 729 "this", 730 ) 731 this_properties = " ".join( 732 [self.sql(prop) for prop in locations[exp.Properties.Location.POST_NAME]] 733 ) 734 this_schema = self.schema_columns_sql(expression.this) 735 this_schema = f"{self.sep()}{this_schema}" if this_schema else "" 736 737 return f"{this_name}{self.sep()}{this_properties}{this_schema}" 738 739 return super().createable_sql(expression, locations)
741 def create_sql(self, expression: exp.Create) -> str: 742 # The comment property comes last in CTAS statements, i.e. after the query 743 query = expression.expression 744 if isinstance(query, exp.Query): 745 comment_prop = expression.find(exp.SchemaCommentProperty) 746 if comment_prop: 747 comment_prop.pop() 748 if not isinstance(query, exp.Subquery): 749 query.replace(exp.paren(query)) 750 else: 751 comment_prop = None 752 753 create_sql = super().create_sql(expression) 754 755 comment_sql = self.sql(comment_prop) 756 comment_sql = f" {comment_sql}" if comment_sql else "" 757 758 return f"{create_sql}{comment_sql}"
def
indexcolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.IndexColumnConstraint) -> str:
764 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 765 this = self.sql(expression, "this") 766 this = f" {this}" if this else "" 767 expr = self.sql(expression, "expression") 768 expr = f" {expr}" if expr else "" 769 index_type = self.sql(expression, "index_type") 770 index_type = f" TYPE {index_type}" if index_type else "" 771 granularity = self.sql(expression, "granularity") 772 granularity = f" GRANULARITY {granularity}" if granularity else "" 773 774 return f"INDEX{this}{expr}{index_type}{granularity}"
805 def not_sql(self, expression: exp.Not) -> str: 806 if isinstance(expression.this, exp.In): 807 if expression.this.args.get("is_global"): 808 # let `GLOBAL IN` child interpose `NOT` 809 return self.sql(expression, "this") 810 811 expression.set("this", exp.paren(expression.this, copy=False)) 812 813 return super().not_sql(expression)
def
values_sql( self, expression: sqlglot.expressions.query.Values, values_as_table: bool = True) -> str:
815 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 816 # If the VALUES clause contains tuples of expressions, we need to treat it 817 # as a table since Clickhouse will automatically alias it as such. 818 alias = expression.args.get("alias") 819 820 if alias and alias.args.get("columns") and expression.expressions: 821 values = expression.expressions[0].expressions 822 values_as_table = any(isinstance(value, exp.Tuple) for value in values) 823 else: 824 values_as_table = True 825 826 # An unparenthesized VALUES in FROM is the values() table function, which takes a single 827 # argument list, so a multi-row VALUES relation must be parenthesized to parse 828 if ( 829 values_as_table 830 and len(expression.expressions) > 1 831 and (alias or isinstance(expression.parent, (exp.From, exp.Join, exp.Table))) 832 ): 833 values = f"(VALUES{self.seg('')}{self.expressions(expression)})" 834 values = self.query_modifiers(expression, values) 835 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 836 alias_sql = self.sql(alias) 837 return f"{values} AS {alias_sql}{pivots}" if alias_sql else f"{values}{pivots}" 838 839 return super().values_sql(expression, values_as_table=values_as_table)
def
timestamptrunc_sql( self, expression: sqlglot.expressions.temporal.DateTrunc | sqlglot.expressions.temporal.TimestampTrunc) -> str:
841 def timestamptrunc_sql(self, expression: exp.DateTrunc | exp.TimestampTrunc) -> str: 842 unit = weekstart_unit_to_str(self, expression) 843 # https://clickhouse.com/docs/whats-new/changelog/2023#improvement 844 if self.dialect.version < (23, 12) and unit and unit.is_string: 845 unit = exp.Literal.string(unit.name.lower()) 846 return self.func("dateTrunc", unit, expression.this, expression.args.get("zone"))
Inherited Members
- sqlglot.generator.Generator
- Generator
- NULL_ORDERING_SUPPORTED
- WINDOW_FUNCS_WITH_NULL_ORDERING
- WINDOW_FUNCS_REQUIRING_ORDER
- IGNORE_NULLS_IN_FUNC
- IGNORE_NULLS_BEFORE_ORDER
- LOCKING_READS_SUPPORTED
- EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
- CREATE_FUNCTION_RETURN_AS
- MATCHED_BY_SOURCE
- SUPPORTS_MERGE_WHERE
- MERGE_SCHEMA_EVOLUTION_MIN_VERSION
- MERGE_ALL_BY_NAME
- SINGLE_STRING_INTERVAL
- INTERVAL_ALLOWS_PLURAL_FORM
- LIMIT_FETCH
- LIMIT_ONLY_LITERALS
- RENAME_TABLE_WITH_DB
- SUPPORTS_GROUPING_SETS_AS_SUFFIX
- INDEX_ON
- INOUT_SEPARATOR
- DIRECTED_JOINS
- SUPPORTS_NEAREST_JOIN
- SUPPORTS_MATCH_CONDITION
- QUERY_HINT_SEP
- IS_BOOL_ALLOWED
- CAST_TO_INT_ROUNDS
- SAFE_INT_DIVISION
- INT_DIV_OPERATOR
- DUPLICATE_KEY_UPDATE_WITH_SET
- LIMIT_IS_TOP
- RETURNING_END
- EXTRACT_ALLOWS_QUOTES
- TZ_TO_WITH_TIME_ZONE
- VALUES_AS_TABLE
- ALTER_TABLE_INCLUDE_COLUMN_KEYWORD
- ALTER_TABLE_ADD_COLUMNS_WRAPPED
- UNNEST_WITH_ORDINALITY
- SEMI_ANTI_JOIN_WITH_SIDE
- COMPUTED_COLUMN_WITH_TYPE
- SUPPORTS_TABLE_COPY
- TABLESAMPLE_WITH_METHOD
- TABLESAMPLE_SEED_KEYWORD
- HISTORICAL_DATA_POST_ALIAS
- COLLATE_IS_FUNC
- DATA_TYPE_SPECIFIERS_ALLOWED
- ENSURE_BOOLS
- CTE_RECURSIVE_KEYWORD_REQUIRED
- SUPPORTS_SINGLE_ARG_CONCAT
- SUPPORTS_TABLE_ALIAS_COLUMNS
- SUPPORTS_NAMED_CTE_COLUMNS
- UNPIVOT_ALIASES_ARE_IDENTIFIERS
- PIVOT_ALIAS_WITH_AS
- JSON_KEY_VALUE_PAIR_SEP
- INSERT_OVERWRITE
- SUPPORTS_SELECT_INTO
- SUPPORTS_OPTIMIZE
- SUPPORTS_EXECUTE_IMMEDIATE
- SUPPORTS_UNLOGGED_TABLES
- SUPPORTS_CREATE_TABLE_LIKE
- SUPPORTS_MODIFY_COLUMN
- SUPPORTS_CHANGE_COLUMN
- SUPPORTS_ALTER_COLUMN_NULLABILITY
- LIKE_PROPERTY_INSIDE_SCHEMA
- MULTI_ARG_DISTINCT
- JSON_TYPE_REQUIRED_FOR_EXTRACTION
- JSON_PATH_BRACKETED_KEY_SUPPORTED
- JSON_PATH_SINGLE_QUOTE_ESCAPE
- JSON_PATH_KEY_QUOTED_FORCES_BRACKETS
- SUPPORTS_WINDOW_EXCLUDE
- SET_OP_PARENTHESIZED_OPERANDS
- COPY_PARAMS_ARE_WRAPPED
- COPY_PARAMS_EQ_REQUIRED
- COPY_HAS_INTO_KEYWORD
- UNICODE_SUBSTITUTE
- STAR_EXCEPT
- HEX_FUNC
- WITH_PROPERTIES_PREFIX
- QUOTE_JSON_PATH
- PAD_FILL_PATTERN_IS_REQUIRED
- SUPPORTS_EXPLODING_PROJECTIONS
- ARRAY_CONCAT_IS_VAR_LEN
- SUPPORTS_CONVERT_TIMEZONE
- SUPPORTS_MEDIAN
- SUPPORTS_UNIX_SECONDS
- ALTER_SET_WRAPPED
- NORMALIZE_EXTRACT_DATE_PARTS
- PARSE_JSON_NAME
- DAYOFWEEK_NAME
- DAYOFWEEK_ZERO_BASED
- VARIANCE_RETURNS_ZERO_ON_SINGLE_VALUE
- ARRAY_SIZE_DIM_REQUIRED
- SUPPORTS_MULTI_ARG_CHR
- SUPPORTS_BETWEEN_FLAGS
- SUPPORTS_LIKE_QUANTIFIERS
- MATCH_AGAINST_TABLE_PREFIX
- SET_ASSIGNMENT_REQUIRES_VARIABLE_KEYWORD
- DECLARE_DEFAULT_ASSIGNMENT
- UPDATE_STATEMENT_SUPPORTS_FROM
- STAR_EXCLUDE_REQUIRES_DERIVED_TABLE
- SUPPORTS_DROP_ALTER_ICEBERG_PROPERTY
- UNSUPPORTED_TYPES
- TYPE_PARAM_SETTINGS
- TIME_PART_SINGULARS
- TOKEN_MAPPING
- PARAMETER_TOKEN
- NAMED_PLACEHOLDER_TOKEN
- EXPRESSION_PRECEDES_PROPERTIES_CREATABLES
- RESERVED_KEYWORDS
- WITH_SEPARATED_COMMENTS
- EXCLUDE_COMMENTS
- UNWRAPPED_INTERVAL_VALUES
- PARAMETERIZABLE_TEXT_TYPES
- EXPRESSIONS_WITHOUT_NESTED_CTES
- RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS
- MOD_OPERATOR
- BARE_OPERATORS
- MOD_PAREN_PARENT_TYPES
- ALTER_PARTITION_OPTIONS
- SAFE_JSON_PATH_KEY_RE
- 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
- sanitize_comment
- maybe_comment
- wrap
- no_identify
- normalize_func
- indent
- sql
- uncache_sql
- cache_sql
- characterset_sql
- column_parts
- column_sql
- pseudocolumn_sql
- columnposition_sql
- columndef_sql
- columnconstraint_sql
- computedcolumnconstraint_sql
- autoincrementcolumnconstraint_sql
- compresscolumnconstraint_sql
- generatedasidentitycolumnconstraint_sql
- generatedasrowcolumnconstraint_sql
- periodforsystemtimeconstraint_sql
- notnullcolumnconstraint_sql
- primarykeycolumnconstraint_sql
- uniquecolumnconstraint_sql
- inoutcolumnconstraint_sql
- sequenceproperties_sql
- triggerproperties_sql
- triggerreferencing_sql
- triggerevent_sql
- clone_sql
- describe_sql
- heredoc_sql
- prepend_ctes
- with_sql
- tablealias_sql
- bitstring_sql
- hexstring_sql
- bytestring_sql
- unicodestring_sql
- rawstring_sql
- datatypeparam_sql
- datatype_param_bound_limiter
- directory_sql
- delete_sql
- drop_sql
- set_operation
- set_operations
- fetch_sql
- limitoptions_sql
- filter_sql
- per_sql
- hint_sql
- indexparameters_sql
- index_sql
- dynamicidentifier_sql
- identifier_sql
- hex_sql
- lowerhex_sql
- inputoutputformat_sql
- national_sql
- properties_sql
- root_properties
- properties
- with_properties
- locate_properties
- property_name
- property_sql
- uuidproperty_sql
- fallbackproperty_sql
- journalproperty_sql
- freespaceproperty_sql
- checksumproperty_sql
- mergeblockratioproperty_sql
- moduleproperty_sql
- datablocksizeproperty_sql
- blockcompressionproperty_sql
- isolatedloadingproperty_sql
- partitionboundspec_sql
- partitionedofproperty_sql
- lockingproperty_sql
- lockingstatement_sql
- withdataproperty_sql
- withsystemversioningproperty_sql
- insert_sql
- introducer_sql
- kill_sql
- pseudotype_sql
- objectidentifier_sql
- onconflict_sql
- returning_sql
- rowformatdelimitedproperty_sql
- withtablehint_sql
- indextablehint_sql
- historicaldata_sql
- table_parts
- table_sql
- tableargument_sql
- tablefromrows_sql
- tablesample_sql
- pivot_sql
- version_sql
- tuple_sql
- update_sql
- var_sql
- into_sql
- from_sql
- groupingsets_sql
- rollup_sql
- rollupindex_sql
- rollupproperty_sql
- cube_sql
- group_sql
- having_sql
- connectto_sql
- disconnect_sql
- connect_sql
- prior_sql
- join_sql
- nearest_sql
- lambda_sql
- lateral_op
- lateral_sql
- limit_sql
- setitem_sql
- set_sql
- queryband_sql
- pragma_sql
- lock_sql
- literal_sql
- escape_str
- loaddata_sql
- null_sql
- boolean_sql
- booland_sql
- boolor_sql
- order_sql
- withfill_sql
- cluster_sql
- clusterproperty_sql
- distribute_sql
- sort_sql
- ordered_sql
- matchrecognizemeasure_sql
- matchrecognize_sql
- query_modifiers
- options_modifier
- forclause_sql
- queryoption_sql
- offset_limit_modifiers
- schema_sql
- schema_columns_sql
- star_sql
- parameter_sql
- sessionparameter_sql
- subquery_sql
- qualify_sql
- unnest_sql
- where_sql
- window_sql
- partition_by_sql
- partitionbyexcluding_sql
- windowspec_sql
- withingroup_sql
- between_sql
- bracket_offset_expressions
- bracket_sql
- all_sql
- any_sql
- exists_sql
- case_sql
- constraint_sql
- nextvaluefor_sql
- extract_date_part
- extract_sql
- trim_sql
- convert_concat_args
- concat_sql
- concatws_sql
- check_sql
- foreignkey_sql
- primarykey_sql
- timeserieskey_sql
- if_sql
- matchagainst_sql
- jsonkeyvalue_sql
- jsonpath_sql
- json_path_part
- format_sql
- formatjson_sql
- formatphrase_sql
- teradataconversion_sql
- teradatatitle_sql
- teradatanamed_sql
- jsonarray_sql
- jsonarrayagg_sql
- jsoncolumndef_sql
- jsonschema_sql
- jsontable_sql
- openjsoncolumndef_sql
- openjson_sql
- in_unnest_op
- interval_sql
- return_sql
- reference_sql
- anonymous_sql
- paren_sql
- pos_sql
- neg_sql
- alias_sql
- pivotalias_sql
- aliases_sql
- atindex_sql
- attimezone_sql
- fromtimezone_sql
- fromiso8601date_sql
- fromiso8601timestamp_sql
- fromiso8601timestampnanos_sql
- add_sql
- and_sql
- or_sql
- xor_sql
- connector_sql
- bitwiseand_sql
- bitwiseleftshift_sql
- bitwisenot_sql
- bitwiseor_sql
- bitwiserightshift_sql
- bitwisexor_sql
- strtotime_sql
- parsedatetime_sql
- currentdate_sql
- collate_sql
- command_sql
- optimize_sql
- comment_sql
- mergetreettlaction_sql
- mergetreettl_sql
- transaction_sql
- commit_sql
- rollback_sql
- altercolumn_sql
- modifycolumn_sql
- alterindex_sql
- alterdiststyle_sql
- altersortkey_sql
- alterrename_sql
- renamecolumn_sql
- alterset_sql
- alter_sql
- altersession_sql
- add_column_sql
- droppartition_sql
- dropprimarykey_sql
- addconstraint_sql
- replacecolumns_sql
- addpartition_sql
- distinct_sql
- ignorenulls_sql
- respectnulls_sql
- havingmax_sql
- intdiv_sql
- dpipe_sql
- nullif_zero_divisor
- div_sql
- safedivide_sql
- overlaps_sql
- distance_sql
- distancend_sql
- nestedjsonselect_sql
- propertyeq_sql
- escape_sql
- glob_sql
- gt_sql
- gte_sql
- like_sql
- ilike_sql
- match_sql
- similarto_sql
- lt_sql
- lte_sql
- mod_sql
- mul_sql
- nullsafeeq_sql
- nullsafeneq_sql
- sub_sql
- jsoncast_sql
- try_sql
- log_sql
- use_sql
- binary
- ceil_floor
- function_fallback_sql
- function_name
- func
- format_args
- too_wide
- format_time
- expressions
- op_expressions
- naked_property
- tag_sql
- token_sql
- userdefinedfunction_sql
- macrooverloads_sql
- macrooverload_sql
- joinhint_sql
- kwarg_sql
- when_sql
- whens_sql
- merge_sql
- tochar_sql
- tonumber_sql
- dictproperty_sql
- dictrange_sql
- dictsubproperty_sql
- aggregatekeyproperty_sql
- duplicatekeyproperty_sql
- uniquekeyproperty_sql
- distributedbyproperty_sql
- clusteredbyproperty_sql
- anyvalue_sql
- querytransform_sql
- indexconstraintoption_sql
- checkcolumnconstraint_sql
- nvl2_sql
- nthvalue_sql
- comprehension_sql
- columnprefix_sql
- opclass_sql
- predict_sql
- generateembedding_sql
- generatetext_sql
- generatetable_sql
- generatebool_sql
- generateint_sql
- generatedouble_sql
- mltranslate_sql
- mlforecast_sql
- aiforecast_sql
- featuresattime_sql
- vectorsearch_sql
- forin_sql
- refresh_sql
- toarray_sql
- tsordstotime_sql
- tsordstotimestamp_sql
- tsordstodatetime_sql
- tsordstodate_sql
- unixdate_sql
- lastday_sql
- dateadd_sql
- arrayinsert_sql
- arrayany_sql
- struct_sql
- partitionrange_sql
- truncatetable_sql
- convert_sql
- copyparameter_sql
- credentials_sql
- copy_sql
- semicolon_sql
- datadeletionproperty_sql
- maskingpolicycolumnconstraint_sql
- gapfill_sql
- scope_resolution
- scoperesolution_sql
- parsejson_sql
- rand_sql
- changes_sql
- pad_sql
- summarize_sql
- explodinggenerateseries_sql
- converttimezone_sql
- json_sql
- jsonvalue_sql
- skipjsoncolumn_sql
- conditionalinsert_sql
- multitableinserts_sql
- oncondition_sql
- jsonextractquote_sql
- jsonexists_sql
- min_sql
- max_sql
- arrayagg_sql
- timeslice_sql
- slice_sql
- apply_sql
- grant_sql
- revoke_sql
- grantprivilege_sql
- grantprincipal_sql
- columns_sql
- overlay_sql
- todouble_sql
- string_sql
- median_sql
- overflowtruncatebehavior_sql
- unixseconds_sql
- arraysort_sql
- variance_sql
- arraysize_sql
- attach_sql
- detach_sql
- attachoption_sql
- watermarkcolumnconstraint_sql
- encodeproperty_sql
- includeproperty_sql
- xmlelement_sql
- xmlkeyvalueoption_sql
- partitionbyrangeproperty_sql
- partitionbyrangepropertydynamic_sql
- unpivotcolumns_sql
- analyzesample_sql
- analyzestatistics_sql
- analyzehistogram_sql
- analyzedelete_sql
- analyzelistchainedrows_sql
- analyzevalidate_sql
- analyze_sql
- xmltable_sql
- xmlnamespace_sql
- export_sql
- declare_sql
- declareitem_sql
- recursivewithsearch_sql
- parameterizedagg_sql
- anonymousaggfunc_sql
- combinedaggfunc_sql
- combinedparameterizedagg_sql
- show_sql
- install_sql
- liststage_sql
- get_put_sql
- translatecharacters_sql
- decodecase_sql
- semanticview_sql
- getextract_sql
- datefromunixdate_sql
- space_sql
- buildproperty_sql
- refreshtriggerproperty_sql
- modelattribute_sql
- directorystage_sql
- uuid_sql
- initcap_sql
- localtime_sql
- localtimestamp_sql
- weekstart_name
- weekstart_sql
- chr_sql
- weightstring_sql
- block_sql
- functionspecification_sql
- storedprocedure_sql
- ifblock_sql
- casestatement_sql
- whileblock_sql
- loopblock_sql
- repeatblock_sql
- leave_sql
- iterate_sql
- execute_sql
- executesql_sql
- executeimmediate_sql
- altermodifysqlsecurity_sql
- usingproperty_sql
- renameindex_sql