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 inline_array_sql, 10 jarowinkler_similarity, 11 json_extract_segments, 12 json_path_key_only_name, 13 length_or_char_length_sql, 14 no_pivot_sql, 15 rename_func, 16 remove_from_array_using_filter, 17 sha256_sql, 18 strposition_sql, 19 var_map_sql, 20 weekstart_unit_to_str, 21 unit_to_var, 22 trim_sql, 23 sha2_digest_sql, 24) 25from sqlglot.generator import unsupported_args 26from sqlglot.helper import is_int 27from collections import defaultdict 28 29DATETIME_DELTA = t.Union[exp.DateAdd, exp.DateDiff, exp.DateSub, exp.TimestampSub, exp.TimestampAdd] 30 31 32def _unix_to_time_sql(self: ClickHouseGenerator, expression: exp.UnixToTime) -> str: 33 scale = expression.args.get("scale") 34 timestamp = expression.this 35 36 if scale in (None, exp.UnixToTime.SECONDS): 37 return self.func("fromUnixTimestamp", exp.cast(timestamp, exp.DType.BIGINT)) 38 if scale == exp.UnixToTime.MILLIS: 39 return self.func("fromUnixTimestamp64Milli", exp.cast(timestamp, exp.DType.BIGINT)) 40 if scale == exp.UnixToTime.MICROS: 41 return self.func("fromUnixTimestamp64Micro", exp.cast(timestamp, exp.DType.BIGINT)) 42 if scale == exp.UnixToTime.NANOS: 43 return self.func("fromUnixTimestamp64Nano", exp.cast(timestamp, exp.DType.BIGINT)) 44 45 return self.func( 46 "fromUnixTimestamp", 47 exp.cast(exp.Div(this=timestamp, expression=exp.func("POW", 10, scale)), exp.DType.BIGINT), 48 ) 49 50 51def _lower_func(sql: str) -> str: 52 index = sql.index("(") 53 return sql[:index].lower() + sql[index:] 54 55 56def _quantile_sql(self: ClickHouseGenerator, expression: exp.Quantile) -> str: 57 quantile = expression.args["quantile"] 58 args = f"({self.sql(expression, 'this')})" 59 60 if isinstance(quantile, exp.Array): 61 func = self.func("quantiles", *quantile) 62 else: 63 func = self.func("quantile", quantile) 64 65 return func + args 66 67 68def _datetime_delta_sql(name: str) -> t.Callable[[generator.Generator, DATETIME_DELTA], str]: 69 def _delta_sql(self: generator.Generator, expression: DATETIME_DELTA) -> str: 70 if not expression.unit: 71 return rename_func(name)(self, expression) 72 73 return self.func( 74 name, 75 unit_to_var(expression), 76 expression.expression, 77 expression.this, 78 expression.args.get("zone"), 79 ) 80 81 return _delta_sql 82 83 84def _timestrtotime_sql(self: ClickHouseGenerator, expression: exp.TimeStrToTime): 85 ts = expression.this 86 87 tz = expression.args.get("zone") 88 if tz and isinstance(ts, exp.Literal): 89 # Clickhouse will not accept timestamps that include a UTC offset, so we must remove them. 90 # The first step to removing is parsing the string with `datetime.datetime.fromisoformat`. 91 # 92 # In python <3.11, `fromisoformat()` can only parse timestamps of millisecond (3 digit) 93 # or microsecond (6 digit) precision. It will error if passed any other number of fractional 94 # digits, so we extract the fractional seconds and pad to 6 digits before parsing. 95 ts_string = ts.name.strip() 96 97 # separate [date and time] from [fractional seconds and UTC offset] 98 ts_parts = ts_string.split(".") 99 if len(ts_parts) == 2: 100 # separate fractional seconds and UTC offset 101 offset_sep = "+" if "+" in ts_parts[1] else "-" 102 ts_frac_parts = ts_parts[1].split(offset_sep) 103 num_frac_parts = len(ts_frac_parts) 104 105 # pad to 6 digits if fractional seconds present 106 ts_frac_parts[0] = ts_frac_parts[0].ljust(6, "0") 107 ts_string = "".join( 108 [ 109 ts_parts[0], # date and time 110 ".", 111 ts_frac_parts[0], # fractional seconds 112 offset_sep if num_frac_parts > 1 else "", 113 ts_frac_parts[1] if num_frac_parts > 1 else "", # utc offset (if present) 114 ] 115 ) 116 117 # return literal with no timezone, eg turn '2020-01-01 12:13:14-08:00' into '2020-01-01 12:13:14' 118 # this is because Clickhouse encodes the timezone as a data type parameter and throws an error if 119 # it's part of the timestamp string 120 ts_without_tz = ( 121 datetime.datetime.fromisoformat(ts_string).replace(tzinfo=None).isoformat(sep=" ") 122 ) 123 ts = exp.Literal.string(ts_without_tz) 124 125 # Non-nullable DateTime64 with microsecond precision 126 expressions = [exp.DataTypeParam(this=tz)] if tz else [] 127 datatype = exp.DType.DATETIME64.into_expr( 128 expressions=[exp.DataTypeParam(this=exp.Literal.number(6)), *expressions], 129 nullable=False, 130 ) 131 132 return self.sql(exp.cast(ts, datatype, dialect=self.dialect)) 133 134 135def _map_sql(self: ClickHouseGenerator, expression: exp.Map | exp.VarMap) -> str: 136 if not (expression.parent and expression.parent.arg_key == "settings"): 137 return _lower_func(var_map_sql(self, expression)) 138 139 keys = expression.args.get("keys") 140 values = expression.args.get("values") 141 142 if not isinstance(keys, exp.Array) or not isinstance(values, exp.Array): 143 self.unsupported("Cannot convert array columns into map.") 144 return "" 145 146 args = [] 147 for key, value in zip(keys.expressions, values.expressions): 148 args.append(f"{self.sql(key)}: {self.sql(value)}") 149 150 csv_args = ", ".join(args) 151 152 return f"{{{csv_args}}}" 153 154 155def _json_cast_sql(self: ClickHouseGenerator, expression: exp.JSONCast) -> str: 156 this = self.sql(expression, "this") 157 to = expression.to 158 to_sql = self.sql(to) 159 160 if to.expressions: 161 to_sql = self.sql(exp.to_identifier(to_sql)) 162 163 return f"{this}.:{to_sql}" 164 165 166class ClickHouseGenerator(generator.Generator): 167 BYTE_STRING_FUNCTION = "unhex" 168 SELECT_KINDS: tuple[str, ...] = () 169 TRY_SUPPORTED = False 170 SUPPORTS_UESCAPE = False 171 SUPPORTS_DECODE_CASE = False 172 173 AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS 174 175 QUERY_HINTS = False 176 STRUCT_DELIMITER = ("(", ")") 177 NVL2_SUPPORTED = False 178 ALTER_SET_TYPE = "TYPE" 179 SUPPORTS_ALTER_COLUMN_IF_EXISTS = True 180 TABLESAMPLE_REQUIRES_PARENS = False 181 TABLESAMPLE_SIZE_IS_ROWS = False 182 TABLESAMPLE_KEYWORDS = "SAMPLE" 183 LAST_DAY_SUPPORTS_DATE_PART = False 184 CAN_IMPLEMENT_ARRAY_ANY = True 185 SUPPORTS_TO_NUMBER = False 186 JOIN_HINTS = False 187 TABLE_HINTS = False 188 GROUPINGS_SEP = "" 189 SET_OP_MODIFIERS = False 190 SET_OP_LIMITS = True 191 ARRAY_SIZE_NAME = "LENGTH" 192 WRAP_DERIVED_VALUES = False 193 AUTO_REFRESH_BARE_INTERVALS = True 194 195 STRING_TYPE_MAPPING: t.ClassVar = { 196 exp.DType.BLOB: "String", 197 exp.DType.CHAR: "String", 198 exp.DType.LONGBLOB: "String", 199 exp.DType.LONGTEXT: "String", 200 exp.DType.MEDIUMBLOB: "String", 201 exp.DType.MEDIUMTEXT: "String", 202 exp.DType.TINYBLOB: "String", 203 exp.DType.TINYTEXT: "String", 204 exp.DType.TEXT: "String", 205 exp.DType.VARBINARY: "String", 206 exp.DType.VARCHAR: "String", 207 } 208 209 SUPPORTED_JSON_PATH_PARTS = { 210 exp.JSONPathKey, 211 exp.JSONPathRoot, 212 exp.JSONPathSubscript, 213 } 214 215 TYPE_MAPPING = { 216 **generator.Generator.TYPE_MAPPING, 217 exp.DType.BLOB: "String", 218 exp.DType.CHAR: "String", 219 exp.DType.LONGBLOB: "String", 220 exp.DType.LONGTEXT: "String", 221 exp.DType.MEDIUMBLOB: "String", 222 exp.DType.MEDIUMTEXT: "String", 223 exp.DType.TINYBLOB: "String", 224 exp.DType.TINYTEXT: "String", 225 exp.DType.TEXT: "String", 226 exp.DType.VARBINARY: "String", 227 exp.DType.VARCHAR: "String", 228 exp.DType.ARRAY: "Array", 229 exp.DType.BOOLEAN: "Bool", 230 exp.DType.BIGINT: "Int64", 231 exp.DType.DATE32: "Date32", 232 exp.DType.DATETIME: "DateTime", 233 exp.DType.DATETIME2: "DateTime", 234 exp.DType.SMALLDATETIME: "DateTime", 235 exp.DType.DATETIME64: "DateTime64", 236 exp.DType.DECIMAL: "Decimal", 237 exp.DType.DECIMAL32: "Decimal32", 238 exp.DType.DECIMAL64: "Decimal64", 239 exp.DType.DECIMAL128: "Decimal128", 240 exp.DType.DECIMAL256: "Decimal256", 241 exp.DType.TIMESTAMP: "DateTime", 242 exp.DType.TIMESTAMPNTZ: "DateTime", 243 exp.DType.TIMESTAMPTZ: "DateTime", 244 exp.DType.DOUBLE: "Float64", 245 exp.DType.ENUM: "Enum", 246 exp.DType.ENUM8: "Enum8", 247 exp.DType.ENUM16: "Enum16", 248 exp.DType.FIXEDSTRING: "FixedString", 249 exp.DType.FLOAT: "Float32", 250 exp.DType.INT: "Int32", 251 exp.DType.MEDIUMINT: "Int32", 252 exp.DType.INT128: "Int128", 253 exp.DType.INT256: "Int256", 254 exp.DType.LOWCARDINALITY: "LowCardinality", 255 exp.DType.MAP: "Map", 256 exp.DType.NESTED: "Nested", 257 exp.DType.NOTHING: "Nothing", 258 exp.DType.SMALLINT: "Int16", 259 exp.DType.STRUCT: "Tuple", 260 exp.DType.TINYINT: "Int8", 261 exp.DType.UBIGINT: "UInt64", 262 exp.DType.UINT: "UInt32", 263 exp.DType.UINT128: "UInt128", 264 exp.DType.UINT256: "UInt256", 265 exp.DType.USMALLINT: "UInt16", 266 exp.DType.UTINYINT: "UInt8", 267 exp.DType.IPV4: "IPv4", 268 exp.DType.IPV6: "IPv6", 269 exp.DType.POINT: "Point", 270 exp.DType.RING: "Ring", 271 exp.DType.LINESTRING: "LineString", 272 exp.DType.MULTILINESTRING: "MultiLineString", 273 exp.DType.POLYGON: "Polygon", 274 exp.DType.MULTIPOLYGON: "MultiPolygon", 275 exp.DType.AGGREGATEFUNCTION: "AggregateFunction", 276 exp.DType.SIMPLEAGGREGATEFUNCTION: "SimpleAggregateFunction", 277 exp.DType.DYNAMIC: "Dynamic", 278 } 279 280 TRANSFORMS = { 281 **{k: v for k, v in generator.Generator.TRANSFORMS.items() if k != exp.AutoRefreshProperty}, 282 exp.AnyValue: rename_func("any"), 283 exp.ApproxDistinct: rename_func("uniq"), 284 exp.ArrayDistinct: rename_func("arrayDistinct"), 285 exp.ArrayConcat: rename_func("arrayConcat"), 286 exp.ArrayContains: rename_func("has"), 287 exp.ArrayFilter: lambda self, e: self.func("arrayFilter", e.expression, e.this), 288 exp.Transform: lambda self, e: self.func("arrayMap", e.expression, e.this), 289 exp.ArrayRemove: remove_from_array_using_filter, 290 exp.ArrayReverse: rename_func("arrayReverse"), 291 exp.ArraySlice: rename_func("arraySlice"), 292 exp.ArraySum: rename_func("arraySum"), 293 exp.ArrayMax: rename_func("arrayMax"), 294 exp.ArrayMin: rename_func("arrayMin"), 295 exp.ArgMax: arg_max_or_min_no_count("argMax"), 296 exp.ArgMin: arg_max_or_min_no_count("argMin"), 297 exp.Array: inline_array_sql, 298 exp.BitwiseAndAgg: rename_func("groupBitAnd"), 299 exp.BitwiseOrAgg: rename_func("groupBitOr"), 300 exp.BitwiseXorAgg: rename_func("groupBitXor"), 301 exp.CityHash64: rename_func("cityHash64"), 302 exp.CastToStrType: rename_func("CAST"), 303 exp.CurrentDatabase: rename_func("CURRENT_DATABASE"), 304 exp.CurrentSchemas: rename_func("CURRENT_SCHEMAS"), 305 exp.CountIf: rename_func("countIf"), 306 exp.CosineDistance: rename_func("cosineDistance"), 307 exp.CompressColumnConstraint: lambda self, e: ( 308 f"CODEC({self.expressions(e, key='this', flat=True)})" 309 ), 310 exp.ComputedColumnConstraint: lambda self, e: ( 311 f"{'MATERIALIZED' if e.args.get('persisted') else 'ALIAS'} {self.sql(e, 'this')}" 312 ), 313 exp.CurrentDate: lambda self, e: self.func("CURRENT_DATE"), 314 exp.CurrentVersion: rename_func("VERSION"), 315 exp.DateAdd: _datetime_delta_sql("DATE_ADD"), 316 exp.DateDiff: _datetime_delta_sql("DATE_DIFF"), 317 exp.DateStrToDate: rename_func("toDate"), 318 exp.DateSub: _datetime_delta_sql("DATE_SUB"), 319 exp.DayOfMonth: rename_func("toDayOfMonth"), 320 exp.DayOfWeekIso: rename_func("toDayOfWeek"), 321 exp.DayOfYear: rename_func("toDayOfYear"), 322 exp.Explode: rename_func("arrayJoin"), 323 exp.FarmFingerprint: rename_func("farmFingerprint64"), 324 exp.Final: lambda self, e: f"{self.sql(e, 'this')} FINAL", 325 exp.IsInf: rename_func("isInfinite"), 326 exp.IsNan: rename_func("isNaN"), 327 exp.JarowinklerSimilarity: jarowinkler_similarity("jaroWinklerSimilarity"), 328 exp.JSONCast: _json_cast_sql, 329 exp.JSONExtract: json_extract_segments("JSONExtractRaw", quoted_index=False), 330 exp.JSONExtractScalar: json_extract_segments("JSONExtractString", quoted_index=False), 331 exp.JSONPathKey: json_path_key_only_name, 332 exp.JSONPathRoot: lambda *_: "", 333 exp.Length: length_or_char_length_sql, 334 exp.Map: _map_sql, 335 exp.Median: rename_func("median"), 336 exp.Nullif: rename_func("nullIf"), 337 exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}", 338 exp.Pivot: no_pivot_sql, 339 exp.Quantile: _quantile_sql, 340 exp.RegexpLike: lambda self, e: self.func("match", e.this, e.expression), 341 exp.Rand: rename_func("randCanonical"), 342 exp.StartsWith: rename_func("startsWith"), 343 exp.Struct: rename_func("tuple"), 344 exp.Trunc: rename_func("trunc"), 345 exp.EndsWith: rename_func("endsWith"), 346 exp.EuclideanDistance: rename_func("L2Distance"), 347 exp.StrPosition: lambda self, e: strposition_sql( 348 self, 349 e, 350 func_name="POSITION", 351 supports_position=True, 352 use_ansi_position=False, 353 ), 354 exp.TimeToStr: lambda self, e: self.func( 355 "formatDateTime", 356 e.this.this if isinstance(e.this, exp.TsOrDsToTimestamp) else e.this, 357 self.format_time(e), 358 e.args.get("zone"), 359 ), 360 exp.TimeStrToTime: _timestrtotime_sql, 361 exp.TimestampAdd: _datetime_delta_sql("TIMESTAMP_ADD"), 362 exp.TimestampSub: _datetime_delta_sql("TIMESTAMP_SUB"), 363 exp.Typeof: rename_func("toTypeName"), 364 exp.VarMap: _map_sql, 365 exp.Xor: lambda self, e: self.func("xor", e.this, e.expression), 366 exp.MD5Digest: rename_func("MD5"), 367 exp.MD5: lambda self, e: self.func("LOWER", self.func("HEX", self.func("MD5", e.this))), 368 exp.SHA: rename_func("SHA1"), 369 exp.SHA1Digest: rename_func("SHA1"), 370 exp.SHA2: sha256_sql, 371 exp.SHA2Digest: sha2_digest_sql, 372 exp.Split: lambda self, e: self.func( 373 "splitByString", e.args.get("expression"), e.this, e.args.get("limit") 374 ), 375 exp.RegexpSplit: lambda self, e: self.func( 376 "splitByRegexp", e.args.get("expression"), e.this, e.args.get("limit") 377 ), 378 exp.UnixToTime: _unix_to_time_sql, 379 exp.Trim: lambda self, e: trim_sql(self, e, default_trim_type="BOTH"), 380 exp.Variance: rename_func("varSamp"), 381 exp.VariancePop: rename_func("varPop"), 382 exp.WeekOfYear: rename_func("toISOWeek"), 383 exp.YearOfWeekIso: rename_func("toISOYear"), 384 exp.SchemaCommentProperty: lambda self, e: self.naked_property(e), 385 exp.Stddev: rename_func("stddevSamp"), 386 exp.Chr: rename_func("CHAR"), 387 exp.Lag: rename_func("lag"), 388 exp.Lead: rename_func("lead"), 389 exp.Levenshtein: unsupported_args("ins_cost", "del_cost", "sub_cost", "max_dist")( 390 rename_func("editDistance") 391 ), 392 exp.ParseDatetime: lambda self, e: self.func( 393 "parseDateTime", e.this, e.args.get("format"), e.args.get("zone") 394 ), 395 } 396 397 PROPERTIES_LOCATION = { 398 **generator.Generator.PROPERTIES_LOCATION, 399 exp.AutoRefreshProperty: exp.Properties.Location.POST_NAME, 400 exp.DefinerProperty: exp.Properties.Location.POST_SCHEMA, 401 exp.OnCluster: exp.Properties.Location.POST_NAME, 402 exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA, 403 exp.ToTableProperty: exp.Properties.Location.POST_NAME, 404 exp.UuidProperty: exp.Properties.Location.POST_NAME, 405 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 406 } 407 408 # There's no list in docs, but it can be found in Clickhouse code 409 # see `ClickHouse/src/Parsers/ParserCreate*.cpp` 410 ON_CLUSTER_TARGETS: t.ClassVar = { 411 "SCHEMA", # Transpiled CREATE SCHEMA may have OnCluster property set 412 "DATABASE", 413 "TABLE", 414 "VIEW", 415 "DICTIONARY", 416 "INDEX", 417 "FUNCTION", 418 "NAMED COLLECTION", 419 } 420 421 # https://clickhouse.com/docs/en/sql-reference/data-types/nullable 422 NON_NULLABLE_TYPES: t.ClassVar = { 423 exp.DType.ARRAY, 424 exp.DType.MAP, 425 exp.DType.STRUCT, 426 exp.DType.POINT, 427 exp.DType.RING, 428 exp.DType.LINESTRING, 429 exp.DType.MULTILINESTRING, 430 exp.DType.POLYGON, 431 exp.DType.MULTIPOLYGON, 432 } 433 434 @unsupported_args("json_scope") 435 def contains_sql(self, expression: exp.Contains) -> str: 436 # ClickHouse has no CONTAINS; the comparison needs parentheses inside another operator 437 result = exp.StrPosition(this=expression.this, substr=expression.expression) > 0 438 if isinstance(expression.parent, exp.Binary) and not isinstance( 439 expression.parent, exp.Connector 440 ): 441 return self.sql(exp.paren(result, copy=False)) 442 return self.sql(result) 443 444 def groupconcat_sql(self, expression: exp.GroupConcat) -> str: 445 this = expression.this 446 separator = expression.args.get("separator") 447 448 if isinstance(this, exp.Limit) and this.this: 449 limit = this 450 this = limit.this.pop() 451 return self.sql( 452 exp.ParameterizedAgg( 453 this="groupConcat", 454 params=[this], 455 expressions=[separator, limit.expression], 456 ) 457 ) 458 459 if separator: 460 return self.sql( 461 exp.ParameterizedAgg( 462 this="groupConcat", 463 params=[this], 464 expressions=[separator], 465 ) 466 ) 467 468 return self.func("groupConcat", this) 469 470 def select_sql(self, expression: exp.Select) -> str: 471 limit = expression.args.get("limit") 472 if isinstance(limit, exp.Fetch) and not expression.args.get("order"): 473 count = limit.args.get("count") 474 expression.set( 475 "limit", exp.Limit(expression=count if count is not None else exp.Literal.number(1)) 476 ) 477 return super().select_sql(expression) 478 479 def offset_sql(self, expression: exp.Offset) -> str: 480 offset = super().offset_sql(expression) 481 482 # OFFSET ... FETCH syntax requires a "ROW" or "ROWS" keyword 483 # https://clickhouse.com/docs/sql-reference/statements/select/offset 484 parent = expression.parent 485 if isinstance(parent, exp.Select) and isinstance(parent.args.get("limit"), exp.Fetch): 486 offset = f"{offset} ROWS" 487 488 return offset 489 490 def strtodate_sql(self, expression: exp.StrToDate) -> str: 491 strtodate_sql = self.function_fallback_sql(expression) 492 493 if not isinstance(expression.parent, exp.Cast): 494 # StrToDate returns DATEs in other dialects (eg. postgres), so 495 # this branch aims to improve the transpilation to clickhouse 496 return self.cast_sql(exp.cast(expression, "DATE")) 497 498 return strtodate_sql 499 500 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 501 this = expression.this 502 503 if isinstance(this, exp.StrToDate) and expression.to == exp.DType.DATETIME.into_expr(): 504 return self.sql(this) 505 506 this = this.unnest() 507 if ( 508 isinstance(this, exp.JSONExtract) 509 and this.args.get("requires_json") 510 and expression.to.is_type(*exp.DataType.TEXT_TYPES) 511 ): 512 return self.func("JSONExtract", this, exp.Literal.string("Nullable(String)")) 513 514 return super().cast_sql(expression, safe_prefix=safe_prefix) 515 516 def trycast_sql(self, expression: exp.TryCast) -> str: 517 dtype = expression.to 518 if not dtype.is_type(*self.NON_NULLABLE_TYPES, check_nullable=True): 519 # Casting x into Nullable(T) appears to behave similarly to TRY_CAST(x AS T) 520 dtype.set("nullable", True) 521 522 return super().cast_sql(expression) 523 524 def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str: 525 this = self.json_path_part(expression.this) 526 return str(int(this) + 1) if is_int(this) else this 527 528 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 529 return f"AS {self.sql(expression, 'this')}" 530 531 def _any_to_has( 532 self, 533 expression: exp.EQ | exp.NEQ, 534 default: t.Callable[[t.Any], str], 535 prefix: str = "", 536 ) -> str: 537 if isinstance(expression.left, exp.Any): 538 arr = expression.left 539 this = expression.right 540 elif isinstance(expression.right, exp.Any): 541 arr = expression.right 542 this = expression.left 543 else: 544 return default(expression) 545 546 return prefix + self.func("has", arr.this.unnest(), this) 547 548 def eq_sql(self, expression: exp.EQ) -> str: 549 return self._any_to_has(expression, super().eq_sql) 550 551 def neq_sql(self, expression: exp.NEQ) -> str: 552 return self._any_to_has(expression, super().neq_sql, "NOT ") 553 554 def regexpcount_sql(self, expression: exp.RegexpCount) -> str: 555 this = expression.this 556 pattern = expression.expression 557 position = expression.args.get("position") 558 parameters = expression.args.get("parameters") 559 560 if position: 561 # SUBSTRING counts bytes in ClickHouse, the position counts characters 562 this = self.func("substringUTF8", this, position) 563 564 if parameters: 565 flags = parameters.name if parameters.is_string else "" 566 if not parameters.is_string or set(flags) - set("cims"): 567 self.unsupported("Only literal 'c', 'i', 'm' and 's' regexp flags are supported") 568 # "c" (case-sensitive) is the default, and the last of "c" and "i" wins 569 if flags.rfind("c") > flags.rfind("i"): 570 flags = flags.replace("i", "") 571 flags = "".join(f for f in flags if f in "ims") 572 if flags: 573 # countMatches has no flags argument, so they are embedded in the pattern 574 pattern = self.func("CONCAT", exp.Literal.string(f"(?{flags})"), pattern) 575 576 return self.func("countMatches", this, pattern) 577 578 def regexpilike_sql(self, expression: exp.RegexpILike) -> str: 579 # Manually add a flag to make the search case-insensitive 580 regex = self.func("CONCAT", "'(?i)'", expression.expression) 581 return self.func("match", expression.this, regex) 582 583 def datatype_sql(self, expression: exp.DataType) -> str: 584 # String is the standard ClickHouse type, every other variant is just an alias. 585 # Additionally, any supplied length parameter will be ignored. 586 # 587 # https://clickhouse.com/docs/en/sql-reference/data-types/string 588 if expression.this in self.STRING_TYPE_MAPPING: 589 dtype = "String" 590 else: 591 dtype = super().datatype_sql(expression) 592 593 # This section changes the type to `Nullable(...)` if the following conditions hold: 594 # - It's marked as nullable - this ensures we won't wrap ClickHouse types with `Nullable` 595 # and change their semantics 596 # - It's not the key type of a `Map`. This is because ClickHouse enforces the following 597 # constraint: "Type of Map key must be a type, that can be represented by integer or 598 # String or FixedString (possibly LowCardinality) or UUID or IPv6" 599 # - It's not a composite type, e.g. `Nullable(Array(...))` is not a valid type 600 parent = expression.parent 601 nullable = expression.args.get("nullable") 602 if nullable is True or ( 603 nullable is None 604 and not ( 605 isinstance(parent, exp.DataType) 606 and parent.is_type(exp.DType.MAP, check_nullable=True) 607 and expression.index in (None, 0) 608 ) 609 and not expression.is_type(*self.NON_NULLABLE_TYPES, check_nullable=True) 610 ): 611 dtype = f"Nullable({dtype})" 612 613 return dtype 614 615 def cte_sql(self, expression: exp.CTE) -> str: 616 if expression.args.get("scalar"): 617 this = self.sql(expression, "this") 618 alias = self.sql(expression, "alias") 619 return f"{this} AS {alias}" 620 621 return super().cte_sql(expression) 622 623 def after_limit_modifiers(self, expression: exp.Expr) -> list[str]: 624 return super().after_limit_modifiers(expression) + [ 625 ( 626 self.seg("SETTINGS ") + self.expressions(expression, key="settings", flat=True) 627 if expression.args.get("settings") 628 else "" 629 ), 630 ( 631 self.seg("FORMAT ") + self.sql(expression, "format") 632 if expression.args.get("format") 633 else "" 634 ), 635 ] 636 637 def placeholder_sql(self, expression: exp.Placeholder) -> str: 638 return f"{{{expression.name}: {self.sql(expression, 'kind')}}}" 639 640 def oncluster_sql(self, expression: exp.OnCluster) -> str: 641 return f"ON CLUSTER {self.sql(expression, 'this')}" 642 643 def _refresh_interval_sql(self, expression: exp.Expr) -> str: 644 if isinstance(expression, exp.Add): 645 return f"{self._refresh_interval_sql(expression.this)} {self._refresh_interval_sql(expression.expression)}" 646 return self.sql(expression.assert_is(exp.Interval)) 647 648 def autorefreshproperty_sql(self, expression: exp.AutoRefreshProperty) -> str: 649 cadence = self.sql(expression, "cadence") 650 interval = expression.this 651 schedule = ( 652 f" {cadence} {self._refresh_interval_sql(interval)}" if cadence and interval else "" 653 ) 654 offset = expression.args.get("offset") 655 offset = f" OFFSET {self._refresh_interval_sql(offset)}" if offset else "" 656 randomize = expression.args.get("randomize") 657 randomize = f" RANDOMIZE FOR {self._refresh_interval_sql(randomize)}" if randomize else "" 658 dependencies = self.expressions(expression, flat=True) 659 dependencies = f" DEPENDS ON {dependencies}" if dependencies else "" 660 settings = self.sql(expression, "settings") 661 settings = f" {settings}" if settings else "" 662 append = " APPEND" if expression.args.get("append") else "" 663 664 return f"REFRESH{schedule}{offset}{randomize}{dependencies}{settings}{append}" 665 666 def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str: 667 if expression.kind in self.ON_CLUSTER_TARGETS and locations.get( 668 exp.Properties.Location.POST_NAME 669 ): 670 this_name = self.sql( 671 expression.this if isinstance(expression.this, exp.Schema) else expression, 672 "this", 673 ) 674 this_properties = " ".join( 675 [self.sql(prop) for prop in locations[exp.Properties.Location.POST_NAME]] 676 ) 677 this_schema = self.schema_columns_sql(expression.this) 678 this_schema = f"{self.sep()}{this_schema}" if this_schema else "" 679 680 return f"{this_name}{self.sep()}{this_properties}{this_schema}" 681 682 return super().createable_sql(expression, locations) 683 684 def create_sql(self, expression: exp.Create) -> str: 685 # The comment property comes last in CTAS statements, i.e. after the query 686 query = expression.expression 687 if isinstance(query, exp.Query): 688 comment_prop = expression.find(exp.SchemaCommentProperty) 689 if comment_prop: 690 comment_prop.pop() 691 if not isinstance(query, exp.Subquery): 692 query.replace(exp.paren(query)) 693 else: 694 comment_prop = None 695 696 create_sql = super().create_sql(expression) 697 698 comment_sql = self.sql(comment_prop) 699 comment_sql = f" {comment_sql}" if comment_sql else "" 700 701 return f"{create_sql}{comment_sql}" 702 703 def prewhere_sql(self, expression: exp.PreWhere) -> str: 704 this = self.indent(self.sql(expression, "this")) 705 return f"{self.seg('PREWHERE')}{self.sep()}{this}" 706 707 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 708 this = self.sql(expression, "this") 709 this = f" {this}" if this else "" 710 expr = self.sql(expression, "expression") 711 expr = f" {expr}" if expr else "" 712 index_type = self.sql(expression, "index_type") 713 index_type = f" TYPE {index_type}" if index_type else "" 714 granularity = self.sql(expression, "granularity") 715 granularity = f" GRANULARITY {granularity}" if granularity else "" 716 717 return f"INDEX{this}{expr}{index_type}{granularity}" 718 719 def partition_sql(self, expression: exp.Partition) -> str: 720 return f"PARTITION {self.expressions(expression, flat=True)}" 721 722 def partitionid_sql(self, expression: exp.PartitionId) -> str: 723 return f"ID {self.sql(expression.this)}" 724 725 def replacepartition_sql(self, expression: exp.ReplacePartition) -> str: 726 return f"REPLACE {self.sql(expression.expression)} FROM {self.sql(expression, 'source')}" 727 728 def projectiondef_sql(self, expression: exp.ProjectionDef) -> str: 729 return f"PROJECTION {self.sql(expression.this)} {self.wrap(expression.expression)}" 730 731 def nestedjsonselect_sql(self, expression: exp.NestedJSONSelect) -> str: 732 return f"{self.sql(expression, 'this')}.^{self.sql(expression, 'expression')}" 733 734 def is_sql(self, expression: exp.Is) -> str: 735 is_sql = super().is_sql(expression) 736 737 if isinstance(expression.parent, exp.Not): 738 # value IS NOT NULL -> NOT (value IS NULL) 739 is_sql = self.wrap(is_sql) 740 741 return is_sql 742 743 def in_sql(self, expression: exp.In) -> str: 744 in_sql = super().in_sql(expression) 745 746 if isinstance(expression.parent, exp.Not) and expression.args.get("is_global"): 747 in_sql = in_sql.replace("GLOBAL IN", "GLOBAL NOT IN", 1) 748 749 return in_sql 750 751 def not_sql(self, expression: exp.Not) -> str: 752 if isinstance(expression.this, exp.In): 753 if expression.this.args.get("is_global"): 754 # let `GLOBAL IN` child interpose `NOT` 755 return self.sql(expression, "this") 756 757 expression.set("this", exp.paren(expression.this, copy=False)) 758 759 return super().not_sql(expression) 760 761 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 762 # If the VALUES clause contains tuples of expressions, we need to treat it 763 # as a table since Clickhouse will automatically alias it as such. 764 alias = expression.args.get("alias") 765 766 if alias and alias.args.get("columns") and expression.expressions: 767 values = expression.expressions[0].expressions 768 values_as_table = any(isinstance(value, exp.Tuple) for value in values) 769 else: 770 values_as_table = True 771 772 return super().values_sql(expression, values_as_table=values_as_table) 773 774 def timestamptrunc_sql(self, expression: exp.DateTrunc | exp.TimestampTrunc) -> str: 775 unit = weekstart_unit_to_str(self, expression) 776 # https://clickhouse.com/docs/whats-new/changelog/2023#improvement 777 if self.dialect.version < (23, 12) and unit and unit.is_string: 778 unit = exp.Literal.string(unit.name.lower()) 779 return self.func("dateTrunc", unit, expression.this, expression.args.get("zone")) 780 781 def datetrunc_sql(self, expression: exp.DateTrunc) -> str: 782 return self.timestamptrunc_sql(expression)
167class ClickHouseGenerator(generator.Generator): 168 BYTE_STRING_FUNCTION = "unhex" 169 SELECT_KINDS: tuple[str, ...] = () 170 TRY_SUPPORTED = False 171 SUPPORTS_UESCAPE = False 172 SUPPORTS_DECODE_CASE = False 173 174 AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS 175 176 QUERY_HINTS = False 177 STRUCT_DELIMITER = ("(", ")") 178 NVL2_SUPPORTED = False 179 ALTER_SET_TYPE = "TYPE" 180 SUPPORTS_ALTER_COLUMN_IF_EXISTS = True 181 TABLESAMPLE_REQUIRES_PARENS = False 182 TABLESAMPLE_SIZE_IS_ROWS = False 183 TABLESAMPLE_KEYWORDS = "SAMPLE" 184 LAST_DAY_SUPPORTS_DATE_PART = False 185 CAN_IMPLEMENT_ARRAY_ANY = True 186 SUPPORTS_TO_NUMBER = False 187 JOIN_HINTS = False 188 TABLE_HINTS = False 189 GROUPINGS_SEP = "" 190 SET_OP_MODIFIERS = False 191 SET_OP_LIMITS = True 192 ARRAY_SIZE_NAME = "LENGTH" 193 WRAP_DERIVED_VALUES = False 194 AUTO_REFRESH_BARE_INTERVALS = True 195 196 STRING_TYPE_MAPPING: t.ClassVar = { 197 exp.DType.BLOB: "String", 198 exp.DType.CHAR: "String", 199 exp.DType.LONGBLOB: "String", 200 exp.DType.LONGTEXT: "String", 201 exp.DType.MEDIUMBLOB: "String", 202 exp.DType.MEDIUMTEXT: "String", 203 exp.DType.TINYBLOB: "String", 204 exp.DType.TINYTEXT: "String", 205 exp.DType.TEXT: "String", 206 exp.DType.VARBINARY: "String", 207 exp.DType.VARCHAR: "String", 208 } 209 210 SUPPORTED_JSON_PATH_PARTS = { 211 exp.JSONPathKey, 212 exp.JSONPathRoot, 213 exp.JSONPathSubscript, 214 } 215 216 TYPE_MAPPING = { 217 **generator.Generator.TYPE_MAPPING, 218 exp.DType.BLOB: "String", 219 exp.DType.CHAR: "String", 220 exp.DType.LONGBLOB: "String", 221 exp.DType.LONGTEXT: "String", 222 exp.DType.MEDIUMBLOB: "String", 223 exp.DType.MEDIUMTEXT: "String", 224 exp.DType.TINYBLOB: "String", 225 exp.DType.TINYTEXT: "String", 226 exp.DType.TEXT: "String", 227 exp.DType.VARBINARY: "String", 228 exp.DType.VARCHAR: "String", 229 exp.DType.ARRAY: "Array", 230 exp.DType.BOOLEAN: "Bool", 231 exp.DType.BIGINT: "Int64", 232 exp.DType.DATE32: "Date32", 233 exp.DType.DATETIME: "DateTime", 234 exp.DType.DATETIME2: "DateTime", 235 exp.DType.SMALLDATETIME: "DateTime", 236 exp.DType.DATETIME64: "DateTime64", 237 exp.DType.DECIMAL: "Decimal", 238 exp.DType.DECIMAL32: "Decimal32", 239 exp.DType.DECIMAL64: "Decimal64", 240 exp.DType.DECIMAL128: "Decimal128", 241 exp.DType.DECIMAL256: "Decimal256", 242 exp.DType.TIMESTAMP: "DateTime", 243 exp.DType.TIMESTAMPNTZ: "DateTime", 244 exp.DType.TIMESTAMPTZ: "DateTime", 245 exp.DType.DOUBLE: "Float64", 246 exp.DType.ENUM: "Enum", 247 exp.DType.ENUM8: "Enum8", 248 exp.DType.ENUM16: "Enum16", 249 exp.DType.FIXEDSTRING: "FixedString", 250 exp.DType.FLOAT: "Float32", 251 exp.DType.INT: "Int32", 252 exp.DType.MEDIUMINT: "Int32", 253 exp.DType.INT128: "Int128", 254 exp.DType.INT256: "Int256", 255 exp.DType.LOWCARDINALITY: "LowCardinality", 256 exp.DType.MAP: "Map", 257 exp.DType.NESTED: "Nested", 258 exp.DType.NOTHING: "Nothing", 259 exp.DType.SMALLINT: "Int16", 260 exp.DType.STRUCT: "Tuple", 261 exp.DType.TINYINT: "Int8", 262 exp.DType.UBIGINT: "UInt64", 263 exp.DType.UINT: "UInt32", 264 exp.DType.UINT128: "UInt128", 265 exp.DType.UINT256: "UInt256", 266 exp.DType.USMALLINT: "UInt16", 267 exp.DType.UTINYINT: "UInt8", 268 exp.DType.IPV4: "IPv4", 269 exp.DType.IPV6: "IPv6", 270 exp.DType.POINT: "Point", 271 exp.DType.RING: "Ring", 272 exp.DType.LINESTRING: "LineString", 273 exp.DType.MULTILINESTRING: "MultiLineString", 274 exp.DType.POLYGON: "Polygon", 275 exp.DType.MULTIPOLYGON: "MultiPolygon", 276 exp.DType.AGGREGATEFUNCTION: "AggregateFunction", 277 exp.DType.SIMPLEAGGREGATEFUNCTION: "SimpleAggregateFunction", 278 exp.DType.DYNAMIC: "Dynamic", 279 } 280 281 TRANSFORMS = { 282 **{k: v for k, v in generator.Generator.TRANSFORMS.items() if k != exp.AutoRefreshProperty}, 283 exp.AnyValue: rename_func("any"), 284 exp.ApproxDistinct: rename_func("uniq"), 285 exp.ArrayDistinct: rename_func("arrayDistinct"), 286 exp.ArrayConcat: rename_func("arrayConcat"), 287 exp.ArrayContains: rename_func("has"), 288 exp.ArrayFilter: lambda self, e: self.func("arrayFilter", e.expression, e.this), 289 exp.Transform: lambda self, e: self.func("arrayMap", e.expression, e.this), 290 exp.ArrayRemove: remove_from_array_using_filter, 291 exp.ArrayReverse: rename_func("arrayReverse"), 292 exp.ArraySlice: rename_func("arraySlice"), 293 exp.ArraySum: rename_func("arraySum"), 294 exp.ArrayMax: rename_func("arrayMax"), 295 exp.ArrayMin: rename_func("arrayMin"), 296 exp.ArgMax: arg_max_or_min_no_count("argMax"), 297 exp.ArgMin: arg_max_or_min_no_count("argMin"), 298 exp.Array: inline_array_sql, 299 exp.BitwiseAndAgg: rename_func("groupBitAnd"), 300 exp.BitwiseOrAgg: rename_func("groupBitOr"), 301 exp.BitwiseXorAgg: rename_func("groupBitXor"), 302 exp.CityHash64: rename_func("cityHash64"), 303 exp.CastToStrType: rename_func("CAST"), 304 exp.CurrentDatabase: rename_func("CURRENT_DATABASE"), 305 exp.CurrentSchemas: rename_func("CURRENT_SCHEMAS"), 306 exp.CountIf: rename_func("countIf"), 307 exp.CosineDistance: rename_func("cosineDistance"), 308 exp.CompressColumnConstraint: lambda self, e: ( 309 f"CODEC({self.expressions(e, key='this', flat=True)})" 310 ), 311 exp.ComputedColumnConstraint: lambda self, e: ( 312 f"{'MATERIALIZED' if e.args.get('persisted') else 'ALIAS'} {self.sql(e, 'this')}" 313 ), 314 exp.CurrentDate: lambda self, e: self.func("CURRENT_DATE"), 315 exp.CurrentVersion: rename_func("VERSION"), 316 exp.DateAdd: _datetime_delta_sql("DATE_ADD"), 317 exp.DateDiff: _datetime_delta_sql("DATE_DIFF"), 318 exp.DateStrToDate: rename_func("toDate"), 319 exp.DateSub: _datetime_delta_sql("DATE_SUB"), 320 exp.DayOfMonth: rename_func("toDayOfMonth"), 321 exp.DayOfWeekIso: rename_func("toDayOfWeek"), 322 exp.DayOfYear: rename_func("toDayOfYear"), 323 exp.Explode: rename_func("arrayJoin"), 324 exp.FarmFingerprint: rename_func("farmFingerprint64"), 325 exp.Final: lambda self, e: f"{self.sql(e, 'this')} FINAL", 326 exp.IsInf: rename_func("isInfinite"), 327 exp.IsNan: rename_func("isNaN"), 328 exp.JarowinklerSimilarity: jarowinkler_similarity("jaroWinklerSimilarity"), 329 exp.JSONCast: _json_cast_sql, 330 exp.JSONExtract: json_extract_segments("JSONExtractRaw", quoted_index=False), 331 exp.JSONExtractScalar: json_extract_segments("JSONExtractString", quoted_index=False), 332 exp.JSONPathKey: json_path_key_only_name, 333 exp.JSONPathRoot: lambda *_: "", 334 exp.Length: length_or_char_length_sql, 335 exp.Map: _map_sql, 336 exp.Median: rename_func("median"), 337 exp.Nullif: rename_func("nullIf"), 338 exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}", 339 exp.Pivot: no_pivot_sql, 340 exp.Quantile: _quantile_sql, 341 exp.RegexpLike: lambda self, e: self.func("match", e.this, e.expression), 342 exp.Rand: rename_func("randCanonical"), 343 exp.StartsWith: rename_func("startsWith"), 344 exp.Struct: rename_func("tuple"), 345 exp.Trunc: rename_func("trunc"), 346 exp.EndsWith: rename_func("endsWith"), 347 exp.EuclideanDistance: rename_func("L2Distance"), 348 exp.StrPosition: lambda self, e: strposition_sql( 349 self, 350 e, 351 func_name="POSITION", 352 supports_position=True, 353 use_ansi_position=False, 354 ), 355 exp.TimeToStr: lambda self, e: self.func( 356 "formatDateTime", 357 e.this.this if isinstance(e.this, exp.TsOrDsToTimestamp) else e.this, 358 self.format_time(e), 359 e.args.get("zone"), 360 ), 361 exp.TimeStrToTime: _timestrtotime_sql, 362 exp.TimestampAdd: _datetime_delta_sql("TIMESTAMP_ADD"), 363 exp.TimestampSub: _datetime_delta_sql("TIMESTAMP_SUB"), 364 exp.Typeof: rename_func("toTypeName"), 365 exp.VarMap: _map_sql, 366 exp.Xor: lambda self, e: self.func("xor", e.this, e.expression), 367 exp.MD5Digest: rename_func("MD5"), 368 exp.MD5: lambda self, e: self.func("LOWER", self.func("HEX", self.func("MD5", e.this))), 369 exp.SHA: rename_func("SHA1"), 370 exp.SHA1Digest: rename_func("SHA1"), 371 exp.SHA2: sha256_sql, 372 exp.SHA2Digest: sha2_digest_sql, 373 exp.Split: lambda self, e: self.func( 374 "splitByString", e.args.get("expression"), e.this, e.args.get("limit") 375 ), 376 exp.RegexpSplit: lambda self, e: self.func( 377 "splitByRegexp", e.args.get("expression"), e.this, e.args.get("limit") 378 ), 379 exp.UnixToTime: _unix_to_time_sql, 380 exp.Trim: lambda self, e: trim_sql(self, e, default_trim_type="BOTH"), 381 exp.Variance: rename_func("varSamp"), 382 exp.VariancePop: rename_func("varPop"), 383 exp.WeekOfYear: rename_func("toISOWeek"), 384 exp.YearOfWeekIso: rename_func("toISOYear"), 385 exp.SchemaCommentProperty: lambda self, e: self.naked_property(e), 386 exp.Stddev: rename_func("stddevSamp"), 387 exp.Chr: rename_func("CHAR"), 388 exp.Lag: rename_func("lag"), 389 exp.Lead: rename_func("lead"), 390 exp.Levenshtein: unsupported_args("ins_cost", "del_cost", "sub_cost", "max_dist")( 391 rename_func("editDistance") 392 ), 393 exp.ParseDatetime: lambda self, e: self.func( 394 "parseDateTime", e.this, e.args.get("format"), e.args.get("zone") 395 ), 396 } 397 398 PROPERTIES_LOCATION = { 399 **generator.Generator.PROPERTIES_LOCATION, 400 exp.AutoRefreshProperty: exp.Properties.Location.POST_NAME, 401 exp.DefinerProperty: exp.Properties.Location.POST_SCHEMA, 402 exp.OnCluster: exp.Properties.Location.POST_NAME, 403 exp.PartitionedByProperty: exp.Properties.Location.POST_SCHEMA, 404 exp.ToTableProperty: exp.Properties.Location.POST_NAME, 405 exp.UuidProperty: exp.Properties.Location.POST_NAME, 406 exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, 407 } 408 409 # There's no list in docs, but it can be found in Clickhouse code 410 # see `ClickHouse/src/Parsers/ParserCreate*.cpp` 411 ON_CLUSTER_TARGETS: t.ClassVar = { 412 "SCHEMA", # Transpiled CREATE SCHEMA may have OnCluster property set 413 "DATABASE", 414 "TABLE", 415 "VIEW", 416 "DICTIONARY", 417 "INDEX", 418 "FUNCTION", 419 "NAMED COLLECTION", 420 } 421 422 # https://clickhouse.com/docs/en/sql-reference/data-types/nullable 423 NON_NULLABLE_TYPES: t.ClassVar = { 424 exp.DType.ARRAY, 425 exp.DType.MAP, 426 exp.DType.STRUCT, 427 exp.DType.POINT, 428 exp.DType.RING, 429 exp.DType.LINESTRING, 430 exp.DType.MULTILINESTRING, 431 exp.DType.POLYGON, 432 exp.DType.MULTIPOLYGON, 433 } 434 435 @unsupported_args("json_scope") 436 def contains_sql(self, expression: exp.Contains) -> str: 437 # ClickHouse has no CONTAINS; the comparison needs parentheses inside another operator 438 result = exp.StrPosition(this=expression.this, substr=expression.expression) > 0 439 if isinstance(expression.parent, exp.Binary) and not isinstance( 440 expression.parent, exp.Connector 441 ): 442 return self.sql(exp.paren(result, copy=False)) 443 return self.sql(result) 444 445 def groupconcat_sql(self, expression: exp.GroupConcat) -> str: 446 this = expression.this 447 separator = expression.args.get("separator") 448 449 if isinstance(this, exp.Limit) and this.this: 450 limit = this 451 this = limit.this.pop() 452 return self.sql( 453 exp.ParameterizedAgg( 454 this="groupConcat", 455 params=[this], 456 expressions=[separator, limit.expression], 457 ) 458 ) 459 460 if separator: 461 return self.sql( 462 exp.ParameterizedAgg( 463 this="groupConcat", 464 params=[this], 465 expressions=[separator], 466 ) 467 ) 468 469 return self.func("groupConcat", this) 470 471 def select_sql(self, expression: exp.Select) -> str: 472 limit = expression.args.get("limit") 473 if isinstance(limit, exp.Fetch) and not expression.args.get("order"): 474 count = limit.args.get("count") 475 expression.set( 476 "limit", exp.Limit(expression=count if count is not None else exp.Literal.number(1)) 477 ) 478 return super().select_sql(expression) 479 480 def offset_sql(self, expression: exp.Offset) -> str: 481 offset = super().offset_sql(expression) 482 483 # OFFSET ... FETCH syntax requires a "ROW" or "ROWS" keyword 484 # https://clickhouse.com/docs/sql-reference/statements/select/offset 485 parent = expression.parent 486 if isinstance(parent, exp.Select) and isinstance(parent.args.get("limit"), exp.Fetch): 487 offset = f"{offset} ROWS" 488 489 return offset 490 491 def strtodate_sql(self, expression: exp.StrToDate) -> str: 492 strtodate_sql = self.function_fallback_sql(expression) 493 494 if not isinstance(expression.parent, exp.Cast): 495 # StrToDate returns DATEs in other dialects (eg. postgres), so 496 # this branch aims to improve the transpilation to clickhouse 497 return self.cast_sql(exp.cast(expression, "DATE")) 498 499 return strtodate_sql 500 501 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 502 this = expression.this 503 504 if isinstance(this, exp.StrToDate) and expression.to == exp.DType.DATETIME.into_expr(): 505 return self.sql(this) 506 507 this = this.unnest() 508 if ( 509 isinstance(this, exp.JSONExtract) 510 and this.args.get("requires_json") 511 and expression.to.is_type(*exp.DataType.TEXT_TYPES) 512 ): 513 return self.func("JSONExtract", this, exp.Literal.string("Nullable(String)")) 514 515 return super().cast_sql(expression, safe_prefix=safe_prefix) 516 517 def trycast_sql(self, expression: exp.TryCast) -> str: 518 dtype = expression.to 519 if not dtype.is_type(*self.NON_NULLABLE_TYPES, check_nullable=True): 520 # Casting x into Nullable(T) appears to behave similarly to TRY_CAST(x AS T) 521 dtype.set("nullable", True) 522 523 return super().cast_sql(expression) 524 525 def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str: 526 this = self.json_path_part(expression.this) 527 return str(int(this) + 1) if is_int(this) else this 528 529 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 530 return f"AS {self.sql(expression, 'this')}" 531 532 def _any_to_has( 533 self, 534 expression: exp.EQ | exp.NEQ, 535 default: t.Callable[[t.Any], str], 536 prefix: str = "", 537 ) -> str: 538 if isinstance(expression.left, exp.Any): 539 arr = expression.left 540 this = expression.right 541 elif isinstance(expression.right, exp.Any): 542 arr = expression.right 543 this = expression.left 544 else: 545 return default(expression) 546 547 return prefix + self.func("has", arr.this.unnest(), this) 548 549 def eq_sql(self, expression: exp.EQ) -> str: 550 return self._any_to_has(expression, super().eq_sql) 551 552 def neq_sql(self, expression: exp.NEQ) -> str: 553 return self._any_to_has(expression, super().neq_sql, "NOT ") 554 555 def regexpcount_sql(self, expression: exp.RegexpCount) -> str: 556 this = expression.this 557 pattern = expression.expression 558 position = expression.args.get("position") 559 parameters = expression.args.get("parameters") 560 561 if position: 562 # SUBSTRING counts bytes in ClickHouse, the position counts characters 563 this = self.func("substringUTF8", this, position) 564 565 if parameters: 566 flags = parameters.name if parameters.is_string else "" 567 if not parameters.is_string or set(flags) - set("cims"): 568 self.unsupported("Only literal 'c', 'i', 'm' and 's' regexp flags are supported") 569 # "c" (case-sensitive) is the default, and the last of "c" and "i" wins 570 if flags.rfind("c") > flags.rfind("i"): 571 flags = flags.replace("i", "") 572 flags = "".join(f for f in flags if f in "ims") 573 if flags: 574 # countMatches has no flags argument, so they are embedded in the pattern 575 pattern = self.func("CONCAT", exp.Literal.string(f"(?{flags})"), pattern) 576 577 return self.func("countMatches", this, pattern) 578 579 def regexpilike_sql(self, expression: exp.RegexpILike) -> str: 580 # Manually add a flag to make the search case-insensitive 581 regex = self.func("CONCAT", "'(?i)'", expression.expression) 582 return self.func("match", expression.this, regex) 583 584 def datatype_sql(self, expression: exp.DataType) -> str: 585 # String is the standard ClickHouse type, every other variant is just an alias. 586 # Additionally, any supplied length parameter will be ignored. 587 # 588 # https://clickhouse.com/docs/en/sql-reference/data-types/string 589 if expression.this in self.STRING_TYPE_MAPPING: 590 dtype = "String" 591 else: 592 dtype = super().datatype_sql(expression) 593 594 # This section changes the type to `Nullable(...)` if the following conditions hold: 595 # - It's marked as nullable - this ensures we won't wrap ClickHouse types with `Nullable` 596 # and change their semantics 597 # - It's not the key type of a `Map`. This is because ClickHouse enforces the following 598 # constraint: "Type of Map key must be a type, that can be represented by integer or 599 # String or FixedString (possibly LowCardinality) or UUID or IPv6" 600 # - It's not a composite type, e.g. `Nullable(Array(...))` is not a valid type 601 parent = expression.parent 602 nullable = expression.args.get("nullable") 603 if nullable is True or ( 604 nullable is None 605 and not ( 606 isinstance(parent, exp.DataType) 607 and parent.is_type(exp.DType.MAP, check_nullable=True) 608 and expression.index in (None, 0) 609 ) 610 and not expression.is_type(*self.NON_NULLABLE_TYPES, check_nullable=True) 611 ): 612 dtype = f"Nullable({dtype})" 613 614 return dtype 615 616 def cte_sql(self, expression: exp.CTE) -> str: 617 if expression.args.get("scalar"): 618 this = self.sql(expression, "this") 619 alias = self.sql(expression, "alias") 620 return f"{this} AS {alias}" 621 622 return super().cte_sql(expression) 623 624 def after_limit_modifiers(self, expression: exp.Expr) -> list[str]: 625 return super().after_limit_modifiers(expression) + [ 626 ( 627 self.seg("SETTINGS ") + self.expressions(expression, key="settings", flat=True) 628 if expression.args.get("settings") 629 else "" 630 ), 631 ( 632 self.seg("FORMAT ") + self.sql(expression, "format") 633 if expression.args.get("format") 634 else "" 635 ), 636 ] 637 638 def placeholder_sql(self, expression: exp.Placeholder) -> str: 639 return f"{{{expression.name}: {self.sql(expression, 'kind')}}}" 640 641 def oncluster_sql(self, expression: exp.OnCluster) -> str: 642 return f"ON CLUSTER {self.sql(expression, 'this')}" 643 644 def _refresh_interval_sql(self, expression: exp.Expr) -> str: 645 if isinstance(expression, exp.Add): 646 return f"{self._refresh_interval_sql(expression.this)} {self._refresh_interval_sql(expression.expression)}" 647 return self.sql(expression.assert_is(exp.Interval)) 648 649 def autorefreshproperty_sql(self, expression: exp.AutoRefreshProperty) -> str: 650 cadence = self.sql(expression, "cadence") 651 interval = expression.this 652 schedule = ( 653 f" {cadence} {self._refresh_interval_sql(interval)}" if cadence and interval else "" 654 ) 655 offset = expression.args.get("offset") 656 offset = f" OFFSET {self._refresh_interval_sql(offset)}" if offset else "" 657 randomize = expression.args.get("randomize") 658 randomize = f" RANDOMIZE FOR {self._refresh_interval_sql(randomize)}" if randomize else "" 659 dependencies = self.expressions(expression, flat=True) 660 dependencies = f" DEPENDS ON {dependencies}" if dependencies else "" 661 settings = self.sql(expression, "settings") 662 settings = f" {settings}" if settings else "" 663 append = " APPEND" if expression.args.get("append") else "" 664 665 return f"REFRESH{schedule}{offset}{randomize}{dependencies}{settings}{append}" 666 667 def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str: 668 if expression.kind in self.ON_CLUSTER_TARGETS and locations.get( 669 exp.Properties.Location.POST_NAME 670 ): 671 this_name = self.sql( 672 expression.this if isinstance(expression.this, exp.Schema) else expression, 673 "this", 674 ) 675 this_properties = " ".join( 676 [self.sql(prop) for prop in locations[exp.Properties.Location.POST_NAME]] 677 ) 678 this_schema = self.schema_columns_sql(expression.this) 679 this_schema = f"{self.sep()}{this_schema}" if this_schema else "" 680 681 return f"{this_name}{self.sep()}{this_properties}{this_schema}" 682 683 return super().createable_sql(expression, locations) 684 685 def create_sql(self, expression: exp.Create) -> str: 686 # The comment property comes last in CTAS statements, i.e. after the query 687 query = expression.expression 688 if isinstance(query, exp.Query): 689 comment_prop = expression.find(exp.SchemaCommentProperty) 690 if comment_prop: 691 comment_prop.pop() 692 if not isinstance(query, exp.Subquery): 693 query.replace(exp.paren(query)) 694 else: 695 comment_prop = None 696 697 create_sql = super().create_sql(expression) 698 699 comment_sql = self.sql(comment_prop) 700 comment_sql = f" {comment_sql}" if comment_sql else "" 701 702 return f"{create_sql}{comment_sql}" 703 704 def prewhere_sql(self, expression: exp.PreWhere) -> str: 705 this = self.indent(self.sql(expression, "this")) 706 return f"{self.seg('PREWHERE')}{self.sep()}{this}" 707 708 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 709 this = self.sql(expression, "this") 710 this = f" {this}" if this else "" 711 expr = self.sql(expression, "expression") 712 expr = f" {expr}" if expr else "" 713 index_type = self.sql(expression, "index_type") 714 index_type = f" TYPE {index_type}" if index_type else "" 715 granularity = self.sql(expression, "granularity") 716 granularity = f" GRANULARITY {granularity}" if granularity else "" 717 718 return f"INDEX{this}{expr}{index_type}{granularity}" 719 720 def partition_sql(self, expression: exp.Partition) -> str: 721 return f"PARTITION {self.expressions(expression, flat=True)}" 722 723 def partitionid_sql(self, expression: exp.PartitionId) -> str: 724 return f"ID {self.sql(expression.this)}" 725 726 def replacepartition_sql(self, expression: exp.ReplacePartition) -> str: 727 return f"REPLACE {self.sql(expression.expression)} FROM {self.sql(expression, 'source')}" 728 729 def projectiondef_sql(self, expression: exp.ProjectionDef) -> str: 730 return f"PROJECTION {self.sql(expression.this)} {self.wrap(expression.expression)}" 731 732 def nestedjsonselect_sql(self, expression: exp.NestedJSONSelect) -> str: 733 return f"{self.sql(expression, 'this')}.^{self.sql(expression, 'expression')}" 734 735 def is_sql(self, expression: exp.Is) -> str: 736 is_sql = super().is_sql(expression) 737 738 if isinstance(expression.parent, exp.Not): 739 # value IS NOT NULL -> NOT (value IS NULL) 740 is_sql = self.wrap(is_sql) 741 742 return is_sql 743 744 def in_sql(self, expression: exp.In) -> str: 745 in_sql = super().in_sql(expression) 746 747 if isinstance(expression.parent, exp.Not) and expression.args.get("is_global"): 748 in_sql = in_sql.replace("GLOBAL IN", "GLOBAL NOT IN", 1) 749 750 return in_sql 751 752 def not_sql(self, expression: exp.Not) -> str: 753 if isinstance(expression.this, exp.In): 754 if expression.this.args.get("is_global"): 755 # let `GLOBAL IN` child interpose `NOT` 756 return self.sql(expression, "this") 757 758 expression.set("this", exp.paren(expression.this, copy=False)) 759 760 return super().not_sql(expression) 761 762 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 763 # If the VALUES clause contains tuples of expressions, we need to treat it 764 # as a table since Clickhouse will automatically alias it as such. 765 alias = expression.args.get("alias") 766 767 if alias and alias.args.get("columns") and expression.expressions: 768 values = expression.expressions[0].expressions 769 values_as_table = any(isinstance(value, exp.Tuple) for value in values) 770 else: 771 values_as_table = True 772 773 return super().values_sql(expression, values_as_table=values_as_table) 774 775 def timestamptrunc_sql(self, expression: exp.DateTrunc | exp.TimestampTrunc) -> str: 776 unit = weekstart_unit_to_str(self, expression) 777 # https://clickhouse.com/docs/whats-new/changelog/2023#improvement 778 if self.dialect.version < (23, 12) and unit and unit.is_string: 779 unit = exp.Literal.string(unit.name.lower()) 780 return self.func("dateTrunc", unit, expression.this, expression.args.get("zone")) 781 782 def datetrunc_sql(self, expression: exp.DateTrunc) -> str: 783 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.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.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.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.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.ArrayRemove'>: <function remove_from_array_using_filter>, <class 'sqlglot.expressions.array.ArrayReverse'>: <function rename_func.<locals>.<lambda>>, <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.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 rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.SHA1Digest'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.SHA2'>: <function sha256_sql>, <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.Variance'>: <function rename_func.<locals>.<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.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.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DistStyleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <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.IncludeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <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.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.POST_SCHEMA: 'POST_SCHEMA'>, <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.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 =
{'INDEX', 'SCHEMA', 'FUNCTION', 'DICTIONARY', 'DATABASE', 'VIEW', 'TABLE', 'NAMED COLLECTION'}
NON_NULLABLE_TYPES: ClassVar =
{<DType.RING: 'RING'>, <DType.LINESTRING: 'LINESTRING'>, <DType.ARRAY: 'ARRAY'>, <DType.MAP: 'MAP'>, <DType.MULTIPOLYGON: 'MULTIPOLYGON'>, <DType.POINT: 'POINT'>, <DType.POLYGON: 'POLYGON'>, <DType.STRUCT: 'STRUCT'>, <DType.MULTILINESTRING: 'MULTILINESTRING'>}
@unsupported_args('json_scope')
def
contains_sql(self, expression: sqlglot.expressions.string.Contains) -> str:
435 @unsupported_args("json_scope") 436 def contains_sql(self, expression: exp.Contains) -> str: 437 # ClickHouse has no CONTAINS; the comparison needs parentheses inside another operator 438 result = exp.StrPosition(this=expression.this, substr=expression.expression) > 0 439 if isinstance(expression.parent, exp.Binary) and not isinstance( 440 expression.parent, exp.Connector 441 ): 442 return self.sql(exp.paren(result, copy=False)) 443 return self.sql(result)
445 def groupconcat_sql(self, expression: exp.GroupConcat) -> str: 446 this = expression.this 447 separator = expression.args.get("separator") 448 449 if isinstance(this, exp.Limit) and this.this: 450 limit = this 451 this = limit.this.pop() 452 return self.sql( 453 exp.ParameterizedAgg( 454 this="groupConcat", 455 params=[this], 456 expressions=[separator, limit.expression], 457 ) 458 ) 459 460 if separator: 461 return self.sql( 462 exp.ParameterizedAgg( 463 this="groupConcat", 464 params=[this], 465 expressions=[separator], 466 ) 467 ) 468 469 return self.func("groupConcat", this)
471 def select_sql(self, expression: exp.Select) -> str: 472 limit = expression.args.get("limit") 473 if isinstance(limit, exp.Fetch) and not expression.args.get("order"): 474 count = limit.args.get("count") 475 expression.set( 476 "limit", exp.Limit(expression=count if count is not None else exp.Literal.number(1)) 477 ) 478 return super().select_sql(expression)
480 def offset_sql(self, expression: exp.Offset) -> str: 481 offset = super().offset_sql(expression) 482 483 # OFFSET ... FETCH syntax requires a "ROW" or "ROWS" keyword 484 # https://clickhouse.com/docs/sql-reference/statements/select/offset 485 parent = expression.parent 486 if isinstance(parent, exp.Select) and isinstance(parent.args.get("limit"), exp.Fetch): 487 offset = f"{offset} ROWS" 488 489 return offset
491 def strtodate_sql(self, expression: exp.StrToDate) -> str: 492 strtodate_sql = self.function_fallback_sql(expression) 493 494 if not isinstance(expression.parent, exp.Cast): 495 # StrToDate returns DATEs in other dialects (eg. postgres), so 496 # this branch aims to improve the transpilation to clickhouse 497 return self.cast_sql(exp.cast(expression, "DATE")) 498 499 return strtodate_sql
def
cast_sql( self, expression: sqlglot.expressions.functions.Cast, safe_prefix: str | None = None) -> str:
501 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 502 this = expression.this 503 504 if isinstance(this, exp.StrToDate) and expression.to == exp.DType.DATETIME.into_expr(): 505 return self.sql(this) 506 507 this = this.unnest() 508 if ( 509 isinstance(this, exp.JSONExtract) 510 and this.args.get("requires_json") 511 and expression.to.is_type(*exp.DataType.TEXT_TYPES) 512 ): 513 return self.func("JSONExtract", this, exp.Literal.string("Nullable(String)")) 514 515 return super().cast_sql(expression, safe_prefix=safe_prefix)
517 def trycast_sql(self, expression: exp.TryCast) -> str: 518 dtype = expression.to 519 if not dtype.is_type(*self.NON_NULLABLE_TYPES, check_nullable=True): 520 # Casting x into Nullable(T) appears to behave similarly to TRY_CAST(x AS T) 521 dtype.set("nullable", True) 522 523 return super().cast_sql(expression)
555 def regexpcount_sql(self, expression: exp.RegexpCount) -> str: 556 this = expression.this 557 pattern = expression.expression 558 position = expression.args.get("position") 559 parameters = expression.args.get("parameters") 560 561 if position: 562 # SUBSTRING counts bytes in ClickHouse, the position counts characters 563 this = self.func("substringUTF8", this, position) 564 565 if parameters: 566 flags = parameters.name if parameters.is_string else "" 567 if not parameters.is_string or set(flags) - set("cims"): 568 self.unsupported("Only literal 'c', 'i', 'm' and 's' regexp flags are supported") 569 # "c" (case-sensitive) is the default, and the last of "c" and "i" wins 570 if flags.rfind("c") > flags.rfind("i"): 571 flags = flags.replace("i", "") 572 flags = "".join(f for f in flags if f in "ims") 573 if flags: 574 # countMatches has no flags argument, so they are embedded in the pattern 575 pattern = self.func("CONCAT", exp.Literal.string(f"(?{flags})"), pattern) 576 577 return self.func("countMatches", this, pattern)
584 def datatype_sql(self, expression: exp.DataType) -> str: 585 # String is the standard ClickHouse type, every other variant is just an alias. 586 # Additionally, any supplied length parameter will be ignored. 587 # 588 # https://clickhouse.com/docs/en/sql-reference/data-types/string 589 if expression.this in self.STRING_TYPE_MAPPING: 590 dtype = "String" 591 else: 592 dtype = super().datatype_sql(expression) 593 594 # This section changes the type to `Nullable(...)` if the following conditions hold: 595 # - It's marked as nullable - this ensures we won't wrap ClickHouse types with `Nullable` 596 # and change their semantics 597 # - It's not the key type of a `Map`. This is because ClickHouse enforces the following 598 # constraint: "Type of Map key must be a type, that can be represented by integer or 599 # String or FixedString (possibly LowCardinality) or UUID or IPv6" 600 # - It's not a composite type, e.g. `Nullable(Array(...))` is not a valid type 601 parent = expression.parent 602 nullable = expression.args.get("nullable") 603 if nullable is True or ( 604 nullable is None 605 and not ( 606 isinstance(parent, exp.DataType) 607 and parent.is_type(exp.DType.MAP, check_nullable=True) 608 and expression.index in (None, 0) 609 ) 610 and not expression.is_type(*self.NON_NULLABLE_TYPES, check_nullable=True) 611 ): 612 dtype = f"Nullable({dtype})" 613 614 return dtype
624 def after_limit_modifiers(self, expression: exp.Expr) -> list[str]: 625 return super().after_limit_modifiers(expression) + [ 626 ( 627 self.seg("SETTINGS ") + self.expressions(expression, key="settings", flat=True) 628 if expression.args.get("settings") 629 else "" 630 ), 631 ( 632 self.seg("FORMAT ") + self.sql(expression, "format") 633 if expression.args.get("format") 634 else "" 635 ), 636 ]
def
autorefreshproperty_sql( self, expression: sqlglot.expressions.properties.AutoRefreshProperty) -> str:
649 def autorefreshproperty_sql(self, expression: exp.AutoRefreshProperty) -> str: 650 cadence = self.sql(expression, "cadence") 651 interval = expression.this 652 schedule = ( 653 f" {cadence} {self._refresh_interval_sql(interval)}" if cadence and interval else "" 654 ) 655 offset = expression.args.get("offset") 656 offset = f" OFFSET {self._refresh_interval_sql(offset)}" if offset else "" 657 randomize = expression.args.get("randomize") 658 randomize = f" RANDOMIZE FOR {self._refresh_interval_sql(randomize)}" if randomize else "" 659 dependencies = self.expressions(expression, flat=True) 660 dependencies = f" DEPENDS ON {dependencies}" if dependencies else "" 661 settings = self.sql(expression, "settings") 662 settings = f" {settings}" if settings else "" 663 append = " APPEND" if expression.args.get("append") else "" 664 665 return f"REFRESH{schedule}{offset}{randomize}{dependencies}{settings}{append}"
def
createable_sql( self, expression: sqlglot.expressions.ddl.Create, locations: collections.defaultdict) -> str:
667 def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str: 668 if expression.kind in self.ON_CLUSTER_TARGETS and locations.get( 669 exp.Properties.Location.POST_NAME 670 ): 671 this_name = self.sql( 672 expression.this if isinstance(expression.this, exp.Schema) else expression, 673 "this", 674 ) 675 this_properties = " ".join( 676 [self.sql(prop) for prop in locations[exp.Properties.Location.POST_NAME]] 677 ) 678 this_schema = self.schema_columns_sql(expression.this) 679 this_schema = f"{self.sep()}{this_schema}" if this_schema else "" 680 681 return f"{this_name}{self.sep()}{this_properties}{this_schema}" 682 683 return super().createable_sql(expression, locations)
685 def create_sql(self, expression: exp.Create) -> str: 686 # The comment property comes last in CTAS statements, i.e. after the query 687 query = expression.expression 688 if isinstance(query, exp.Query): 689 comment_prop = expression.find(exp.SchemaCommentProperty) 690 if comment_prop: 691 comment_prop.pop() 692 if not isinstance(query, exp.Subquery): 693 query.replace(exp.paren(query)) 694 else: 695 comment_prop = None 696 697 create_sql = super().create_sql(expression) 698 699 comment_sql = self.sql(comment_prop) 700 comment_sql = f" {comment_sql}" if comment_sql else "" 701 702 return f"{create_sql}{comment_sql}"
def
indexcolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.IndexColumnConstraint) -> str:
708 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 709 this = self.sql(expression, "this") 710 this = f" {this}" if this else "" 711 expr = self.sql(expression, "expression") 712 expr = f" {expr}" if expr else "" 713 index_type = self.sql(expression, "index_type") 714 index_type = f" TYPE {index_type}" if index_type else "" 715 granularity = self.sql(expression, "granularity") 716 granularity = f" GRANULARITY {granularity}" if granularity else "" 717 718 return f"INDEX{this}{expr}{index_type}{granularity}"
752 def not_sql(self, expression: exp.Not) -> str: 753 if isinstance(expression.this, exp.In): 754 if expression.this.args.get("is_global"): 755 # let `GLOBAL IN` child interpose `NOT` 756 return self.sql(expression, "this") 757 758 expression.set("this", exp.paren(expression.this, copy=False)) 759 760 return super().not_sql(expression)
def
values_sql( self, expression: sqlglot.expressions.query.Values, values_as_table: bool = True) -> str:
762 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 763 # If the VALUES clause contains tuples of expressions, we need to treat it 764 # as a table since Clickhouse will automatically alias it as such. 765 alias = expression.args.get("alias") 766 767 if alias and alias.args.get("columns") and expression.expressions: 768 values = expression.expressions[0].expressions 769 values_as_table = any(isinstance(value, exp.Tuple) for value in values) 770 else: 771 values_as_table = True 772 773 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:
775 def timestamptrunc_sql(self, expression: exp.DateTrunc | exp.TimestampTrunc) -> str: 776 unit = weekstart_unit_to_str(self, expression) 777 # https://clickhouse.com/docs/whats-new/changelog/2023#improvement 778 if self.dialect.version < (23, 12) and unit and unit.is_string: 779 unit = exp.Literal.string(unit.name.lower()) 780 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
- 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
- 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
- QUERY_HINT_SEP
- IS_BOOL_ALLOWED
- CAST_TO_INT_ROUNDS
- SAFE_INT_DIVISION
- 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
- 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_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
- ARRAY_SIZE_DIM_REQUIRED
- 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
- 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
- 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
- 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
- connect_sql
- prior_sql
- join_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_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
- formatjson_sql
- formatphrase_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
- 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
- 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
- div_sql
- safedivide_sql
- overlaps_sql
- distance_sql
- distancend_sql
- dot_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
- arrayagg_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
- 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
- altermodifysqlsecurity_sql
- usingproperty_sql
- renameindex_sql