sqlglot.generators.singlestore
1from __future__ import annotations 2 3import re 4import typing as t 5 6from sqlglot import exp 7from sqlglot.dialects.dialect import ( 8 json_extract_segments, 9 json_path_key_only_name, 10 rename_func, 11 bool_xor_sql, 12 count_if_to_sum, 13 timestamptrunc_sql, 14 date_add_interval_sql, 15 timestampdiff_sql, 16 remove_ts_or_ds_to_date, 17) 18from sqlglot.expressions import DataType 19from sqlglot import generator 20from sqlglot.generator import unsupported_args 21from sqlglot.generators.mysql import MySQLGenerator, date_add_sql 22 23 24def _unicode_substitute(m: re.Match[str]) -> str: 25 return chr(int(m.group(1), 16)) 26 27 28class SingleStoreGenerator(MySQLGenerator): 29 SUPPORTS_UESCAPE = False 30 SUPPORTS_ALTER_COLUMN_NULLABILITY = False 31 NULL_ORDERING_SUPPORTED: bool | None = True 32 MATCH_AGAINST_TABLE_PREFIX: str | None = "TABLE " 33 STRUCT_DELIMITER = ("(", ")") 34 35 UNICODE_SUBSTITUTE: t.ClassVar[t.Any] = staticmethod(_unicode_substitute) 36 37 SUPPORTED_JSON_PATH_PARTS = { 38 exp.JSONPathKey, 39 exp.JSONPathRoot, 40 exp.JSONPathSubscript, 41 } 42 43 TRANSFORMS = { 44 **{ 45 k: v 46 for k, v in MySQLGenerator.TRANSFORMS.items() 47 if k not in (exp.JSONExtractScalar, exp.CurrentDate) 48 }, 49 exp.TsOrDsToDate: lambda self, e: ( 50 self.func("TO_DATE", e.this, self.format_time(e)) 51 if e.args.get("format") 52 else self.func("DATE", e.this) 53 ), 54 exp.StrToTime: lambda self, e: self.func("TO_TIMESTAMP", e.this, self.format_time(e)), 55 exp.ToChar: lambda self, e: self.func("TO_CHAR", e.this, self.format_time(e)), 56 exp.StrToDate: lambda self, e: self.func( 57 "STR_TO_DATE", 58 e.this, 59 self.format_time( 60 e, 61 inverse_time_mapping=self.dialect.MYSQL_INVERSE_TIME_MAPPING, 62 inverse_time_trie=self.dialect.MYSQL_INVERSE_TIME_TRIE, 63 ), 64 ), 65 exp.TimeToStr: lambda self, e: self.func( 66 "DATE_FORMAT", 67 e.this, 68 self.format_time( 69 e, 70 inverse_time_mapping=self.dialect.MYSQL_INVERSE_TIME_MAPPING, 71 inverse_time_trie=self.dialect.MYSQL_INVERSE_TIME_TRIE, 72 ), 73 ), 74 exp.Date: unsupported_args("zone", "expressions")(rename_func("DATE")), 75 exp.Cast: unsupported_args("format", "action", "default")( 76 lambda self, e: f"{self.sql(e, 'this')} :> {self.sql(e, 'to')}" 77 ), 78 exp.TryCast: unsupported_args("format", "action", "default")( 79 lambda self, e: f"{self.sql(e, 'this')} !:> {self.sql(e, 'to')}" 80 ), 81 exp.CastToStrType: lambda self, e: self.sql( 82 exp.cast(e.this, DataType.from_str(e.args["to"].name)) 83 ), 84 exp.StrToUnix: unsupported_args("format")(rename_func("UNIX_TIMESTAMP")), 85 exp.TimeToUnix: rename_func("UNIX_TIMESTAMP"), 86 exp.TimeStrToUnix: rename_func("UNIX_TIMESTAMP"), 87 exp.UnixSeconds: rename_func("UNIX_TIMESTAMP"), 88 exp.UnixToStr: lambda self, e: self.func( 89 "FROM_UNIXTIME", 90 e.this, 91 self.format_time( 92 e, 93 inverse_time_mapping=self.dialect.MYSQL_INVERSE_TIME_MAPPING, 94 inverse_time_trie=self.dialect.MYSQL_INVERSE_TIME_TRIE, 95 ), 96 ), 97 exp.UnixToTime: unsupported_args("scale", "zone", "hours", "minutes")( 98 lambda self, e: self.func( 99 "FROM_UNIXTIME", 100 e.this, 101 self.format_time( 102 e, 103 inverse_time_mapping=self.dialect.MYSQL_INVERSE_TIME_MAPPING, 104 inverse_time_trie=self.dialect.MYSQL_INVERSE_TIME_TRIE, 105 ), 106 ), 107 ), 108 exp.UnixToTimeStr: lambda self, e: f"FROM_UNIXTIME({self.sql(e, 'this')}) :> TEXT", 109 exp.DateBin: unsupported_args("unit", "zone")( 110 lambda self, e: self.func("TIME_BUCKET", e.this, e.expression, e.args.get("origin")) 111 ), 112 exp.TimeStrToDate: lambda self, e: self.sql(exp.cast(e.this, exp.DType.DATE)), 113 exp.FromTimeZone: lambda self, e: self.func( 114 "CONVERT_TZ", e.this, e.args.get("zone"), "'UTC'" 115 ), 116 exp.DiToDate: lambda self, e: ( 117 f"STR_TO_DATE({self.sql(e, 'this')}, {self.dialect.DATEINT_FORMAT})" 118 ), 119 exp.DateToDi: lambda self, e: ( 120 f"(DATE_FORMAT({self.sql(e, 'this')}, {self.dialect.DATEINT_FORMAT}) :> INT)" 121 ), 122 exp.TsOrDiToDi: lambda self, e: ( 123 f"(DATE_FORMAT({self.sql(e, 'this')}, {self.dialect.DATEINT_FORMAT}) :> INT)" 124 ), 125 exp.Time: unsupported_args("zone")(lambda self, e: f"{self.sql(e, 'this')} :> TIME"), 126 exp.DatetimeAdd: remove_ts_or_ds_to_date(date_add_sql("ADD")), 127 exp.DatetimeTrunc: unsupported_args("zone")(timestamptrunc_sql()), 128 exp.DatetimeSub: date_add_interval_sql("DATE", "SUB"), 129 exp.DatetimeDiff: timestampdiff_sql, 130 exp.DateTrunc: unsupported_args("zone")(timestamptrunc_sql()), 131 exp.DateDiff: unsupported_args("zone")( 132 lambda self, e: ( 133 timestampdiff_sql(self, e) 134 if e.unit is not None 135 else self.func("DATEDIFF", e.this, e.expression) 136 ) 137 ), 138 exp.TsOrDsDiff: lambda self, e: ( 139 timestampdiff_sql(self, e) 140 if e.unit is not None 141 else self.func("DATEDIFF", e.this, e.expression) 142 ), 143 exp.TimestampTrunc: unsupported_args("zone")(timestamptrunc_sql()), 144 exp.CurrentDatetime: lambda self, e: self.sql( 145 self.dialect.CAST_TO_TIME6( 146 exp.CurrentTimestamp(this=exp.Literal.number(6)), exp.DType.DATETIME 147 ) 148 ), 149 exp.JSONExtract: unsupported_args( 150 "only_json_types", 151 "expressions", 152 "variant_extract", 153 "json_query", 154 "option", 155 "quote", 156 "on_condition", 157 "requires_json", 158 )(json_extract_segments("JSON_EXTRACT_JSON")), 159 exp.JSONBExtract: json_extract_segments("BSON_EXTRACT_BSON"), 160 exp.JSONPathKey: json_path_key_only_name, 161 exp.JSONPathSubscript: lambda self, e: self.json_path_part(e.this), 162 exp.JSONPathRoot: lambda *_: "", 163 exp.JSONFormat: unsupported_args("options", "is_json")(rename_func("JSON_PRETTY")), 164 exp.JSONArrayAgg: unsupported_args("null_handling", "return_type", "strict")( 165 lambda self, e: self.func("JSON_AGG", e.this, suffix=f"{self.sql(e, 'order')})") 166 ), 167 exp.JSONArray: unsupported_args("null_handling", "return_type", "strict")( 168 rename_func("JSON_BUILD_ARRAY") 169 ), 170 exp.JSONBExists: lambda self, e: self.func( 171 "BSON_MATCH_ANY_EXISTS", e.this, e.args.get("path") 172 ), 173 exp.JSONExists: lambda self, e: ( 174 f"{self.sql(e.this)}::?{self.sql(e.args.get('path'))}" 175 if e.args.get("from_dcolonqmark") 176 else self.func("JSON_MATCH_ANY_EXISTS", e.this, e.args.get("path")) 177 ), 178 exp.JSONObject: unsupported_args("null_handling", "unique_keys", "return_type", "encoding")( 179 rename_func("JSON_BUILD_OBJECT") 180 ), 181 exp.DayOfWeekIso: lambda self, e: f"(({self.func('DAYOFWEEK', e.this)} % 7) + 1)", 182 exp.DayOfMonth: rename_func("DAY"), 183 exp.Hll: rename_func("APPROX_COUNT_DISTINCT"), 184 exp.ApproxDistinct: rename_func("APPROX_COUNT_DISTINCT"), 185 exp.CountIf: count_if_to_sum, 186 exp.LogicalOr: lambda self, e: f"MAX(ABS({self.sql(e, 'this')}))", 187 exp.LogicalAnd: lambda self, e: f"MIN(ABS({self.sql(e, 'this')}))", 188 exp.ApproxQuantile: unsupported_args("accuracy", "weight")( 189 lambda self, e: self.func( 190 "APPROX_PERCENTILE", 191 e.this, 192 e.args.get("quantile"), 193 e.args.get("error_tolerance"), 194 ) 195 ), 196 exp.Variance: rename_func("VAR_SAMP"), 197 exp.VariancePop: rename_func("VAR_POP"), 198 exp.Xor: bool_xor_sql, 199 exp.Cbrt: lambda self, e: self.sql( 200 exp.Pow(this=e.this, expression=exp.Literal.number(1) / exp.Literal.number(3)) 201 ), 202 exp.RegexpLike: lambda self, e: self.binary(e, "RLIKE"), 203 exp.Repeat: lambda self, e: self.func( 204 "LPAD", 205 exp.Literal.string(""), 206 exp.Mul(this=self.func("LENGTH", e.this), expression=e.args.get("times")), 207 e.this, 208 ), 209 exp.IsAscii: lambda self, e: f"({self.sql(e, 'this')} RLIKE '^[\x00-\x7f]*$')", 210 exp.MD5Digest: lambda self, e: self.func("UNHEX", self.func("MD5", e.this)), 211 exp.Contains: rename_func("INSTR"), 212 exp.RegexpExtractAll: unsupported_args("position", "occurrence", "group")( 213 lambda self, e: self.func( 214 "REGEXP_MATCH", 215 e.this, 216 e.expression, 217 e.args.get("parameters"), 218 ) 219 ), 220 exp.RegexpExtract: unsupported_args("group")( 221 lambda self, e: self.func( 222 "REGEXP_SUBSTR", 223 e.this, 224 e.expression, 225 e.args.get("position"), 226 e.args.get("occurrence"), 227 e.args.get("parameters"), 228 ) 229 ), 230 exp.StartsWith: lambda self, e: self.func( 231 "REGEXP_INSTR", e.this, self.func("CONCAT", exp.Literal.string("^"), e.expression) 232 ), 233 exp.FromBase: lambda self, e: self.func( 234 "CONV", e.this, e.expression, exp.Literal.number(10) 235 ), 236 exp.RegexpILike: lambda self, e: self.binary( 237 exp.RegexpLike( 238 this=exp.Lower(this=e.this), 239 expression=exp.Lower(this=e.expression), 240 ), 241 "RLIKE", 242 ), 243 exp.Stuff: lambda self, e: self.func( 244 "CONCAT", 245 self.func("SUBSTRING", e.this, exp.Literal.number(1), e.args.get("start") - 1), 246 e.expression, 247 self.func("SUBSTRING", e.this, e.args.get("start") + e.args.get("length")), 248 ), 249 exp.National: lambda self, e: self.national_sql(e, prefix=""), 250 exp.Reduce: unsupported_args("finish")( 251 lambda self, e: self.func("REDUCE", e.args.get("initial"), e.this, e.args.get("merge")) 252 ), 253 exp.MatchAgainst: unsupported_args("modifier")( 254 lambda self, e: generator.Generator.matchagainst_sql(self, e) 255 ), 256 exp.Show: unsupported_args( 257 "history", 258 "terse", 259 "offset", 260 "starts_with", 261 "limit", 262 "from_", 263 "scope", 264 "scope_kind", 265 "mutex", 266 "query", 267 "channel", 268 "log", 269 "types", 270 "privileges", 271 )(lambda self, e: MySQLGenerator.show_sql(self, e)), 272 exp.Describe: unsupported_args( 273 "style", 274 "kind", 275 "expressions", 276 "partition", 277 "format", 278 )(lambda self, e: generator.Generator.describe_sql(self, e)), 279 } 280 281 UNSUPPORTED_TYPES = { 282 exp.DType.ARRAY, 283 exp.DType.AGGREGATEFUNCTION, 284 exp.DType.SIMPLEAGGREGATEFUNCTION, 285 exp.DType.BIGSERIAL, 286 exp.DType.BPCHAR, 287 exp.DType.DATEMULTIRANGE, 288 exp.DType.DATERANGE, 289 exp.DType.DYNAMIC, 290 exp.DType.HLLSKETCH, 291 exp.DType.HSTORE, 292 exp.DType.IMAGE, 293 exp.DType.INET, 294 exp.DType.INT128, 295 exp.DType.INT256, 296 exp.DType.INT4MULTIRANGE, 297 exp.DType.INT4RANGE, 298 exp.DType.INT8MULTIRANGE, 299 exp.DType.INT8RANGE, 300 exp.DType.INTERVAL, 301 exp.DType.IPADDRESS, 302 exp.DType.IPPREFIX, 303 exp.DType.IPV4, 304 exp.DType.IPV6, 305 exp.DType.LIST, 306 exp.DType.MAP, 307 exp.DType.LOWCARDINALITY, 308 exp.DType.MONEY, 309 exp.DType.MULTILINESTRING, 310 exp.DType.NAME, 311 exp.DType.NESTED, 312 exp.DType.NOTHING, 313 exp.DType.NULL, 314 exp.DType.NUMMULTIRANGE, 315 exp.DType.NUMRANGE, 316 exp.DType.OBJECT, 317 exp.DType.RANGE, 318 exp.DType.ROWVERSION, 319 exp.DType.SERIAL, 320 exp.DType.SMALLSERIAL, 321 exp.DType.SMALLMONEY, 322 exp.DType.SUPER, 323 exp.DType.TIMETZ, 324 exp.DType.TIMESTAMPNTZ, 325 exp.DType.TIMESTAMPLTZ, 326 exp.DType.TIMESTAMPTZ, 327 exp.DType.TIMESTAMP_NS, 328 exp.DType.TSMULTIRANGE, 329 exp.DType.TSRANGE, 330 exp.DType.TSTZMULTIRANGE, 331 exp.DType.TSTZRANGE, 332 exp.DType.UINT128, 333 exp.DType.UINT256, 334 exp.DType.UNION, 335 exp.DType.UNKNOWN, 336 exp.DType.USERDEFINED, 337 exp.DType.UUID, 338 exp.DType.VARIANT, 339 exp.DType.XML, 340 exp.DType.TDIGEST, 341 } 342 343 TYPE_MAPPING = { 344 **MySQLGenerator.TYPE_MAPPING, 345 exp.DType.BIGDECIMAL: "DECIMAL", 346 exp.DType.BIT: "BOOLEAN", 347 exp.DType.DATE32: "DATE", 348 exp.DType.DATETIME64: "DATETIME", 349 exp.DType.DECIMAL32: "DECIMAL", 350 exp.DType.DECIMAL64: "DECIMAL", 351 exp.DType.DECIMAL128: "DECIMAL", 352 exp.DType.DECIMAL256: "DECIMAL", 353 exp.DType.ENUM8: "ENUM", 354 exp.DType.ENUM16: "ENUM", 355 exp.DType.FIXEDSTRING: "TEXT", 356 exp.DType.GEOMETRY: "GEOGRAPHY", 357 exp.DType.POINT: "GEOGRAPHYPOINT", 358 exp.DType.RING: "GEOGRAPHY", 359 exp.DType.LINESTRING: "GEOGRAPHY", 360 exp.DType.POLYGON: "GEOGRAPHY", 361 exp.DType.MULTIPOLYGON: "GEOGRAPHY", 362 exp.DType.STRUCT: "RECORD", 363 exp.DType.JSONB: "BSON", 364 exp.DType.TIMESTAMP: "TIMESTAMP", 365 exp.DType.TIMESTAMP_S: "TIMESTAMP", 366 exp.DType.TIMESTAMP_MS: "TIMESTAMP", 367 } 368 369 TYPE_PARAM_SETTINGS = { 370 **MySQLGenerator.TYPE_PARAM_SETTINGS, 371 exp.DType.TIMESTAMP_MS: ((6,), ()), 372 } 373 374 # https://docs.singlestore.com/cloud/reference/sql-reference/restricted-keywords/list-of-restricted-keywords/ 375 RESERVED_KEYWORDS = { 376 "abs", 377 "absolute", 378 "access", 379 "account", 380 "acos", 381 "action", 382 "add", 383 "adddate", 384 "addtime", 385 "admin", 386 "aes_decrypt", 387 "aes_encrypt", 388 "after", 389 "against", 390 "aggregate", 391 "aggregates", 392 "aggregator", 393 "aggregator_id", 394 "aggregator_plan_hash", 395 "aggregators", 396 "algorithm", 397 "all", 398 "also", 399 "alter", 400 "always", 401 "analyse", 402 "analyze", 403 "and", 404 "anti_join", 405 "any", 406 "any_value", 407 "approx_count_distinct", 408 "approx_count_distinct_accumulate", 409 "approx_count_distinct_combine", 410 "approx_count_distinct_estimate", 411 "approx_geography_intersects", 412 "approx_percentile", 413 "arghistory", 414 "arrange", 415 "arrangement", 416 "array", 417 "as", 418 "asc", 419 "ascii", 420 "asensitive", 421 "asin", 422 "asm", 423 "assertion", 424 "assignment", 425 "ast", 426 "asymmetric", 427 "async", 428 "at", 429 "atan", 430 "atan2", 431 "attach", 432 "attribute", 433 "authorization", 434 "auto", 435 "auto_increment", 436 "auto_reprovision", 437 "autostats", 438 "autostats_cardinality_mode", 439 "autostats_enabled", 440 "autostats_histogram_mode", 441 "autostats_sampling", 442 "availability", 443 "avg", 444 "avg_row_length", 445 "avro", 446 "azure", 447 "background", 448 "_background_threads_for_cleanup", 449 "backup", 450 "backup_history", 451 "backup_id", 452 "backward", 453 "batch", 454 "batches", 455 "batch_interval", 456 "_batch_size_limit", 457 "before", 458 "begin", 459 "between", 460 "bigint", 461 "bin", 462 "binary", 463 "_binary", 464 "bit", 465 "bit_and", 466 "bit_count", 467 "bit_or", 468 "bit_xor", 469 "blob", 470 "bool", 471 "boolean", 472 "bootstrap", 473 "both", 474 "_bt", 475 "btree", 476 "bucket_count", 477 "by", 478 "byte", 479 "byte_length", 480 "cache", 481 "call", 482 "call_for_pipeline", 483 "called", 484 "capture", 485 "cascade", 486 "cascaded", 487 "case", 488 "cast", 489 "catalog", 490 "ceil", 491 "ceiling", 492 "chain", 493 "change", 494 "char", 495 "character", 496 "characteristics", 497 "character_length", 498 "char_length", 499 "charset", 500 "check", 501 "checkpoint", 502 "_check_can_connect", 503 "_check_consistency", 504 "checksum", 505 "_checksum", 506 "class", 507 "clear", 508 "client", 509 "client_found_rows", 510 "close", 511 "cluster", 512 "clustered", 513 "cnf", 514 "coalesce", 515 "coercibility", 516 "collate", 517 "collation", 518 "collect", 519 "column", 520 "columnar", 521 "columns", 522 "columnstore", 523 "columnstore_segment_rows", 524 "comment", 525 "comments", 526 "commit", 527 "committed", 528 "_commit_log_tail", 529 "committed", 530 "compact", 531 "compile", 532 "compressed", 533 "compression", 534 "concat", 535 "concat_ws", 536 "concurrent", 537 "concurrently", 538 "condition", 539 "configuration", 540 "connection", 541 "connection_id", 542 "connections", 543 "config", 544 "constraint", 545 "constraints", 546 "content", 547 "continue", 548 "_continue_replay", 549 "conv", 550 "conversion", 551 "convert", 552 "convert_tz", 553 "copy", 554 "_core", 555 "cos", 556 "cost", 557 "cot", 558 "count", 559 "create", 560 "credentials", 561 "cross", 562 "cube", 563 "csv", 564 "cume_dist", 565 "curdate", 566 "current", 567 "current_catalog", 568 "current_date", 569 "current_role", 570 "current_schema", 571 "current_security_groups", 572 "current_security_roles", 573 "current_time", 574 "current_timestamp", 575 "current_user", 576 "cursor", 577 "curtime", 578 "cycle", 579 "data", 580 "database", 581 "databases", 582 "date", 583 "date_add", 584 "datediff", 585 "date_format", 586 "date_sub", 587 "date_trunc", 588 "datetime", 589 "day", 590 "day_hour", 591 "day_microsecond", 592 "day_minute", 593 "dayname", 594 "dayofmonth", 595 "dayofweek", 596 "dayofyear", 597 "day_second", 598 "deallocate", 599 "dec", 600 "decimal", 601 "declare", 602 "decode", 603 "default", 604 "defaults", 605 "deferrable", 606 "deferred", 607 "defined", 608 "definer", 609 "degrees", 610 "delayed", 611 "delay_key_write", 612 "delete", 613 "delimiter", 614 "delimiters", 615 "dense_rank", 616 "desc", 617 "describe", 618 "detach", 619 "deterministic", 620 "dictionary", 621 "differential", 622 "directory", 623 "disable", 624 "discard", 625 "_disconnect", 626 "disk", 627 "distinct", 628 "distinctrow", 629 "distributed_joins", 630 "div", 631 "do", 632 "document", 633 "domain", 634 "dot_product", 635 "double", 636 "drop", 637 "_drop_profile", 638 "dual", 639 "dump", 640 "duplicate", 641 "dynamic", 642 "earliest", 643 "each", 644 "echo", 645 "election", 646 "else", 647 "elseif", 648 "elt", 649 "enable", 650 "enclosed", 651 "encoding", 652 "encrypted", 653 "end", 654 "engine", 655 "engines", 656 "enum", 657 "errors", 658 "escape", 659 "escaped", 660 "estimate", 661 "euclidean_distance", 662 "event", 663 "events", 664 "except", 665 "exclude", 666 "excluding", 667 "exclusive", 668 "execute", 669 "exists", 670 "exit", 671 "exp", 672 "explain", 673 "extended", 674 "extension", 675 "external", 676 "external_host", 677 "external_port", 678 "extract", 679 "extractor", 680 "extractors", 681 "extra_join", 682 "_failover", 683 "failed_login_attempts", 684 "failure", 685 "false", 686 "family", 687 "fault", 688 "fetch", 689 "field", 690 "fields", 691 "file", 692 "files", 693 "fill", 694 "first", 695 "first_value", 696 "fix_alter", 697 "fixed", 698 "float", 699 "float4", 700 "float8", 701 "floor", 702 "flush", 703 "following", 704 "for", 705 "force", 706 "force_compiled_mode", 707 "force_interpreter_mode", 708 "foreground", 709 "foreign", 710 "format", 711 "forward", 712 "found_rows", 713 "freeze", 714 "from", 715 "from_base64", 716 "from_days", 717 "from_unixtime", 718 "fs", 719 "_fsync", 720 "full", 721 "fulltext", 722 "function", 723 "functions", 724 "gc", 725 "gcs", 726 "get_format", 727 "_gc", 728 "_gcx", 729 "generate", 730 "geography", 731 "geography_area", 732 "geography_contains", 733 "geography_distance", 734 "geography_intersects", 735 "geography_latitude", 736 "geography_length", 737 "geography_longitude", 738 "geographypoint", 739 "geography_point", 740 "geography_within_distance", 741 "geometry", 742 "geometry_area", 743 "geometry_contains", 744 "geometry_distance", 745 "geometry_filter", 746 "geometry_intersects", 747 "geometry_length", 748 "geometrypoint", 749 "geometry_point", 750 "geometry_within_distance", 751 "geometry_x", 752 "geometry_y", 753 "global", 754 "_global_version_timestamp", 755 "grant", 756 "granted", 757 "grants", 758 "greatest", 759 "group", 760 "grouping", 761 "groups", 762 "group_concat", 763 "gzip", 764 "handle", 765 "handler", 766 "hard_cpu_limit_percentage", 767 "hash", 768 "has_temp_tables", 769 "having", 770 "hdfs", 771 "header", 772 "heartbeat_no_logging", 773 "hex", 774 "highlight", 775 "high_priority", 776 "hold", 777 "holding", 778 "host", 779 "hosts", 780 "hour", 781 "hour_microsecond", 782 "hour_minute", 783 "hour_second", 784 "identified", 785 "identity", 786 "if", 787 "ifnull", 788 "ignore", 789 "ilike", 790 "immediate", 791 "immutable", 792 "implicit", 793 "import", 794 "in", 795 "including", 796 "increment", 797 "incremental", 798 "index", 799 "indexes", 800 "inet_aton", 801 "inet_ntoa", 802 "inet6_aton", 803 "inet6_ntoa", 804 "infile", 805 "inherit", 806 "inherits", 807 "_init_profile", 808 "init", 809 "initcap", 810 "initialize", 811 "initially", 812 "inject", 813 "inline", 814 "inner", 815 "inout", 816 "input", 817 "insensitive", 818 "insert", 819 "insert_method", 820 "instance", 821 "instead", 822 "instr", 823 "int", 824 "int1", 825 "int2", 826 "int3", 827 "int4", 828 "int8", 829 "integer", 830 "_internal_dynamic_typecast", 831 "interpreter_mode", 832 "intersect", 833 "interval", 834 "into", 835 "invoker", 836 "is", 837 "isnull", 838 "isolation", 839 "iterate", 840 "join", 841 "json", 842 "json_agg", 843 "json_array_contains_double", 844 "json_array_contains_json", 845 "json_array_contains_string", 846 "json_array_push_double", 847 "json_array_push_json", 848 "json_array_push_string", 849 "json_delete_key", 850 "json_extract_double", 851 "json_extract_json", 852 "json_extract_string", 853 "json_extract_bigint", 854 "json_get_type", 855 "json_length", 856 "json_set_double", 857 "json_set_json", 858 "json_set_string", 859 "json_splice_double", 860 "json_splice_json", 861 "json_splice_string", 862 "kafka", 863 "key", 864 "key_block_size", 865 "keys", 866 "kill", 867 "killall", 868 "label", 869 "lag", 870 "language", 871 "large", 872 "last", 873 "last_day", 874 "last_insert_id", 875 "last_value", 876 "lateral", 877 "latest", 878 "lc_collate", 879 "lc_ctype", 880 "lcase", 881 "lead", 882 "leading", 883 "leaf", 884 "leakproof", 885 "least", 886 "leave", 887 "leaves", 888 "left", 889 "length", 890 "level", 891 "license", 892 "like", 893 "limit", 894 "lines", 895 "listen", 896 "llvm", 897 "ln", 898 "load", 899 "loaddata_where", 900 "_load", 901 "local", 902 "localtime", 903 "localtimestamp", 904 "locate", 905 "location", 906 "lock", 907 "log", 908 "log10", 909 "log2", 910 "long", 911 "longblob", 912 "longtext", 913 "loop", 914 "lower", 915 "low_priority", 916 "lpad", 917 "_ls", 918 "ltrim", 919 "lz4", 920 "management", 921 "_management_thread", 922 "mapping", 923 "master", 924 "match", 925 "materialized", 926 "max", 927 "maxvalue", 928 "max_concurrency", 929 "max_errors", 930 "max_partitions_per_batch", 931 "max_queue_depth", 932 "max_retries_per_batch_partition", 933 "max_rows", 934 "mbc", 935 "md5", 936 "mpl", 937 "median", 938 "mediumblob", 939 "mediumint", 940 "mediumtext", 941 "member", 942 "memory", 943 "memory_percentage", 944 "_memsql_table_id_lookup", 945 "memsql", 946 "memsql_deserialize", 947 "memsql_imitating_kafka", 948 "memsql_serialize", 949 "merge", 950 "metadata", 951 "microsecond", 952 "middleint", 953 "min", 954 "min_rows", 955 "minus", 956 "minute", 957 "minute_microsecond", 958 "minute_second", 959 "minvalue", 960 "mod", 961 "mode", 962 "model", 963 "modifies", 964 "modify", 965 "month", 966 "monthname", 967 "months_between", 968 "move", 969 "mpl", 970 "names", 971 "named", 972 "namespace", 973 "national", 974 "natural", 975 "nchar", 976 "next", 977 "no", 978 "node", 979 "none", 980 "no_query_rewrite", 981 "noparam", 982 "not", 983 "nothing", 984 "notify", 985 "now", 986 "nowait", 987 "no_write_to_binlog", 988 "no_query_rewrite", 989 "norely", 990 "nth_value", 991 "ntile", 992 "null", 993 "nullcols", 994 "nullif", 995 "nulls", 996 "numeric", 997 "nvarchar", 998 "object", 999 "octet_length", 1000 "of", 1001 "off", 1002 "offline", 1003 "offset", 1004 "offsets", 1005 "oids", 1006 "on", 1007 "online", 1008 "only", 1009 "open", 1010 "operator", 1011 "optimization", 1012 "optimize", 1013 "optimizer", 1014 "optimizer_state", 1015 "option", 1016 "options", 1017 "optionally", 1018 "or", 1019 "order", 1020 "ordered_serialize", 1021 "orphan", 1022 "out", 1023 "out_of_order", 1024 "outer", 1025 "outfile", 1026 "over", 1027 "overlaps", 1028 "overlay", 1029 "owned", 1030 "owner", 1031 "pack_keys", 1032 "paired", 1033 "parser", 1034 "parquet", 1035 "partial", 1036 "partition", 1037 "partition_id", 1038 "partitioning", 1039 "partitions", 1040 "passing", 1041 "password", 1042 "password_lock_time", 1043 "parser", 1044 "pause", 1045 "_pause_replay", 1046 "percent_rank", 1047 "percentile_cont", 1048 "percentile_disc", 1049 "periodic", 1050 "persisted", 1051 "pi", 1052 "pipeline", 1053 "pipelines", 1054 "pivot", 1055 "placing", 1056 "plan", 1057 "plans", 1058 "plancache", 1059 "plugins", 1060 "pool", 1061 "pools", 1062 "port", 1063 "position", 1064 "pow", 1065 "power", 1066 "preceding", 1067 "precision", 1068 "prepare", 1069 "prepared", 1070 "preserve", 1071 "primary", 1072 "prior", 1073 "privileges", 1074 "procedural", 1075 "procedure", 1076 "procedures", 1077 "process", 1078 "processlist", 1079 "profile", 1080 "profiles", 1081 "program", 1082 "promote", 1083 "proxy", 1084 "purge", 1085 "quarter", 1086 "queries", 1087 "query", 1088 "query_timeout", 1089 "queue", 1090 "quote", 1091 "radians", 1092 "rand", 1093 "range", 1094 "rank", 1095 "read", 1096 "_read", 1097 "reads", 1098 "real", 1099 "reassign", 1100 "rebalance", 1101 "recheck", 1102 "record", 1103 "recursive", 1104 "redundancy", 1105 "redundant", 1106 "ref", 1107 "reference", 1108 "references", 1109 "refresh", 1110 "regexp", 1111 "reindex", 1112 "relative", 1113 "release", 1114 "reload", 1115 "rely", 1116 "remote", 1117 "remove", 1118 "rename", 1119 "repair", 1120 "_repair_table", 1121 "repeat", 1122 "repeatable", 1123 "_repl", 1124 "_reprovisioning", 1125 "replace", 1126 "replica", 1127 "replicate", 1128 "replicating", 1129 "replication", 1130 "durability", 1131 "require", 1132 "resource", 1133 "resource_pool", 1134 "reset", 1135 "restart", 1136 "restore", 1137 "restrict", 1138 "result", 1139 "_resurrect", 1140 "retry", 1141 "return", 1142 "returning", 1143 "returns", 1144 "reverse", 1145 "revoke", 1146 "rg_pool", 1147 "right", 1148 "right_anti_join", 1149 "right_semi_join", 1150 "right_straight_join", 1151 "rlike", 1152 "role", 1153 "roles", 1154 "rollback", 1155 "rollup", 1156 "round", 1157 "routine", 1158 "row", 1159 "row_count", 1160 "row_format", 1161 "row_number", 1162 "rows", 1163 "rowstore", 1164 "rule", 1165 "rpad", 1166 "_rpc", 1167 "rtrim", 1168 "running", 1169 "s3", 1170 "safe", 1171 "save", 1172 "savepoint", 1173 "scalar", 1174 "schema", 1175 "schemas", 1176 "schema_binding", 1177 "scroll", 1178 "search", 1179 "second", 1180 "second_microsecond", 1181 "sec_to_time", 1182 "security", 1183 "select", 1184 "semi_join", 1185 "_send_threads", 1186 "sensitive", 1187 "separator", 1188 "sequence", 1189 "sequences", 1190 "serial", 1191 "serializable", 1192 "series", 1193 "service_user", 1194 "server", 1195 "session", 1196 "session_user", 1197 "set", 1198 "setof", 1199 "security_lists_intersect", 1200 "sha", 1201 "sha1", 1202 "sha2", 1203 "shard", 1204 "sharded", 1205 "sharded_id", 1206 "share", 1207 "show", 1208 "shutdown", 1209 "sigmoid", 1210 "sign", 1211 "signal", 1212 "similar", 1213 "simple", 1214 "site", 1215 "signed", 1216 "sin", 1217 "skip", 1218 "skipped_batches", 1219 "sleep", 1220 "_sleep", 1221 "smallint", 1222 "snapshot", 1223 "_snapshot", 1224 "_snapshots", 1225 "soft_cpu_limit_percentage", 1226 "some", 1227 "soname", 1228 "sparse", 1229 "spatial", 1230 "spatial_check_index", 1231 "specific", 1232 "split", 1233 "sql", 1234 "sql_big_result", 1235 "sql_buffer_result", 1236 "sql_cache", 1237 "sql_calc_found_rows", 1238 "sqlexception", 1239 "sql_mode", 1240 "sql_no_cache", 1241 "sql_no_logging", 1242 "sql_small_result", 1243 "sqlstate", 1244 "sqlwarning", 1245 "sqrt", 1246 "ssl", 1247 "stable", 1248 "standalone", 1249 "start", 1250 "starting", 1251 "state", 1252 "statement", 1253 "statistics", 1254 "stats", 1255 "status", 1256 "std", 1257 "stddev", 1258 "stddev_pop", 1259 "stddev_samp", 1260 "stdin", 1261 "stdout", 1262 "stop", 1263 "storage", 1264 "str_to_date", 1265 "straight_join", 1266 "strict", 1267 "string", 1268 "strip", 1269 "subdate", 1270 "substr", 1271 "substring", 1272 "substring_index", 1273 "success", 1274 "sum", 1275 "super", 1276 "symmetric", 1277 "sync_snapshot", 1278 "sync", 1279 "_sync", 1280 "_sync2", 1281 "_sync_partitions", 1282 "_sync_snapshot", 1283 "synchronize", 1284 "sysid", 1285 "system", 1286 "table", 1287 "table_checksum", 1288 "tables", 1289 "tablespace", 1290 "tags", 1291 "tan", 1292 "target_size", 1293 "task", 1294 "temp", 1295 "template", 1296 "temporary", 1297 "temptable", 1298 "_term_bump", 1299 "terminate", 1300 "terminated", 1301 "test", 1302 "text", 1303 "then", 1304 "time", 1305 "timediff", 1306 "time_bucket", 1307 "time_format", 1308 "timeout", 1309 "timestamp", 1310 "timestampadd", 1311 "timestampdiff", 1312 "timezone", 1313 "time_to_sec", 1314 "tinyblob", 1315 "tinyint", 1316 "tinytext", 1317 "to", 1318 "to_base64", 1319 "to_char", 1320 "to_date", 1321 "to_days", 1322 "to_json", 1323 "to_number", 1324 "to_seconds", 1325 "to_timestamp", 1326 "tracelogs", 1327 "traditional", 1328 "trailing", 1329 "transform", 1330 "transaction", 1331 "_transactions_experimental", 1332 "treat", 1333 "trigger", 1334 "triggers", 1335 "trim", 1336 "true", 1337 "trunc", 1338 "truncate", 1339 "trusted", 1340 "two_phase", 1341 "_twopcid", 1342 "type", 1343 "types", 1344 "ucase", 1345 "unbounded", 1346 "uncommitted", 1347 "undefined", 1348 "undo", 1349 "unencrypted", 1350 "unenforced", 1351 "unhex", 1352 "unhold", 1353 "unicode", 1354 "union", 1355 "unique", 1356 "_unittest", 1357 "unix_timestamp", 1358 "unknown", 1359 "unlisten", 1360 "_unload", 1361 "unlock", 1362 "unlogged", 1363 "unpivot", 1364 "unsigned", 1365 "until", 1366 "update", 1367 "upgrade", 1368 "upper", 1369 "usage", 1370 "use", 1371 "user", 1372 "users", 1373 "using", 1374 "utc_date", 1375 "utc_time", 1376 "utc_timestamp", 1377 "_utf8", 1378 "vacuum", 1379 "valid", 1380 "validate", 1381 "validator", 1382 "value", 1383 "values", 1384 "varbinary", 1385 "varchar", 1386 "varcharacter", 1387 "variables", 1388 "variadic", 1389 "variance", 1390 "var_pop", 1391 "var_samp", 1392 "varying", 1393 "vector_sub", 1394 "verbose", 1395 "version", 1396 "view", 1397 "void", 1398 "volatile", 1399 "voting", 1400 "wait", 1401 "_wake", 1402 "warnings", 1403 "week", 1404 "weekday", 1405 "weekofyear", 1406 "when", 1407 "where", 1408 "while", 1409 "whitespace", 1410 "window", 1411 "with", 1412 "without", 1413 "within", 1414 "_wm_heartbeat", 1415 "work", 1416 "workload", 1417 "wrapper", 1418 "write", 1419 "xact_id", 1420 "xor", 1421 "year", 1422 "year_month", 1423 "yes", 1424 "zerofill", 1425 "zone", 1426 } 1427 1428 def jsonextractscalar_sql(self, expression: exp.JSONExtractScalar) -> str: 1429 json_type = expression.args.get("json_type") 1430 func_name = "JSON_EXTRACT_JSON" if json_type is None else f"JSON_EXTRACT_{json_type}" 1431 return json_extract_segments(func_name)(self, expression) 1432 1433 def jsonbextractscalar_sql(self, expression: exp.JSONBExtractScalar) -> str: 1434 json_type = expression.args.get("json_type") 1435 func_name = "BSON_EXTRACT_BSON" if json_type is None else f"BSON_EXTRACT_{json_type}" 1436 return json_extract_segments(func_name)(self, expression) 1437 1438 def jsonextractarray_sql(self, expression: exp.JSONExtractArray) -> str: 1439 self.unsupported("Arrays are not supported in SingleStore") 1440 return self.function_fallback_sql(expression) 1441 1442 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 1443 if expression.args.get("on_condition"): 1444 self.unsupported("JSON_VALUE does not support on_condition") 1445 res: exp.Expr = exp.JSONExtractScalar( 1446 this=expression.this, 1447 expression=expression.args.get("path"), 1448 json_type="STRING", 1449 ) 1450 1451 returning = expression.args.get("returning") 1452 if returning is not None: 1453 res = exp.Cast(this=res, to=returning) 1454 1455 return self.sql(res) 1456 1457 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 1458 # SingleStore includes trailing NULLs in percentile calculations, so we sort them first 1459 if isinstance(expression.this, (exp.PercentileCont, exp.PercentileDisc)) and isinstance( 1460 expression.expression, exp.Order 1461 ): 1462 expression = expression.copy() 1463 for ordered in expression.expression.expressions: 1464 ordered.set("nulls_first", True) 1465 1466 return super().withingroup_sql(expression) 1467 1468 def all_sql(self, expression: exp.All) -> str: 1469 self.unsupported("ALL subquery predicate is not supported in SingleStore") 1470 return super().all_sql(expression) 1471 1472 def jsonarraycontains_sql(self, expression: exp.JSONArrayContains) -> str: 1473 json_type = expression.text("json_type").upper() 1474 1475 if json_type: 1476 return self.func( 1477 f"JSON_ARRAY_CONTAINS_{json_type}", expression.expression, expression.this 1478 ) 1479 1480 return self.func( 1481 "JSON_ARRAY_CONTAINS_JSON", 1482 expression.expression, 1483 self.func("TO_JSON", expression.this), 1484 ) 1485 1486 def datatype_sql(self, expression: exp.DataType) -> str: 1487 for arg_name in ("kind", "values"): 1488 if expression.args.get(arg_name): 1489 self.unsupported(f"DATATYPE does not support {arg_name}") 1490 if expression.args.get("nested") and not expression.is_type(exp.DType.STRUCT): 1491 self.unsupported( 1492 f"Argument 'nested' is not supported for representation of '{expression.this.value}' in SingleStore" 1493 ) 1494 1495 if expression.is_type(exp.DType.VARBINARY) and not expression.expressions: 1496 # `VARBINARY` must always have a size - if it doesn't, we always generate `BLOB` 1497 return "BLOB" 1498 if expression.is_type( 1499 exp.DType.DECIMAL32, 1500 exp.DType.DECIMAL64, 1501 exp.DType.DECIMAL128, 1502 exp.DType.DECIMAL256, 1503 ): 1504 scale = self.expressions(expression, flat=True) 1505 1506 if expression.is_type(exp.DType.DECIMAL32): 1507 precision = "9" 1508 elif expression.is_type(exp.DType.DECIMAL64): 1509 precision = "18" 1510 elif expression.is_type(exp.DType.DECIMAL128): 1511 precision = "38" 1512 else: 1513 # 65 is a maximum precision supported in SingleStore 1514 precision = "65" 1515 if scale is not None: 1516 return f"DECIMAL({precision}, {scale[0]})" 1517 else: 1518 return f"DECIMAL({precision})" 1519 if expression.is_type(exp.DType.VECTOR): 1520 expressions = expression.expressions 1521 if len(expressions) == 2: 1522 type_name = self.sql(expressions[0]) 1523 if type_name in self.dialect.INVERSE_VECTOR_TYPE_ALIASES: 1524 type_name = self.dialect.INVERSE_VECTOR_TYPE_ALIASES[type_name] 1525 1526 return f"VECTOR({self.sql(expressions[1])}, {type_name})" 1527 1528 return super().datatype_sql(expression) 1529 1530 def collate_sql(self, expression: exp.Collate) -> str: 1531 # SingleStore does not support setting a collation for column in the SELECT query, 1532 # so we cast column to a LONGTEXT type with specific collation. If the cast is 1533 # already there (e.g. when regenerating previously generated SQL), don't add 1534 # another one, so that generation stays idempotent. 1535 this = expression.this 1536 if isinstance(this, exp.Cast) and this.to.this == exp.DType.LONGTEXT: 1537 return self.binary(expression, "COLLATE") 1538 return self.binary(expression, ":> LONGTEXT COLLATE") 1539 1540 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 1541 timezone = expression.this 1542 if timezone: 1543 if isinstance(timezone, exp.Literal) and timezone.name.lower() == "utc": 1544 return self.func("UTC_DATE") 1545 self.unsupported("CurrentDate with timezone is not supported in SingleStore") 1546 1547 return self.func("CURRENT_DATE") 1548 1549 def currenttime_sql(self, expression: exp.CurrentTime) -> str: 1550 arg = expression.this 1551 if arg: 1552 if isinstance(arg, exp.Literal) and arg.name.lower() == "utc": 1553 return self.func("UTC_TIME") 1554 if isinstance(arg, exp.Literal) and arg.is_number: 1555 return self.func("CURRENT_TIME", arg) 1556 self.unsupported("CurrentTime with timezone is not supported in SingleStore") 1557 1558 return self.func("CURRENT_TIME") 1559 1560 def currenttimestamp_sql(self, expression: exp.CurrentTimestamp) -> str: 1561 arg = expression.this 1562 if arg: 1563 if isinstance(arg, exp.Literal) and arg.name.lower() == "utc": 1564 return self.func("UTC_TIMESTAMP") 1565 if isinstance(arg, exp.Literal) and arg.is_number: 1566 return self.func("CURRENT_TIMESTAMP", arg) 1567 self.unsupported("CurrentTimestamp with timezone is not supported in SingleStore") 1568 1569 return self.func("CURRENT_TIMESTAMP") 1570 1571 def standardhash_sql(self, expression: exp.StandardHash) -> str: 1572 hash_function = expression.expression 1573 if hash_function is None: 1574 return self.func("SHA", expression.this) 1575 if isinstance(hash_function, exp.Literal): 1576 if hash_function.name.lower() == "sha": 1577 return self.func("SHA", expression.this) 1578 if hash_function.name.lower() == "md5": 1579 return self.func("MD5", expression.this) 1580 1581 self.unsupported(f"{hash_function.this} hash method is not supported in SingleStore") 1582 return self.func("SHA", expression.this) 1583 1584 self.unsupported("STANDARD_HASH function is not supported in SingleStore") 1585 return self.func("SHA", expression.this) 1586 1587 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 1588 for arg_name in ("is_database", "exists", "cluster", "identity", "option", "partition"): 1589 if expression.args.get(arg_name): 1590 self.unsupported(f"TRUNCATE TABLE does not support {arg_name}") 1591 statements = [] 1592 for table in expression.expressions: 1593 statements.append(f"TRUNCATE {self.sql(table)}") 1594 1595 return "; ".join(statements) 1596 1597 def renamecolumn_sql(self, expression: exp.RenameColumn) -> str: 1598 if expression.args.get("exists"): 1599 self.unsupported("RENAME COLUMN does not support exists") 1600 old_column = self.sql(expression, "this") 1601 new_column = self.sql(expression, "to") 1602 return f"CHANGE {old_column} {new_column}" 1603 1604 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 1605 for arg_name in ("drop", "comment", "visible", "using"): 1606 if expression.args.get(arg_name): 1607 self.unsupported(f"ALTER COLUMN does not support {arg_name}") 1608 alter = super().altercolumn_sql(expression) 1609 1610 collate = self.sql(expression, "collate") 1611 collate = f" COLLATE {collate}" if collate else "" 1612 return f"{alter}{collate}" 1613 1614 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 1615 this = self.sql(expression, "this") 1616 not_null = " NOT NULL" if expression.args.get("not_null") else "" 1617 type = self.sql(expression, "data_type") or "AUTO" 1618 return f"AS {this} PERSISTED {type}{not_null}"
29class SingleStoreGenerator(MySQLGenerator): 30 SUPPORTS_UESCAPE = False 31 SUPPORTS_ALTER_COLUMN_NULLABILITY = False 32 NULL_ORDERING_SUPPORTED: bool | None = True 33 MATCH_AGAINST_TABLE_PREFIX: str | None = "TABLE " 34 STRUCT_DELIMITER = ("(", ")") 35 36 UNICODE_SUBSTITUTE: t.ClassVar[t.Any] = staticmethod(_unicode_substitute) 37 38 SUPPORTED_JSON_PATH_PARTS = { 39 exp.JSONPathKey, 40 exp.JSONPathRoot, 41 exp.JSONPathSubscript, 42 } 43 44 TRANSFORMS = { 45 **{ 46 k: v 47 for k, v in MySQLGenerator.TRANSFORMS.items() 48 if k not in (exp.JSONExtractScalar, exp.CurrentDate) 49 }, 50 exp.TsOrDsToDate: lambda self, e: ( 51 self.func("TO_DATE", e.this, self.format_time(e)) 52 if e.args.get("format") 53 else self.func("DATE", e.this) 54 ), 55 exp.StrToTime: lambda self, e: self.func("TO_TIMESTAMP", e.this, self.format_time(e)), 56 exp.ToChar: lambda self, e: self.func("TO_CHAR", e.this, self.format_time(e)), 57 exp.StrToDate: lambda self, e: self.func( 58 "STR_TO_DATE", 59 e.this, 60 self.format_time( 61 e, 62 inverse_time_mapping=self.dialect.MYSQL_INVERSE_TIME_MAPPING, 63 inverse_time_trie=self.dialect.MYSQL_INVERSE_TIME_TRIE, 64 ), 65 ), 66 exp.TimeToStr: lambda self, e: self.func( 67 "DATE_FORMAT", 68 e.this, 69 self.format_time( 70 e, 71 inverse_time_mapping=self.dialect.MYSQL_INVERSE_TIME_MAPPING, 72 inverse_time_trie=self.dialect.MYSQL_INVERSE_TIME_TRIE, 73 ), 74 ), 75 exp.Date: unsupported_args("zone", "expressions")(rename_func("DATE")), 76 exp.Cast: unsupported_args("format", "action", "default")( 77 lambda self, e: f"{self.sql(e, 'this')} :> {self.sql(e, 'to')}" 78 ), 79 exp.TryCast: unsupported_args("format", "action", "default")( 80 lambda self, e: f"{self.sql(e, 'this')} !:> {self.sql(e, 'to')}" 81 ), 82 exp.CastToStrType: lambda self, e: self.sql( 83 exp.cast(e.this, DataType.from_str(e.args["to"].name)) 84 ), 85 exp.StrToUnix: unsupported_args("format")(rename_func("UNIX_TIMESTAMP")), 86 exp.TimeToUnix: rename_func("UNIX_TIMESTAMP"), 87 exp.TimeStrToUnix: rename_func("UNIX_TIMESTAMP"), 88 exp.UnixSeconds: rename_func("UNIX_TIMESTAMP"), 89 exp.UnixToStr: lambda self, e: self.func( 90 "FROM_UNIXTIME", 91 e.this, 92 self.format_time( 93 e, 94 inverse_time_mapping=self.dialect.MYSQL_INVERSE_TIME_MAPPING, 95 inverse_time_trie=self.dialect.MYSQL_INVERSE_TIME_TRIE, 96 ), 97 ), 98 exp.UnixToTime: unsupported_args("scale", "zone", "hours", "minutes")( 99 lambda self, e: self.func( 100 "FROM_UNIXTIME", 101 e.this, 102 self.format_time( 103 e, 104 inverse_time_mapping=self.dialect.MYSQL_INVERSE_TIME_MAPPING, 105 inverse_time_trie=self.dialect.MYSQL_INVERSE_TIME_TRIE, 106 ), 107 ), 108 ), 109 exp.UnixToTimeStr: lambda self, e: f"FROM_UNIXTIME({self.sql(e, 'this')}) :> TEXT", 110 exp.DateBin: unsupported_args("unit", "zone")( 111 lambda self, e: self.func("TIME_BUCKET", e.this, e.expression, e.args.get("origin")) 112 ), 113 exp.TimeStrToDate: lambda self, e: self.sql(exp.cast(e.this, exp.DType.DATE)), 114 exp.FromTimeZone: lambda self, e: self.func( 115 "CONVERT_TZ", e.this, e.args.get("zone"), "'UTC'" 116 ), 117 exp.DiToDate: lambda self, e: ( 118 f"STR_TO_DATE({self.sql(e, 'this')}, {self.dialect.DATEINT_FORMAT})" 119 ), 120 exp.DateToDi: lambda self, e: ( 121 f"(DATE_FORMAT({self.sql(e, 'this')}, {self.dialect.DATEINT_FORMAT}) :> INT)" 122 ), 123 exp.TsOrDiToDi: lambda self, e: ( 124 f"(DATE_FORMAT({self.sql(e, 'this')}, {self.dialect.DATEINT_FORMAT}) :> INT)" 125 ), 126 exp.Time: unsupported_args("zone")(lambda self, e: f"{self.sql(e, 'this')} :> TIME"), 127 exp.DatetimeAdd: remove_ts_or_ds_to_date(date_add_sql("ADD")), 128 exp.DatetimeTrunc: unsupported_args("zone")(timestamptrunc_sql()), 129 exp.DatetimeSub: date_add_interval_sql("DATE", "SUB"), 130 exp.DatetimeDiff: timestampdiff_sql, 131 exp.DateTrunc: unsupported_args("zone")(timestamptrunc_sql()), 132 exp.DateDiff: unsupported_args("zone")( 133 lambda self, e: ( 134 timestampdiff_sql(self, e) 135 if e.unit is not None 136 else self.func("DATEDIFF", e.this, e.expression) 137 ) 138 ), 139 exp.TsOrDsDiff: lambda self, e: ( 140 timestampdiff_sql(self, e) 141 if e.unit is not None 142 else self.func("DATEDIFF", e.this, e.expression) 143 ), 144 exp.TimestampTrunc: unsupported_args("zone")(timestamptrunc_sql()), 145 exp.CurrentDatetime: lambda self, e: self.sql( 146 self.dialect.CAST_TO_TIME6( 147 exp.CurrentTimestamp(this=exp.Literal.number(6)), exp.DType.DATETIME 148 ) 149 ), 150 exp.JSONExtract: unsupported_args( 151 "only_json_types", 152 "expressions", 153 "variant_extract", 154 "json_query", 155 "option", 156 "quote", 157 "on_condition", 158 "requires_json", 159 )(json_extract_segments("JSON_EXTRACT_JSON")), 160 exp.JSONBExtract: json_extract_segments("BSON_EXTRACT_BSON"), 161 exp.JSONPathKey: json_path_key_only_name, 162 exp.JSONPathSubscript: lambda self, e: self.json_path_part(e.this), 163 exp.JSONPathRoot: lambda *_: "", 164 exp.JSONFormat: unsupported_args("options", "is_json")(rename_func("JSON_PRETTY")), 165 exp.JSONArrayAgg: unsupported_args("null_handling", "return_type", "strict")( 166 lambda self, e: self.func("JSON_AGG", e.this, suffix=f"{self.sql(e, 'order')})") 167 ), 168 exp.JSONArray: unsupported_args("null_handling", "return_type", "strict")( 169 rename_func("JSON_BUILD_ARRAY") 170 ), 171 exp.JSONBExists: lambda self, e: self.func( 172 "BSON_MATCH_ANY_EXISTS", e.this, e.args.get("path") 173 ), 174 exp.JSONExists: lambda self, e: ( 175 f"{self.sql(e.this)}::?{self.sql(e.args.get('path'))}" 176 if e.args.get("from_dcolonqmark") 177 else self.func("JSON_MATCH_ANY_EXISTS", e.this, e.args.get("path")) 178 ), 179 exp.JSONObject: unsupported_args("null_handling", "unique_keys", "return_type", "encoding")( 180 rename_func("JSON_BUILD_OBJECT") 181 ), 182 exp.DayOfWeekIso: lambda self, e: f"(({self.func('DAYOFWEEK', e.this)} % 7) + 1)", 183 exp.DayOfMonth: rename_func("DAY"), 184 exp.Hll: rename_func("APPROX_COUNT_DISTINCT"), 185 exp.ApproxDistinct: rename_func("APPROX_COUNT_DISTINCT"), 186 exp.CountIf: count_if_to_sum, 187 exp.LogicalOr: lambda self, e: f"MAX(ABS({self.sql(e, 'this')}))", 188 exp.LogicalAnd: lambda self, e: f"MIN(ABS({self.sql(e, 'this')}))", 189 exp.ApproxQuantile: unsupported_args("accuracy", "weight")( 190 lambda self, e: self.func( 191 "APPROX_PERCENTILE", 192 e.this, 193 e.args.get("quantile"), 194 e.args.get("error_tolerance"), 195 ) 196 ), 197 exp.Variance: rename_func("VAR_SAMP"), 198 exp.VariancePop: rename_func("VAR_POP"), 199 exp.Xor: bool_xor_sql, 200 exp.Cbrt: lambda self, e: self.sql( 201 exp.Pow(this=e.this, expression=exp.Literal.number(1) / exp.Literal.number(3)) 202 ), 203 exp.RegexpLike: lambda self, e: self.binary(e, "RLIKE"), 204 exp.Repeat: lambda self, e: self.func( 205 "LPAD", 206 exp.Literal.string(""), 207 exp.Mul(this=self.func("LENGTH", e.this), expression=e.args.get("times")), 208 e.this, 209 ), 210 exp.IsAscii: lambda self, e: f"({self.sql(e, 'this')} RLIKE '^[\x00-\x7f]*$')", 211 exp.MD5Digest: lambda self, e: self.func("UNHEX", self.func("MD5", e.this)), 212 exp.Contains: rename_func("INSTR"), 213 exp.RegexpExtractAll: unsupported_args("position", "occurrence", "group")( 214 lambda self, e: self.func( 215 "REGEXP_MATCH", 216 e.this, 217 e.expression, 218 e.args.get("parameters"), 219 ) 220 ), 221 exp.RegexpExtract: unsupported_args("group")( 222 lambda self, e: self.func( 223 "REGEXP_SUBSTR", 224 e.this, 225 e.expression, 226 e.args.get("position"), 227 e.args.get("occurrence"), 228 e.args.get("parameters"), 229 ) 230 ), 231 exp.StartsWith: lambda self, e: self.func( 232 "REGEXP_INSTR", e.this, self.func("CONCAT", exp.Literal.string("^"), e.expression) 233 ), 234 exp.FromBase: lambda self, e: self.func( 235 "CONV", e.this, e.expression, exp.Literal.number(10) 236 ), 237 exp.RegexpILike: lambda self, e: self.binary( 238 exp.RegexpLike( 239 this=exp.Lower(this=e.this), 240 expression=exp.Lower(this=e.expression), 241 ), 242 "RLIKE", 243 ), 244 exp.Stuff: lambda self, e: self.func( 245 "CONCAT", 246 self.func("SUBSTRING", e.this, exp.Literal.number(1), e.args.get("start") - 1), 247 e.expression, 248 self.func("SUBSTRING", e.this, e.args.get("start") + e.args.get("length")), 249 ), 250 exp.National: lambda self, e: self.national_sql(e, prefix=""), 251 exp.Reduce: unsupported_args("finish")( 252 lambda self, e: self.func("REDUCE", e.args.get("initial"), e.this, e.args.get("merge")) 253 ), 254 exp.MatchAgainst: unsupported_args("modifier")( 255 lambda self, e: generator.Generator.matchagainst_sql(self, e) 256 ), 257 exp.Show: unsupported_args( 258 "history", 259 "terse", 260 "offset", 261 "starts_with", 262 "limit", 263 "from_", 264 "scope", 265 "scope_kind", 266 "mutex", 267 "query", 268 "channel", 269 "log", 270 "types", 271 "privileges", 272 )(lambda self, e: MySQLGenerator.show_sql(self, e)), 273 exp.Describe: unsupported_args( 274 "style", 275 "kind", 276 "expressions", 277 "partition", 278 "format", 279 )(lambda self, e: generator.Generator.describe_sql(self, e)), 280 } 281 282 UNSUPPORTED_TYPES = { 283 exp.DType.ARRAY, 284 exp.DType.AGGREGATEFUNCTION, 285 exp.DType.SIMPLEAGGREGATEFUNCTION, 286 exp.DType.BIGSERIAL, 287 exp.DType.BPCHAR, 288 exp.DType.DATEMULTIRANGE, 289 exp.DType.DATERANGE, 290 exp.DType.DYNAMIC, 291 exp.DType.HLLSKETCH, 292 exp.DType.HSTORE, 293 exp.DType.IMAGE, 294 exp.DType.INET, 295 exp.DType.INT128, 296 exp.DType.INT256, 297 exp.DType.INT4MULTIRANGE, 298 exp.DType.INT4RANGE, 299 exp.DType.INT8MULTIRANGE, 300 exp.DType.INT8RANGE, 301 exp.DType.INTERVAL, 302 exp.DType.IPADDRESS, 303 exp.DType.IPPREFIX, 304 exp.DType.IPV4, 305 exp.DType.IPV6, 306 exp.DType.LIST, 307 exp.DType.MAP, 308 exp.DType.LOWCARDINALITY, 309 exp.DType.MONEY, 310 exp.DType.MULTILINESTRING, 311 exp.DType.NAME, 312 exp.DType.NESTED, 313 exp.DType.NOTHING, 314 exp.DType.NULL, 315 exp.DType.NUMMULTIRANGE, 316 exp.DType.NUMRANGE, 317 exp.DType.OBJECT, 318 exp.DType.RANGE, 319 exp.DType.ROWVERSION, 320 exp.DType.SERIAL, 321 exp.DType.SMALLSERIAL, 322 exp.DType.SMALLMONEY, 323 exp.DType.SUPER, 324 exp.DType.TIMETZ, 325 exp.DType.TIMESTAMPNTZ, 326 exp.DType.TIMESTAMPLTZ, 327 exp.DType.TIMESTAMPTZ, 328 exp.DType.TIMESTAMP_NS, 329 exp.DType.TSMULTIRANGE, 330 exp.DType.TSRANGE, 331 exp.DType.TSTZMULTIRANGE, 332 exp.DType.TSTZRANGE, 333 exp.DType.UINT128, 334 exp.DType.UINT256, 335 exp.DType.UNION, 336 exp.DType.UNKNOWN, 337 exp.DType.USERDEFINED, 338 exp.DType.UUID, 339 exp.DType.VARIANT, 340 exp.DType.XML, 341 exp.DType.TDIGEST, 342 } 343 344 TYPE_MAPPING = { 345 **MySQLGenerator.TYPE_MAPPING, 346 exp.DType.BIGDECIMAL: "DECIMAL", 347 exp.DType.BIT: "BOOLEAN", 348 exp.DType.DATE32: "DATE", 349 exp.DType.DATETIME64: "DATETIME", 350 exp.DType.DECIMAL32: "DECIMAL", 351 exp.DType.DECIMAL64: "DECIMAL", 352 exp.DType.DECIMAL128: "DECIMAL", 353 exp.DType.DECIMAL256: "DECIMAL", 354 exp.DType.ENUM8: "ENUM", 355 exp.DType.ENUM16: "ENUM", 356 exp.DType.FIXEDSTRING: "TEXT", 357 exp.DType.GEOMETRY: "GEOGRAPHY", 358 exp.DType.POINT: "GEOGRAPHYPOINT", 359 exp.DType.RING: "GEOGRAPHY", 360 exp.DType.LINESTRING: "GEOGRAPHY", 361 exp.DType.POLYGON: "GEOGRAPHY", 362 exp.DType.MULTIPOLYGON: "GEOGRAPHY", 363 exp.DType.STRUCT: "RECORD", 364 exp.DType.JSONB: "BSON", 365 exp.DType.TIMESTAMP: "TIMESTAMP", 366 exp.DType.TIMESTAMP_S: "TIMESTAMP", 367 exp.DType.TIMESTAMP_MS: "TIMESTAMP", 368 } 369 370 TYPE_PARAM_SETTINGS = { 371 **MySQLGenerator.TYPE_PARAM_SETTINGS, 372 exp.DType.TIMESTAMP_MS: ((6,), ()), 373 } 374 375 # https://docs.singlestore.com/cloud/reference/sql-reference/restricted-keywords/list-of-restricted-keywords/ 376 RESERVED_KEYWORDS = { 377 "abs", 378 "absolute", 379 "access", 380 "account", 381 "acos", 382 "action", 383 "add", 384 "adddate", 385 "addtime", 386 "admin", 387 "aes_decrypt", 388 "aes_encrypt", 389 "after", 390 "against", 391 "aggregate", 392 "aggregates", 393 "aggregator", 394 "aggregator_id", 395 "aggregator_plan_hash", 396 "aggregators", 397 "algorithm", 398 "all", 399 "also", 400 "alter", 401 "always", 402 "analyse", 403 "analyze", 404 "and", 405 "anti_join", 406 "any", 407 "any_value", 408 "approx_count_distinct", 409 "approx_count_distinct_accumulate", 410 "approx_count_distinct_combine", 411 "approx_count_distinct_estimate", 412 "approx_geography_intersects", 413 "approx_percentile", 414 "arghistory", 415 "arrange", 416 "arrangement", 417 "array", 418 "as", 419 "asc", 420 "ascii", 421 "asensitive", 422 "asin", 423 "asm", 424 "assertion", 425 "assignment", 426 "ast", 427 "asymmetric", 428 "async", 429 "at", 430 "atan", 431 "atan2", 432 "attach", 433 "attribute", 434 "authorization", 435 "auto", 436 "auto_increment", 437 "auto_reprovision", 438 "autostats", 439 "autostats_cardinality_mode", 440 "autostats_enabled", 441 "autostats_histogram_mode", 442 "autostats_sampling", 443 "availability", 444 "avg", 445 "avg_row_length", 446 "avro", 447 "azure", 448 "background", 449 "_background_threads_for_cleanup", 450 "backup", 451 "backup_history", 452 "backup_id", 453 "backward", 454 "batch", 455 "batches", 456 "batch_interval", 457 "_batch_size_limit", 458 "before", 459 "begin", 460 "between", 461 "bigint", 462 "bin", 463 "binary", 464 "_binary", 465 "bit", 466 "bit_and", 467 "bit_count", 468 "bit_or", 469 "bit_xor", 470 "blob", 471 "bool", 472 "boolean", 473 "bootstrap", 474 "both", 475 "_bt", 476 "btree", 477 "bucket_count", 478 "by", 479 "byte", 480 "byte_length", 481 "cache", 482 "call", 483 "call_for_pipeline", 484 "called", 485 "capture", 486 "cascade", 487 "cascaded", 488 "case", 489 "cast", 490 "catalog", 491 "ceil", 492 "ceiling", 493 "chain", 494 "change", 495 "char", 496 "character", 497 "characteristics", 498 "character_length", 499 "char_length", 500 "charset", 501 "check", 502 "checkpoint", 503 "_check_can_connect", 504 "_check_consistency", 505 "checksum", 506 "_checksum", 507 "class", 508 "clear", 509 "client", 510 "client_found_rows", 511 "close", 512 "cluster", 513 "clustered", 514 "cnf", 515 "coalesce", 516 "coercibility", 517 "collate", 518 "collation", 519 "collect", 520 "column", 521 "columnar", 522 "columns", 523 "columnstore", 524 "columnstore_segment_rows", 525 "comment", 526 "comments", 527 "commit", 528 "committed", 529 "_commit_log_tail", 530 "committed", 531 "compact", 532 "compile", 533 "compressed", 534 "compression", 535 "concat", 536 "concat_ws", 537 "concurrent", 538 "concurrently", 539 "condition", 540 "configuration", 541 "connection", 542 "connection_id", 543 "connections", 544 "config", 545 "constraint", 546 "constraints", 547 "content", 548 "continue", 549 "_continue_replay", 550 "conv", 551 "conversion", 552 "convert", 553 "convert_tz", 554 "copy", 555 "_core", 556 "cos", 557 "cost", 558 "cot", 559 "count", 560 "create", 561 "credentials", 562 "cross", 563 "cube", 564 "csv", 565 "cume_dist", 566 "curdate", 567 "current", 568 "current_catalog", 569 "current_date", 570 "current_role", 571 "current_schema", 572 "current_security_groups", 573 "current_security_roles", 574 "current_time", 575 "current_timestamp", 576 "current_user", 577 "cursor", 578 "curtime", 579 "cycle", 580 "data", 581 "database", 582 "databases", 583 "date", 584 "date_add", 585 "datediff", 586 "date_format", 587 "date_sub", 588 "date_trunc", 589 "datetime", 590 "day", 591 "day_hour", 592 "day_microsecond", 593 "day_minute", 594 "dayname", 595 "dayofmonth", 596 "dayofweek", 597 "dayofyear", 598 "day_second", 599 "deallocate", 600 "dec", 601 "decimal", 602 "declare", 603 "decode", 604 "default", 605 "defaults", 606 "deferrable", 607 "deferred", 608 "defined", 609 "definer", 610 "degrees", 611 "delayed", 612 "delay_key_write", 613 "delete", 614 "delimiter", 615 "delimiters", 616 "dense_rank", 617 "desc", 618 "describe", 619 "detach", 620 "deterministic", 621 "dictionary", 622 "differential", 623 "directory", 624 "disable", 625 "discard", 626 "_disconnect", 627 "disk", 628 "distinct", 629 "distinctrow", 630 "distributed_joins", 631 "div", 632 "do", 633 "document", 634 "domain", 635 "dot_product", 636 "double", 637 "drop", 638 "_drop_profile", 639 "dual", 640 "dump", 641 "duplicate", 642 "dynamic", 643 "earliest", 644 "each", 645 "echo", 646 "election", 647 "else", 648 "elseif", 649 "elt", 650 "enable", 651 "enclosed", 652 "encoding", 653 "encrypted", 654 "end", 655 "engine", 656 "engines", 657 "enum", 658 "errors", 659 "escape", 660 "escaped", 661 "estimate", 662 "euclidean_distance", 663 "event", 664 "events", 665 "except", 666 "exclude", 667 "excluding", 668 "exclusive", 669 "execute", 670 "exists", 671 "exit", 672 "exp", 673 "explain", 674 "extended", 675 "extension", 676 "external", 677 "external_host", 678 "external_port", 679 "extract", 680 "extractor", 681 "extractors", 682 "extra_join", 683 "_failover", 684 "failed_login_attempts", 685 "failure", 686 "false", 687 "family", 688 "fault", 689 "fetch", 690 "field", 691 "fields", 692 "file", 693 "files", 694 "fill", 695 "first", 696 "first_value", 697 "fix_alter", 698 "fixed", 699 "float", 700 "float4", 701 "float8", 702 "floor", 703 "flush", 704 "following", 705 "for", 706 "force", 707 "force_compiled_mode", 708 "force_interpreter_mode", 709 "foreground", 710 "foreign", 711 "format", 712 "forward", 713 "found_rows", 714 "freeze", 715 "from", 716 "from_base64", 717 "from_days", 718 "from_unixtime", 719 "fs", 720 "_fsync", 721 "full", 722 "fulltext", 723 "function", 724 "functions", 725 "gc", 726 "gcs", 727 "get_format", 728 "_gc", 729 "_gcx", 730 "generate", 731 "geography", 732 "geography_area", 733 "geography_contains", 734 "geography_distance", 735 "geography_intersects", 736 "geography_latitude", 737 "geography_length", 738 "geography_longitude", 739 "geographypoint", 740 "geography_point", 741 "geography_within_distance", 742 "geometry", 743 "geometry_area", 744 "geometry_contains", 745 "geometry_distance", 746 "geometry_filter", 747 "geometry_intersects", 748 "geometry_length", 749 "geometrypoint", 750 "geometry_point", 751 "geometry_within_distance", 752 "geometry_x", 753 "geometry_y", 754 "global", 755 "_global_version_timestamp", 756 "grant", 757 "granted", 758 "grants", 759 "greatest", 760 "group", 761 "grouping", 762 "groups", 763 "group_concat", 764 "gzip", 765 "handle", 766 "handler", 767 "hard_cpu_limit_percentage", 768 "hash", 769 "has_temp_tables", 770 "having", 771 "hdfs", 772 "header", 773 "heartbeat_no_logging", 774 "hex", 775 "highlight", 776 "high_priority", 777 "hold", 778 "holding", 779 "host", 780 "hosts", 781 "hour", 782 "hour_microsecond", 783 "hour_minute", 784 "hour_second", 785 "identified", 786 "identity", 787 "if", 788 "ifnull", 789 "ignore", 790 "ilike", 791 "immediate", 792 "immutable", 793 "implicit", 794 "import", 795 "in", 796 "including", 797 "increment", 798 "incremental", 799 "index", 800 "indexes", 801 "inet_aton", 802 "inet_ntoa", 803 "inet6_aton", 804 "inet6_ntoa", 805 "infile", 806 "inherit", 807 "inherits", 808 "_init_profile", 809 "init", 810 "initcap", 811 "initialize", 812 "initially", 813 "inject", 814 "inline", 815 "inner", 816 "inout", 817 "input", 818 "insensitive", 819 "insert", 820 "insert_method", 821 "instance", 822 "instead", 823 "instr", 824 "int", 825 "int1", 826 "int2", 827 "int3", 828 "int4", 829 "int8", 830 "integer", 831 "_internal_dynamic_typecast", 832 "interpreter_mode", 833 "intersect", 834 "interval", 835 "into", 836 "invoker", 837 "is", 838 "isnull", 839 "isolation", 840 "iterate", 841 "join", 842 "json", 843 "json_agg", 844 "json_array_contains_double", 845 "json_array_contains_json", 846 "json_array_contains_string", 847 "json_array_push_double", 848 "json_array_push_json", 849 "json_array_push_string", 850 "json_delete_key", 851 "json_extract_double", 852 "json_extract_json", 853 "json_extract_string", 854 "json_extract_bigint", 855 "json_get_type", 856 "json_length", 857 "json_set_double", 858 "json_set_json", 859 "json_set_string", 860 "json_splice_double", 861 "json_splice_json", 862 "json_splice_string", 863 "kafka", 864 "key", 865 "key_block_size", 866 "keys", 867 "kill", 868 "killall", 869 "label", 870 "lag", 871 "language", 872 "large", 873 "last", 874 "last_day", 875 "last_insert_id", 876 "last_value", 877 "lateral", 878 "latest", 879 "lc_collate", 880 "lc_ctype", 881 "lcase", 882 "lead", 883 "leading", 884 "leaf", 885 "leakproof", 886 "least", 887 "leave", 888 "leaves", 889 "left", 890 "length", 891 "level", 892 "license", 893 "like", 894 "limit", 895 "lines", 896 "listen", 897 "llvm", 898 "ln", 899 "load", 900 "loaddata_where", 901 "_load", 902 "local", 903 "localtime", 904 "localtimestamp", 905 "locate", 906 "location", 907 "lock", 908 "log", 909 "log10", 910 "log2", 911 "long", 912 "longblob", 913 "longtext", 914 "loop", 915 "lower", 916 "low_priority", 917 "lpad", 918 "_ls", 919 "ltrim", 920 "lz4", 921 "management", 922 "_management_thread", 923 "mapping", 924 "master", 925 "match", 926 "materialized", 927 "max", 928 "maxvalue", 929 "max_concurrency", 930 "max_errors", 931 "max_partitions_per_batch", 932 "max_queue_depth", 933 "max_retries_per_batch_partition", 934 "max_rows", 935 "mbc", 936 "md5", 937 "mpl", 938 "median", 939 "mediumblob", 940 "mediumint", 941 "mediumtext", 942 "member", 943 "memory", 944 "memory_percentage", 945 "_memsql_table_id_lookup", 946 "memsql", 947 "memsql_deserialize", 948 "memsql_imitating_kafka", 949 "memsql_serialize", 950 "merge", 951 "metadata", 952 "microsecond", 953 "middleint", 954 "min", 955 "min_rows", 956 "minus", 957 "minute", 958 "minute_microsecond", 959 "minute_second", 960 "minvalue", 961 "mod", 962 "mode", 963 "model", 964 "modifies", 965 "modify", 966 "month", 967 "monthname", 968 "months_between", 969 "move", 970 "mpl", 971 "names", 972 "named", 973 "namespace", 974 "national", 975 "natural", 976 "nchar", 977 "next", 978 "no", 979 "node", 980 "none", 981 "no_query_rewrite", 982 "noparam", 983 "not", 984 "nothing", 985 "notify", 986 "now", 987 "nowait", 988 "no_write_to_binlog", 989 "no_query_rewrite", 990 "norely", 991 "nth_value", 992 "ntile", 993 "null", 994 "nullcols", 995 "nullif", 996 "nulls", 997 "numeric", 998 "nvarchar", 999 "object", 1000 "octet_length", 1001 "of", 1002 "off", 1003 "offline", 1004 "offset", 1005 "offsets", 1006 "oids", 1007 "on", 1008 "online", 1009 "only", 1010 "open", 1011 "operator", 1012 "optimization", 1013 "optimize", 1014 "optimizer", 1015 "optimizer_state", 1016 "option", 1017 "options", 1018 "optionally", 1019 "or", 1020 "order", 1021 "ordered_serialize", 1022 "orphan", 1023 "out", 1024 "out_of_order", 1025 "outer", 1026 "outfile", 1027 "over", 1028 "overlaps", 1029 "overlay", 1030 "owned", 1031 "owner", 1032 "pack_keys", 1033 "paired", 1034 "parser", 1035 "parquet", 1036 "partial", 1037 "partition", 1038 "partition_id", 1039 "partitioning", 1040 "partitions", 1041 "passing", 1042 "password", 1043 "password_lock_time", 1044 "parser", 1045 "pause", 1046 "_pause_replay", 1047 "percent_rank", 1048 "percentile_cont", 1049 "percentile_disc", 1050 "periodic", 1051 "persisted", 1052 "pi", 1053 "pipeline", 1054 "pipelines", 1055 "pivot", 1056 "placing", 1057 "plan", 1058 "plans", 1059 "plancache", 1060 "plugins", 1061 "pool", 1062 "pools", 1063 "port", 1064 "position", 1065 "pow", 1066 "power", 1067 "preceding", 1068 "precision", 1069 "prepare", 1070 "prepared", 1071 "preserve", 1072 "primary", 1073 "prior", 1074 "privileges", 1075 "procedural", 1076 "procedure", 1077 "procedures", 1078 "process", 1079 "processlist", 1080 "profile", 1081 "profiles", 1082 "program", 1083 "promote", 1084 "proxy", 1085 "purge", 1086 "quarter", 1087 "queries", 1088 "query", 1089 "query_timeout", 1090 "queue", 1091 "quote", 1092 "radians", 1093 "rand", 1094 "range", 1095 "rank", 1096 "read", 1097 "_read", 1098 "reads", 1099 "real", 1100 "reassign", 1101 "rebalance", 1102 "recheck", 1103 "record", 1104 "recursive", 1105 "redundancy", 1106 "redundant", 1107 "ref", 1108 "reference", 1109 "references", 1110 "refresh", 1111 "regexp", 1112 "reindex", 1113 "relative", 1114 "release", 1115 "reload", 1116 "rely", 1117 "remote", 1118 "remove", 1119 "rename", 1120 "repair", 1121 "_repair_table", 1122 "repeat", 1123 "repeatable", 1124 "_repl", 1125 "_reprovisioning", 1126 "replace", 1127 "replica", 1128 "replicate", 1129 "replicating", 1130 "replication", 1131 "durability", 1132 "require", 1133 "resource", 1134 "resource_pool", 1135 "reset", 1136 "restart", 1137 "restore", 1138 "restrict", 1139 "result", 1140 "_resurrect", 1141 "retry", 1142 "return", 1143 "returning", 1144 "returns", 1145 "reverse", 1146 "revoke", 1147 "rg_pool", 1148 "right", 1149 "right_anti_join", 1150 "right_semi_join", 1151 "right_straight_join", 1152 "rlike", 1153 "role", 1154 "roles", 1155 "rollback", 1156 "rollup", 1157 "round", 1158 "routine", 1159 "row", 1160 "row_count", 1161 "row_format", 1162 "row_number", 1163 "rows", 1164 "rowstore", 1165 "rule", 1166 "rpad", 1167 "_rpc", 1168 "rtrim", 1169 "running", 1170 "s3", 1171 "safe", 1172 "save", 1173 "savepoint", 1174 "scalar", 1175 "schema", 1176 "schemas", 1177 "schema_binding", 1178 "scroll", 1179 "search", 1180 "second", 1181 "second_microsecond", 1182 "sec_to_time", 1183 "security", 1184 "select", 1185 "semi_join", 1186 "_send_threads", 1187 "sensitive", 1188 "separator", 1189 "sequence", 1190 "sequences", 1191 "serial", 1192 "serializable", 1193 "series", 1194 "service_user", 1195 "server", 1196 "session", 1197 "session_user", 1198 "set", 1199 "setof", 1200 "security_lists_intersect", 1201 "sha", 1202 "sha1", 1203 "sha2", 1204 "shard", 1205 "sharded", 1206 "sharded_id", 1207 "share", 1208 "show", 1209 "shutdown", 1210 "sigmoid", 1211 "sign", 1212 "signal", 1213 "similar", 1214 "simple", 1215 "site", 1216 "signed", 1217 "sin", 1218 "skip", 1219 "skipped_batches", 1220 "sleep", 1221 "_sleep", 1222 "smallint", 1223 "snapshot", 1224 "_snapshot", 1225 "_snapshots", 1226 "soft_cpu_limit_percentage", 1227 "some", 1228 "soname", 1229 "sparse", 1230 "spatial", 1231 "spatial_check_index", 1232 "specific", 1233 "split", 1234 "sql", 1235 "sql_big_result", 1236 "sql_buffer_result", 1237 "sql_cache", 1238 "sql_calc_found_rows", 1239 "sqlexception", 1240 "sql_mode", 1241 "sql_no_cache", 1242 "sql_no_logging", 1243 "sql_small_result", 1244 "sqlstate", 1245 "sqlwarning", 1246 "sqrt", 1247 "ssl", 1248 "stable", 1249 "standalone", 1250 "start", 1251 "starting", 1252 "state", 1253 "statement", 1254 "statistics", 1255 "stats", 1256 "status", 1257 "std", 1258 "stddev", 1259 "stddev_pop", 1260 "stddev_samp", 1261 "stdin", 1262 "stdout", 1263 "stop", 1264 "storage", 1265 "str_to_date", 1266 "straight_join", 1267 "strict", 1268 "string", 1269 "strip", 1270 "subdate", 1271 "substr", 1272 "substring", 1273 "substring_index", 1274 "success", 1275 "sum", 1276 "super", 1277 "symmetric", 1278 "sync_snapshot", 1279 "sync", 1280 "_sync", 1281 "_sync2", 1282 "_sync_partitions", 1283 "_sync_snapshot", 1284 "synchronize", 1285 "sysid", 1286 "system", 1287 "table", 1288 "table_checksum", 1289 "tables", 1290 "tablespace", 1291 "tags", 1292 "tan", 1293 "target_size", 1294 "task", 1295 "temp", 1296 "template", 1297 "temporary", 1298 "temptable", 1299 "_term_bump", 1300 "terminate", 1301 "terminated", 1302 "test", 1303 "text", 1304 "then", 1305 "time", 1306 "timediff", 1307 "time_bucket", 1308 "time_format", 1309 "timeout", 1310 "timestamp", 1311 "timestampadd", 1312 "timestampdiff", 1313 "timezone", 1314 "time_to_sec", 1315 "tinyblob", 1316 "tinyint", 1317 "tinytext", 1318 "to", 1319 "to_base64", 1320 "to_char", 1321 "to_date", 1322 "to_days", 1323 "to_json", 1324 "to_number", 1325 "to_seconds", 1326 "to_timestamp", 1327 "tracelogs", 1328 "traditional", 1329 "trailing", 1330 "transform", 1331 "transaction", 1332 "_transactions_experimental", 1333 "treat", 1334 "trigger", 1335 "triggers", 1336 "trim", 1337 "true", 1338 "trunc", 1339 "truncate", 1340 "trusted", 1341 "two_phase", 1342 "_twopcid", 1343 "type", 1344 "types", 1345 "ucase", 1346 "unbounded", 1347 "uncommitted", 1348 "undefined", 1349 "undo", 1350 "unencrypted", 1351 "unenforced", 1352 "unhex", 1353 "unhold", 1354 "unicode", 1355 "union", 1356 "unique", 1357 "_unittest", 1358 "unix_timestamp", 1359 "unknown", 1360 "unlisten", 1361 "_unload", 1362 "unlock", 1363 "unlogged", 1364 "unpivot", 1365 "unsigned", 1366 "until", 1367 "update", 1368 "upgrade", 1369 "upper", 1370 "usage", 1371 "use", 1372 "user", 1373 "users", 1374 "using", 1375 "utc_date", 1376 "utc_time", 1377 "utc_timestamp", 1378 "_utf8", 1379 "vacuum", 1380 "valid", 1381 "validate", 1382 "validator", 1383 "value", 1384 "values", 1385 "varbinary", 1386 "varchar", 1387 "varcharacter", 1388 "variables", 1389 "variadic", 1390 "variance", 1391 "var_pop", 1392 "var_samp", 1393 "varying", 1394 "vector_sub", 1395 "verbose", 1396 "version", 1397 "view", 1398 "void", 1399 "volatile", 1400 "voting", 1401 "wait", 1402 "_wake", 1403 "warnings", 1404 "week", 1405 "weekday", 1406 "weekofyear", 1407 "when", 1408 "where", 1409 "while", 1410 "whitespace", 1411 "window", 1412 "with", 1413 "without", 1414 "within", 1415 "_wm_heartbeat", 1416 "work", 1417 "workload", 1418 "wrapper", 1419 "write", 1420 "xact_id", 1421 "xor", 1422 "year", 1423 "year_month", 1424 "yes", 1425 "zerofill", 1426 "zone", 1427 } 1428 1429 def jsonextractscalar_sql(self, expression: exp.JSONExtractScalar) -> str: 1430 json_type = expression.args.get("json_type") 1431 func_name = "JSON_EXTRACT_JSON" if json_type is None else f"JSON_EXTRACT_{json_type}" 1432 return json_extract_segments(func_name)(self, expression) 1433 1434 def jsonbextractscalar_sql(self, expression: exp.JSONBExtractScalar) -> str: 1435 json_type = expression.args.get("json_type") 1436 func_name = "BSON_EXTRACT_BSON" if json_type is None else f"BSON_EXTRACT_{json_type}" 1437 return json_extract_segments(func_name)(self, expression) 1438 1439 def jsonextractarray_sql(self, expression: exp.JSONExtractArray) -> str: 1440 self.unsupported("Arrays are not supported in SingleStore") 1441 return self.function_fallback_sql(expression) 1442 1443 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 1444 if expression.args.get("on_condition"): 1445 self.unsupported("JSON_VALUE does not support on_condition") 1446 res: exp.Expr = exp.JSONExtractScalar( 1447 this=expression.this, 1448 expression=expression.args.get("path"), 1449 json_type="STRING", 1450 ) 1451 1452 returning = expression.args.get("returning") 1453 if returning is not None: 1454 res = exp.Cast(this=res, to=returning) 1455 1456 return self.sql(res) 1457 1458 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 1459 # SingleStore includes trailing NULLs in percentile calculations, so we sort them first 1460 if isinstance(expression.this, (exp.PercentileCont, exp.PercentileDisc)) and isinstance( 1461 expression.expression, exp.Order 1462 ): 1463 expression = expression.copy() 1464 for ordered in expression.expression.expressions: 1465 ordered.set("nulls_first", True) 1466 1467 return super().withingroup_sql(expression) 1468 1469 def all_sql(self, expression: exp.All) -> str: 1470 self.unsupported("ALL subquery predicate is not supported in SingleStore") 1471 return super().all_sql(expression) 1472 1473 def jsonarraycontains_sql(self, expression: exp.JSONArrayContains) -> str: 1474 json_type = expression.text("json_type").upper() 1475 1476 if json_type: 1477 return self.func( 1478 f"JSON_ARRAY_CONTAINS_{json_type}", expression.expression, expression.this 1479 ) 1480 1481 return self.func( 1482 "JSON_ARRAY_CONTAINS_JSON", 1483 expression.expression, 1484 self.func("TO_JSON", expression.this), 1485 ) 1486 1487 def datatype_sql(self, expression: exp.DataType) -> str: 1488 for arg_name in ("kind", "values"): 1489 if expression.args.get(arg_name): 1490 self.unsupported(f"DATATYPE does not support {arg_name}") 1491 if expression.args.get("nested") and not expression.is_type(exp.DType.STRUCT): 1492 self.unsupported( 1493 f"Argument 'nested' is not supported for representation of '{expression.this.value}' in SingleStore" 1494 ) 1495 1496 if expression.is_type(exp.DType.VARBINARY) and not expression.expressions: 1497 # `VARBINARY` must always have a size - if it doesn't, we always generate `BLOB` 1498 return "BLOB" 1499 if expression.is_type( 1500 exp.DType.DECIMAL32, 1501 exp.DType.DECIMAL64, 1502 exp.DType.DECIMAL128, 1503 exp.DType.DECIMAL256, 1504 ): 1505 scale = self.expressions(expression, flat=True) 1506 1507 if expression.is_type(exp.DType.DECIMAL32): 1508 precision = "9" 1509 elif expression.is_type(exp.DType.DECIMAL64): 1510 precision = "18" 1511 elif expression.is_type(exp.DType.DECIMAL128): 1512 precision = "38" 1513 else: 1514 # 65 is a maximum precision supported in SingleStore 1515 precision = "65" 1516 if scale is not None: 1517 return f"DECIMAL({precision}, {scale[0]})" 1518 else: 1519 return f"DECIMAL({precision})" 1520 if expression.is_type(exp.DType.VECTOR): 1521 expressions = expression.expressions 1522 if len(expressions) == 2: 1523 type_name = self.sql(expressions[0]) 1524 if type_name in self.dialect.INVERSE_VECTOR_TYPE_ALIASES: 1525 type_name = self.dialect.INVERSE_VECTOR_TYPE_ALIASES[type_name] 1526 1527 return f"VECTOR({self.sql(expressions[1])}, {type_name})" 1528 1529 return super().datatype_sql(expression) 1530 1531 def collate_sql(self, expression: exp.Collate) -> str: 1532 # SingleStore does not support setting a collation for column in the SELECT query, 1533 # so we cast column to a LONGTEXT type with specific collation. If the cast is 1534 # already there (e.g. when regenerating previously generated SQL), don't add 1535 # another one, so that generation stays idempotent. 1536 this = expression.this 1537 if isinstance(this, exp.Cast) and this.to.this == exp.DType.LONGTEXT: 1538 return self.binary(expression, "COLLATE") 1539 return self.binary(expression, ":> LONGTEXT COLLATE") 1540 1541 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 1542 timezone = expression.this 1543 if timezone: 1544 if isinstance(timezone, exp.Literal) and timezone.name.lower() == "utc": 1545 return self.func("UTC_DATE") 1546 self.unsupported("CurrentDate with timezone is not supported in SingleStore") 1547 1548 return self.func("CURRENT_DATE") 1549 1550 def currenttime_sql(self, expression: exp.CurrentTime) -> str: 1551 arg = expression.this 1552 if arg: 1553 if isinstance(arg, exp.Literal) and arg.name.lower() == "utc": 1554 return self.func("UTC_TIME") 1555 if isinstance(arg, exp.Literal) and arg.is_number: 1556 return self.func("CURRENT_TIME", arg) 1557 self.unsupported("CurrentTime with timezone is not supported in SingleStore") 1558 1559 return self.func("CURRENT_TIME") 1560 1561 def currenttimestamp_sql(self, expression: exp.CurrentTimestamp) -> str: 1562 arg = expression.this 1563 if arg: 1564 if isinstance(arg, exp.Literal) and arg.name.lower() == "utc": 1565 return self.func("UTC_TIMESTAMP") 1566 if isinstance(arg, exp.Literal) and arg.is_number: 1567 return self.func("CURRENT_TIMESTAMP", arg) 1568 self.unsupported("CurrentTimestamp with timezone is not supported in SingleStore") 1569 1570 return self.func("CURRENT_TIMESTAMP") 1571 1572 def standardhash_sql(self, expression: exp.StandardHash) -> str: 1573 hash_function = expression.expression 1574 if hash_function is None: 1575 return self.func("SHA", expression.this) 1576 if isinstance(hash_function, exp.Literal): 1577 if hash_function.name.lower() == "sha": 1578 return self.func("SHA", expression.this) 1579 if hash_function.name.lower() == "md5": 1580 return self.func("MD5", expression.this) 1581 1582 self.unsupported(f"{hash_function.this} hash method is not supported in SingleStore") 1583 return self.func("SHA", expression.this) 1584 1585 self.unsupported("STANDARD_HASH function is not supported in SingleStore") 1586 return self.func("SHA", expression.this) 1587 1588 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 1589 for arg_name in ("is_database", "exists", "cluster", "identity", "option", "partition"): 1590 if expression.args.get(arg_name): 1591 self.unsupported(f"TRUNCATE TABLE does not support {arg_name}") 1592 statements = [] 1593 for table in expression.expressions: 1594 statements.append(f"TRUNCATE {self.sql(table)}") 1595 1596 return "; ".join(statements) 1597 1598 def renamecolumn_sql(self, expression: exp.RenameColumn) -> str: 1599 if expression.args.get("exists"): 1600 self.unsupported("RENAME COLUMN does not support exists") 1601 old_column = self.sql(expression, "this") 1602 new_column = self.sql(expression, "to") 1603 return f"CHANGE {old_column} {new_column}" 1604 1605 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 1606 for arg_name in ("drop", "comment", "visible", "using"): 1607 if expression.args.get(arg_name): 1608 self.unsupported(f"ALTER COLUMN does not support {arg_name}") 1609 alter = super().altercolumn_sql(expression) 1610 1611 collate = self.sql(expression, "collate") 1612 collate = f" COLLATE {collate}" if collate else "" 1613 return f"{alter}{collate}" 1614 1615 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 1616 this = self.sql(expression, "this") 1617 not_null = " NOT NULL" if expression.args.get("not_null") else "" 1618 type = self.sql(expression, "data_type") or "AUTO" 1619 return f"AS {this} PERSISTED {type}{not_null}"
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
SUPPORTED_JSON_PATH_PARTS =
{<class 'sqlglot.expressions.query.JSONPathKey'>, <class 'sqlglot.expressions.query.JSONPathRoot'>, <class 'sqlglot.expressions.query.JSONPathSubscript'>}
TRANSFORMS =
{<class 'sqlglot.expressions.query.JSONPathKey'>: <function json_path_key_only_name>, <class 'sqlglot.expressions.query.JSONPathRoot'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.query.JSONPathSubscript'>: <function SingleStoreGenerator.<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.AutoRefreshProperty'>: <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 MySQLGenerator.<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 rename_func.<locals>.<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 rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.UtcTimestamp'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.query.Variadic'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.VarMap'>: <function Generator.<lambda>>, <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.ArrayAgg'>: <function rename_func.<locals>.<lambda>>, <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.math.BitwiseCount'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.Chr'>: <function MySQLGenerator.<lambda>>, <class 'sqlglot.expressions.functions.CurrentVersion'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.DateDiff'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.DateAdd'>: <function date_add_sql.<locals>.func>, <class 'sqlglot.expressions.temporal.DateStrToDate'>: <function datestrtodate_sql>, <class 'sqlglot.expressions.temporal.DateSub'>: <function date_add_sql.<locals>.func>, <class 'sqlglot.expressions.temporal.DateTrunc'>: <function timestamptrunc_sql.<locals>._timestamptrunc_sql>, <class 'sqlglot.expressions.temporal.Day'>: <function remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.temporal.DayOfMonth'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.DayOfWeek'>: <function remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.temporal.DayOfYear'>: <function remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.aggregate.GroupConcat'>: <function MySQLGenerator.<lambda>>, <class 'sqlglot.expressions.core.ILike'>: <function no_ilike_sql>, <class 'sqlglot.expressions.functions.If'>: <function if_sql.<locals>._if_sql>, <class 'sqlglot.expressions.string.Length'>: <function length_or_char_length_sql>, <class 'sqlglot.expressions.aggregate.LogicalOr'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.aggregate.LogicalAnd'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.aggregate.Max'>: <function max_or_greatest>, <class 'sqlglot.expressions.aggregate.Min'>: <function min_or_least>, <class 'sqlglot.expressions.temporal.Month'>: <function remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.core.NullSafeEQ'>: <function MySQLGenerator.<lambda>>, <class 'sqlglot.expressions.core.NullSafeNEQ'>: <function MySQLGenerator.<lambda>>, <class 'sqlglot.expressions.string.NumberToStr'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.query.Pivot'>: <function no_pivot_sql>, <class 'sqlglot.expressions.query.Select'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.string.StrPosition'>: <function MySQLGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.StrToDate'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.StrToTime'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.string.Stuff'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.query.TableSample'>: <function no_tablesample_sql>, <class 'sqlglot.expressions.temporal.TimeFromParts'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.TimestampAdd'>: <function date_add_interval_sql.<locals>.func>, <class 'sqlglot.expressions.temporal.TimestampDiff'>: <function MySQLGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.TimestampSub'>: <function date_add_interval_sql.<locals>.func>, <class 'sqlglot.expressions.temporal.TimeStrToUnix'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.TimeStrToTime'>: <function MySQLGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.TimeToStr'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.string.Trim'>: <function trim_sql>, <class 'sqlglot.expressions.math.Trunc'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.functions.TryCast'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.TsOrDsAdd'>: <function date_add_sql.<locals>.func>, <class 'sqlglot.expressions.temporal.TsOrDsDiff'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.TsOrDsToDate'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.string.Unicode'>: <function MySQLGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.UnixToTime'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.Week'>: <function remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.temporal.WeekOfYear'>: <function remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.temporal.Year'>: <function remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.string.ToChar'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.Date'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.functions.Cast'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.functions.CastToStrType'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.StrToUnix'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.TimeToUnix'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.UnixSeconds'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.UnixToStr'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.UnixToTimeStr'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.DateBin'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.TimeStrToDate'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.core.FromTimeZone'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.DiToDate'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.DateToDi'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.TsOrDiToDi'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.Time'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.DatetimeAdd'>: <function remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.temporal.DatetimeTrunc'>: <function timestamptrunc_sql.<locals>._timestamptrunc_sql>, <class 'sqlglot.expressions.temporal.DatetimeSub'>: <function date_add_interval_sql.<locals>.func>, <class 'sqlglot.expressions.temporal.DatetimeDiff'>: <function timestampdiff_sql>, <class 'sqlglot.expressions.temporal.TimestampTrunc'>: <function timestamptrunc_sql.<locals>._timestamptrunc_sql>, <class 'sqlglot.expressions.temporal.CurrentDatetime'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.json.JSONExtract'>: <function json_extract_segments.<locals>._json_extract_segments>, <class 'sqlglot.expressions.json.JSONBExtract'>: <function json_extract_segments.<locals>._json_extract_segments>, <class 'sqlglot.expressions.json.JSONFormat'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.json.JSONArrayAgg'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.json.JSONArray'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.json.JSONBExists'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.json.JSONExists'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.DayOfWeekIso'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.core.Hll'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.ApproxDistinct'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.CountIf'>: <function count_if_to_sum>, <class 'sqlglot.expressions.aggregate.ApproxQuantile'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.aggregate.Variance'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.VariancePop'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.core.Xor'>: <function bool_xor_sql>, <class 'sqlglot.expressions.math.Cbrt'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.core.RegexpLike'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.string.Repeat'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.string.IsAscii'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.string.MD5Digest'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.string.Contains'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.RegexpExtractAll'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.string.RegexpExtract'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.string.StartsWith'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.string.FromBase'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.string.RegexpILike'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.query.National'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.array.Reduce'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.string.MatchAgainst'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.ddl.Show'>: <function SingleStoreGenerator.<lambda>>, <class 'sqlglot.expressions.ddl.Describe'>: <function SingleStoreGenerator.<lambda>>}
UNSUPPORTED_TYPES =
{<DType.SMALLMONEY: 'SMALLMONEY'>, <DType.HSTORE: 'HSTORE'>, <DType.TDIGEST: 'TDIGEST'>, <DType.NAME: 'NAME'>, <DType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, <DType.UNION: 'UNION'>, <DType.INT4RANGE: 'INT4RANGE'>, <DType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>, <DType.USERDEFINED: 'USER-DEFINED'>, <DType.ROWVERSION: 'ROWVERSION'>, <DType.SUPER: 'SUPER'>, <DType.INT8RANGE: 'INT8RANGE'>, <DType.DATERANGE: 'DATERANGE'>, <DType.NULL: 'NULL'>, <DType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, <DType.OBJECT: 'OBJECT'>, <DType.TIMETZ: 'TIMETZ'>, <DType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <DType.NOTHING: 'NOTHING'>, <DType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <DType.INTERVAL: 'INTERVAL'>, <DType.TSRANGE: 'TSRANGE'>, <DType.BPCHAR: 'BPCHAR'>, <DType.SMALLSERIAL: 'SMALLSERIAL'>, <DType.INT256: 'INT256'>, <DType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, <DType.NUMRANGE: 'NUMRANGE'>, <DType.ARRAY: 'ARRAY'>, <DType.TSMULTIRANGE: 'TSMULTIRANGE'>, <DType.UUID: 'UUID'>, <DType.SIMPLEAGGREGATEFUNCTION: 'SIMPLEAGGREGATEFUNCTION'>, <DType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, <DType.BIGSERIAL: 'BIGSERIAL'>, <DType.IPADDRESS: 'IPADDRESS'>, <DType.TIMESTAMP_NS: 'TIMESTAMP_NS'>, <DType.MONEY: 'MONEY'>, <DType.IPV6: 'IPV6'>, <DType.VARIANT: 'VARIANT'>, <DType.IPPREFIX: 'IPPREFIX'>, <DType.RANGE: 'RANGE'>, <DType.INT128: 'INT128'>, <DType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, <DType.LIST: 'LIST'>, <DType.AGGREGATEFUNCTION: 'AGGREGATEFUNCTION'>, <DType.NESTED: 'NESTED'>, <DType.IMAGE: 'IMAGE'>, <DType.SERIAL: 'SERIAL'>, <DType.UINT128: 'UINT128'>, <DType.IPV4: 'IPV4'>, <DType.HLLSKETCH: 'HLLSKETCH'>, <DType.DYNAMIC: 'DYNAMIC'>, <DType.UINT256: 'UINT256'>, <DType.MULTILINESTRING: 'MULTILINESTRING'>, <DType.INET: 'INET'>, <DType.MAP: 'MAP'>, <DType.LOWCARDINALITY: 'LOWCARDINALITY'>, <DType.UNKNOWN: 'UNKNOWN'>, <DType.TSTZRANGE: 'TSTZRANGE'>, <DType.XML: 'XML'>}
TYPE_MAPPING =
{<DType.NCHAR: 'NCHAR'>: 'CHAR', <DType.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <DType.INET: 'INET'>: 'INET', <DType.ROWVERSION: 'ROWVERSION'>: 'VARBINARY', <DType.UBIGINT: 'UBIGINT'>: 'BIGINT', <DType.UINT: 'UINT'>: 'INT', <DType.UMEDIUMINT: 'UMEDIUMINT'>: 'MEDIUMINT', <DType.USMALLINT: 'USMALLINT'>: 'SMALLINT', <DType.UTINYINT: 'UTINYINT'>: 'TINYINT', <DType.UDECIMAL: 'UDECIMAL'>: 'DECIMAL', <DType.UDOUBLE: 'UDOUBLE'>: 'DOUBLE', <DType.DATETIME2: 'DATETIME2'>: 'DATETIME', <DType.SMALLDATETIME: 'SMALLDATETIME'>: 'DATETIME', <DType.TIMESTAMP: 'TIMESTAMP'>: 'TIMESTAMP', <DType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>: 'DATETIME', <DType.TIMESTAMPTZ: 'TIMESTAMPTZ'>: 'TIMESTAMP', <DType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>: 'TIMESTAMP', <DType.BIGDECIMAL: 'BIGDECIMAL'>: 'DECIMAL', <DType.BIT: 'BIT'>: 'BOOLEAN', <DType.DATE32: 'DATE32'>: 'DATE', <DType.DATETIME64: 'DATETIME64'>: 'DATETIME', <DType.DECIMAL32: 'DECIMAL32'>: 'DECIMAL', <DType.DECIMAL64: 'DECIMAL64'>: 'DECIMAL', <DType.DECIMAL128: 'DECIMAL128'>: 'DECIMAL', <DType.DECIMAL256: 'DECIMAL256'>: 'DECIMAL', <DType.ENUM8: 'ENUM8'>: 'ENUM', <DType.ENUM16: 'ENUM16'>: 'ENUM', <DType.FIXEDSTRING: 'FIXEDSTRING'>: 'TEXT', <DType.GEOMETRY: 'GEOMETRY'>: 'GEOGRAPHY', <DType.POINT: 'POINT'>: 'GEOGRAPHYPOINT', <DType.RING: 'RING'>: 'GEOGRAPHY', <DType.LINESTRING: 'LINESTRING'>: 'GEOGRAPHY', <DType.POLYGON: 'POLYGON'>: 'GEOGRAPHY', <DType.MULTIPOLYGON: 'MULTIPOLYGON'>: 'GEOGRAPHY', <DType.STRUCT: 'STRUCT'>: 'RECORD', <DType.JSONB: 'JSONB'>: 'BSON', <DType.TIMESTAMP_S: 'TIMESTAMP_S'>: 'TIMESTAMP', <DType.TIMESTAMP_MS: 'TIMESTAMP_MS'>: 'TIMESTAMP'}
RESERVED_KEYWORDS =
{'sql', 'lc_ctype', 'transform', 'failure', 'prepared', 'from', 'proxy', 'asensitive', 'named', 'delayed', 'warnings', 'disk', 'references', 'btree', 'locate', 'max_concurrency', 'profiles', 'trailing', 'arrange', 'from_base64', 'enum', 'nchar', 'cursor', 'validator', 'octet_length', 'smallint', 'timeout', 'aggregator_plan_hash', 'index', 'elseif', 'procedure', 'admin', 'case', 'approx_percentile', 'content', 'extractor', 'aes_encrypt', 'ssl', 'max_retries_per_batch_partition', 'label', 'following', 'geography_latitude', 'write', 'account', 'group', 'backup', 'called', 'mediumblob', 'roles', 'sql_mode', 'echo', 'location', 'time_to_sec', 'select', 'last_day', 'stable', 'var_samp', 'inherit', 'rand', '_global_version_timestamp', 'comments', 'replication', 'dense_rank', 'boolean', 'external_host', 'read', 'session', 'cache', 'procedural', 'bit_or', 'flush', 'license', 'host', 'engines', 'earliest', 'degrees', 'character_length', 'azure', 'quote', 'approx_count_distinct_accumulate', 'sec_to_time', 'explain', 'family', 'nvarchar', 'cross', 'mbc', 'convert_tz', 'conv', 'while', 'call_for_pipeline', 'analyse', 'is', 'long', 'upper', 'dayofweek', 'interval', 'day_microsecond', 'site', 'status', 'format', 'failed_login_attempts', 'else', 'pipelines', 'aes_decrypt', 'management', 'inline', 'varbinary', 'replica', 'escaped', 'byte', 'relative', 'sqrt', 'log', 'end', 'json_set_json', 'values', 'identity', 'wrapper', 'recursive', 'capture', 'to_timestamp', 'if', 'unique', 'bucket_count', 'rollback', 'partition_id', 'arghistory', 'autostats_histogram_mode', 'ordered_serialize', 'having', 'availability', 'auto_reprovision', 'voting', 'isnull', 'desc', 'instead', 'position', 's3', 'geography_within_distance', '_sync_snapshot', 'loop', 'recheck', 'curtime', '_sync2', 'template', 'sequence', 'unbounded', 'savepoint', 'row_count', 'signal', 'window', 'stdin', 'nothing', 'binary', '_sleep', 'json_get_type', 'partition', '_twopcid', 'weekofyear', 'noparam', 'fs', 'connection', 'placing', 'preserve', 'restrict', '_read', 'rename', 'force', 'median', 'aggregator_id', 'access', 'attribute', 'leave', 'tinyint', 'sql_calc_found_rows', 'date_trunc', 'int3', 'aggregates', 'bool', 'use', 'sha', 'do', 'acos', 'return', 'lock', 'backward', 'constraint', 'trusted', 'geographypoint', 'snapshot', 'exclude', 'encrypted', 'declare', 'member', 'optimizer_state', 'current_user', 'init', 'with', 'strip', 'percentile_disc', 'statement', 'minus', 'longblob', 'share', 'version', '_wake', 'as', 'nullif', 'schema_binding', 'log2', 'merge', 'range', 'autostats_enabled', 'ast', 'validate', 'hosts', 'exp', 'json_array_contains_string', 'online', 'leakproof', 'replicate', 'invoker', 'json_array_push_json', 'gc', '_utf8', 'commit', 'duplicate', 'extended', 'utc_timestamp', 'length', 'sql_small_result', 'real', '_internal_dynamic_typecast', '_unittest', 'geometrypoint', 'to', 'array', 'functions', 'substring_index', 'date_format', 'unhold', 'using', 'action', 'infile', 'unknown', '_core', 'current', 'minute', 'save', 'auto_increment', 'right_anti_join', 'pivot', 'purge', 'order', 'limit', 'cluster', 'pool', '_repl', 'plans', 'no_write_to_binlog', 'cnf', 'to_json', 'kafka', 'resource_pool', 'optionally', 'ceil', 'longtext', 'service_user', 'md5', 'check', 'pools', 'aggregators', 'outfile', 'any', 'mediumint', 'disable', '_repair_table', 'global', 'hour_minute', 'deferrable', 'second_microsecond', 'release', 'promote', 'alter', '_sync_partitions', 'current_time', 'columns', 'day_minute', 'owner', 'role', 'tan', 'cot', 'to_base64', 'connection_id', 'field', 'hour_microsecond', 'modifies', 'json_set_double', 'assignment', 'reverse', 'timestampadd', 'tables', 'scroll', 'gzip', 'ref', 'radians', 'now', 'fix_alter', 'sleep', '_gcx', 'asymmetric', 'restart', 'last_value', 'json_array_contains_double', '_bt', 'in', 'utc_date', 'xor', 'time_bucket', 'schema', 'autostats_sampling', 'date_add', 'replace', 'election', 'mpl', 'change', 'blob', 'current_security_groups', 'nowait', '_init_profile', 'last_insert_id', 'current_date', '_pause_replay', 'handler', 'cos', 'true', 'state', 'rollup', 'returning', 'norely', 'password_lock_time', 'bit_and', 'port', 'geometry_y', 'reindex', 'drop', 'persisted', 'event', 'assertion', 'rowstore', 'atan', 'cube', 'analyze', 'lateral', 'killall', 'min', 'background', 'terminate', 'dayofmonth', 'str_to_date', '_drop_profile', 'minvalue', 'repair', 'stop', 'and', 'collate', 'json_length', 'sysid', 'inner', '_ls', 'escape', 'at', 'offset', 'weekday', 'integer', 'geography_longitude', 'count', 'skipped_batches', 'except', 'users', 'prepare', 'strict', 'reload', 'percentile_cont', 'stdout', 'database', 'low_priority', 'text', 'sql_no_logging', 'statistics', 'both', 'extractors', 'month', 'off', 'quarter', 'key', 'current_catalog', 'sync_snapshot', 'remove', 'byte_length', 'lead', 'trigger', 'mediumtext', 'offline', 'latest', 'test', 'granted', 'timestamp', 'unenforced', 'fields', 'none', 'hold', 'unicode', 'deterministic', 'only', 'time', 'dot_product', 'enclosed', 'usage', 'instance', 'minute_microsecond', 'coercibility', 'gcs', 'json_splice_json', '_load', 'varchar', 'keys', 'temporary', 'geometry', 'simple', 'pow', 'stddev_samp', 'defaults', 'max', 'document', 'ln', 'whitespace', 'process', 'groups', 'json_extract_double', 'tracelogs', 'insert', 'between', 'definer', 'extra_join', '_check_can_connect', 'directory', 'has_temp_tables', 'intersect', 'substr', 'generate', 'revoke', 'update', 'estimate', 'system', 'first', 'view', 'from_unixtime', 'hex', 'without', 'dual', 'insensitive', 'always', 'compression', 'datediff', 'model', 'bin', 'resource', 'cume_dist', 'vector_sub', 'repeat', 'coalesce', 'json_extract_string', 'to_days', 'hard_cpu_limit_percentage', 'initialize', 'leading', 'distinctrow', 'year_month', 'traditional', 'by', 'concurrently', 'oids', 'inject', 'ascii', 'dynamic', 'natural', 'continue', 'subdate', 'bigint', 'engine', 'asm', 'cast', 'queue', 'out_of_order', 'level', 'maxvalue', 'high_priority', 'grants', 'microsecond', 'series', 'char_length', 'ceiling', 'force_interpreter_mode', '_wm_heartbeat', 'standalone', 'parser', 'header', 'local', 'geography_length', 'to_char', 'routine', 'config', 'inet_aton', 'redundant', 'sequences', 'exists', 'optimizer', 'similar', 'unhex', 'authorization', 'int1', 'floor', 'lcase', 'sql_big_result', 'variadic', 'volatile', 'chain', 'redundancy', 'or', 'close', 'left', 'incremental', 'aggregate', 'sql_cache', 'day_hour', 'durability', 'autostats', 'sync', 'current_schema', 'zone', 'max_queue_depth', 'rg_pool', 'join', 'remote', 'separator', 'float4', 'isolation', 'detach', 'months_between', 'bit_count', 'temp', 'within', 'set', 'sum', 'inherits', 'json_splice_double', 'primary', 'geography_contains', 'double', 'geometry_area', 'day_second', 'to_number', 'lower', '_unload', 'plugins', 'character', 'before', 'parquet', 'rank', 'sqlwarning', '_transactions_experimental', 'orphan', 'stats', 'unencrypted', 'mode', 'over', 'llvm', 'create', 'partitions', 'tinyblob', 'ltrim', 'row_number', '_rpc', 'memsql_serialize', '_check_consistency', 'iterate', 'add', 'sharded', 'attach', 'wait', 'workload', 'configuration', 'hour', 'batches', 'last', '_checksum', 'client', 'large', 'string', 'prior', 'extension', 'files', 'geometry_intersects', 'cost', 'synchronize', 'right_semi_join', 'json', '_snapshot', 'fetch', 'dayname', 'minute_second', 'lines', 'greatest', 'geometry_within_distance', 'unsigned', 'valid', 'zerofill', 'unlock', 'plan', 'sql_buffer_result', 'json_splice_string', 'second', 'plancache', 'batch_interval', 'column', 'max_rows', 'object', 'on', 'all', 'move', 'int2', 'reads', 'absolute', 'soname', 'semi_join', 'match', 'replicating', 'privileges', 'avg_row_length', 'unpivot', 'serializable', 'geometry_filter', 'no', 'two_phase', 'profile', 'require', 'bit_xor', 'connections', '_memsql_table_id_lookup', 'first_value', 'import', 'overlay', 'for', '_management_thread', 'highlight', 'spatial', 'bit', '_sync', 'skip', 'adddate', 'optimization', 'bootstrap', 'where', 'avg', 'client_found_rows', 'grouping', 'inet6_aton', 'unlisten', 'target_size', 'cycle', 'class', 'json_array_push_double', 'overlaps', 'json_array_contains_json', 'freeze', 'approx_count_distinct', 'checksum', 'char', 'metadata', 'like', 'dump', 'safe', 'foreground', 'operator', 'identified', 'holding', 'hdfs', 'ilike', '_binary', 'clustered', 'row', 'grant', 'query', 'vacuum', 'terminated', 'query_timeout', 'nth_value', 'reference', 'anti_join', 'ignore', 'arrangement', 'deallocate', 'handle', 'async', 'week', 'sharded_id', 'symmetric', 'key_block_size', 'asin', 'regexp', 'memsql', 'next', 'memory', 'middleint', 'catalog', 'listen', 'distinct', 'into', 'load', 'date', '_commit_log_tail', 'notify', 'sqlexception', 'describe', 'also', 'of', 'reassign', 'float8', 'columnar', 'get_format', 'data', 'xact_id', 'precision', 'against', 'rule', 'mapping', 'varying', 'interpreter_mode', 'default', 'until', 'file', 'lpad', 'credentials', 'mod', 'sensitive', 'out', 'addtime', 'hour_second', 'force_compiled_mode', 'checkpoint', 'null', 'day', 'geography_point', 'conversion', 'including', 'setof', 'json_array_push_string', 'function', 'names', 'work', 'geometry_contains', 'sparse', 'server', 'procedures', 'current_security_roles', 'cascaded', 'columnstore_segment_rows', 'geography', 'any_value', 'asc', 'compressed', 'immutable', 'triggers', 'json_agg', '_send_threads', 'lag', 'option', 'serial', 'databases', 'scalar', 'atan2', 'avro', 'concat', 'instr', 'dayofyear', 'localtime', 'no_query_rewrite', 'returns', '_term_bump', 'sin', 'value', 'auto', 'queries', 'json_extract_json', 'each', 'aggregator', 'group_concat', 'result', 'sign', 'backup_history', '_fsync', 'types', 'owned', 'geography_distance', 'stddev_pop', 'forward', 'shutdown', 'user', 'int4', 'timediff', 'kill', 'paired', 'div', 'delay_key_write', 'type', 'approx_count_distinct_combine', 'compact', 'fixed', 'memsql_deserialize', 'batch', 'verbose', 'decimal', 'full', 'condition', 'offsets', 'compile', 'soft_cpu_limit_percentage', 'substring', '_continue_replay', 'initially', 'curdate', 'elt', 'hash', 'max_partitions_per_batch', 'processlist', 'backup_id', 'some', 'master', 'password', 'undo', 'utc_time', 'fulltext', 'log10', 'options', '_disconnect', 'approx_count_distinct_estimate', 'columnstore', 'row_format', 'geometry_distance', 'treat', 'rely', 'external', 'concat_ws', 'variables', 'unlogged', 'collect', 'start', 'initcap', 'approx_geography_intersects', 'enable', 'pi', 'decode', 'geography_area', 'ucase', 'inout', '_background_threads_for_cleanup', 'convert', 'language', 'tinytext', 'outer', 'rlike', 'void', 'security_lists_intersect', 'algorithm', 'memory_percentage', 'unix_timestamp', 'record', 'call', 'differential', 'pipeline', 'concurrent', 'date_sub', 'inet_ntoa', '_gc', 'current_role', 'leaf', 'sql_no_cache', 'input', 'signed', 'partitioning', 'truncate', 'geometry_point', 'union', 'datetime', 'repeatable', 'task', 'autostats_cardinality_mode', 'leaves', 'comment', '_resurrect', 'fault', 'show', 'periodic', 'national', 'nulls', 'retry', 'open', 'int8', 'to_seconds', 'memsql_imitating_kafka', 'discard', 'time_format', 'encoding', 'copy', 'temptable', 'dec', 'namespace', 'super', 'distributed_joins', 'materialized', 'current_timestamp', 'std', 'sha2', 'insert_method', 'committed', 'restore', 'delete', 'rpad', 'storage', 'monthname', '_reprovisioning', 'euclidean_distance', 'undefined', 'rows', 'varcharacter', 'modify', 'variance', 'timezone', '_snapshots', 'stddev', 'ntile', '_batch_size_limit', 'errors', 'begin', 'excluding', 'geometry_length', 'indexes', 'ifnull', 'search', 'table', 'sqlstate', 'passing', 'after', 'numeric', 'sigmoid', 'foreign', 'then', 'starting', 'rtrim', 'optimize', 'upgrade', 'not', 'csv', 'program', 'running', 'specific', 'events', 'float', 'int', 'delimiter', 'sha1', 'defined', 'pack_keys', 'year', 'geometry_x', 'rebalance', 'clear', 'geography_intersects', 'partial', 'round', 'right_straight_join', 'inet6_ntoa', 'nullcols', 'spatial_check_index', 'success', 'to_date', 'localtimestamp', 'refresh', 'max_errors', 'split', 'implicit', 'cascade', 'least', 'uncommitted', 'right', 'increment', 'power', 'tags', 'charset', 'json_extract_bigint', 'preceding', 'json_delete_key', 'schemas', 'characteristics', 'delimiters', 'false', 'fill', 'session_user', 'domain', 'shard', 'trunc', 'external_port', 'lz4', 'when', 'yes', 'dictionary', 'security', 'exit', 'pause', 'percent_rank', 'var_pop', 'trim', 'from_days', 'collation', 'json_set_string', 'execute', 'exclusive', 'deferred', 'abs', 'heartbeat_no_logging', 'extract', 'lc_collate', 'tablespace', 'node', 'reset', 'timestampdiff', 'min_rows', '_failover', 'constraints', 'found_rows', 'loaddata_where', 'immediate', 'table_checksum', 'transaction', 'straight_join'}
1443 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 1444 if expression.args.get("on_condition"): 1445 self.unsupported("JSON_VALUE does not support on_condition") 1446 res: exp.Expr = exp.JSONExtractScalar( 1447 this=expression.this, 1448 expression=expression.args.get("path"), 1449 json_type="STRING", 1450 ) 1451 1452 returning = expression.args.get("returning") 1453 if returning is not None: 1454 res = exp.Cast(this=res, to=returning) 1455 1456 return self.sql(res)
1458 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 1459 # SingleStore includes trailing NULLs in percentile calculations, so we sort them first 1460 if isinstance(expression.this, (exp.PercentileCont, exp.PercentileDisc)) and isinstance( 1461 expression.expression, exp.Order 1462 ): 1463 expression = expression.copy() 1464 for ordered in expression.expression.expressions: 1465 ordered.set("nulls_first", True) 1466 1467 return super().withingroup_sql(expression)
1473 def jsonarraycontains_sql(self, expression: exp.JSONArrayContains) -> str: 1474 json_type = expression.text("json_type").upper() 1475 1476 if json_type: 1477 return self.func( 1478 f"JSON_ARRAY_CONTAINS_{json_type}", expression.expression, expression.this 1479 ) 1480 1481 return self.func( 1482 "JSON_ARRAY_CONTAINS_JSON", 1483 expression.expression, 1484 self.func("TO_JSON", expression.this), 1485 )
1487 def datatype_sql(self, expression: exp.DataType) -> str: 1488 for arg_name in ("kind", "values"): 1489 if expression.args.get(arg_name): 1490 self.unsupported(f"DATATYPE does not support {arg_name}") 1491 if expression.args.get("nested") and not expression.is_type(exp.DType.STRUCT): 1492 self.unsupported( 1493 f"Argument 'nested' is not supported for representation of '{expression.this.value}' in SingleStore" 1494 ) 1495 1496 if expression.is_type(exp.DType.VARBINARY) and not expression.expressions: 1497 # `VARBINARY` must always have a size - if it doesn't, we always generate `BLOB` 1498 return "BLOB" 1499 if expression.is_type( 1500 exp.DType.DECIMAL32, 1501 exp.DType.DECIMAL64, 1502 exp.DType.DECIMAL128, 1503 exp.DType.DECIMAL256, 1504 ): 1505 scale = self.expressions(expression, flat=True) 1506 1507 if expression.is_type(exp.DType.DECIMAL32): 1508 precision = "9" 1509 elif expression.is_type(exp.DType.DECIMAL64): 1510 precision = "18" 1511 elif expression.is_type(exp.DType.DECIMAL128): 1512 precision = "38" 1513 else: 1514 # 65 is a maximum precision supported in SingleStore 1515 precision = "65" 1516 if scale is not None: 1517 return f"DECIMAL({precision}, {scale[0]})" 1518 else: 1519 return f"DECIMAL({precision})" 1520 if expression.is_type(exp.DType.VECTOR): 1521 expressions = expression.expressions 1522 if len(expressions) == 2: 1523 type_name = self.sql(expressions[0]) 1524 if type_name in self.dialect.INVERSE_VECTOR_TYPE_ALIASES: 1525 type_name = self.dialect.INVERSE_VECTOR_TYPE_ALIASES[type_name] 1526 1527 return f"VECTOR({self.sql(expressions[1])}, {type_name})" 1528 1529 return super().datatype_sql(expression)
1531 def collate_sql(self, expression: exp.Collate) -> str: 1532 # SingleStore does not support setting a collation for column in the SELECT query, 1533 # so we cast column to a LONGTEXT type with specific collation. If the cast is 1534 # already there (e.g. when regenerating previously generated SQL), don't add 1535 # another one, so that generation stays idempotent. 1536 this = expression.this 1537 if isinstance(this, exp.Cast) and this.to.this == exp.DType.LONGTEXT: 1538 return self.binary(expression, "COLLATE") 1539 return self.binary(expression, ":> LONGTEXT COLLATE")
1541 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 1542 timezone = expression.this 1543 if timezone: 1544 if isinstance(timezone, exp.Literal) and timezone.name.lower() == "utc": 1545 return self.func("UTC_DATE") 1546 self.unsupported("CurrentDate with timezone is not supported in SingleStore") 1547 1548 return self.func("CURRENT_DATE")
1550 def currenttime_sql(self, expression: exp.CurrentTime) -> str: 1551 arg = expression.this 1552 if arg: 1553 if isinstance(arg, exp.Literal) and arg.name.lower() == "utc": 1554 return self.func("UTC_TIME") 1555 if isinstance(arg, exp.Literal) and arg.is_number: 1556 return self.func("CURRENT_TIME", arg) 1557 self.unsupported("CurrentTime with timezone is not supported in SingleStore") 1558 1559 return self.func("CURRENT_TIME")
1561 def currenttimestamp_sql(self, expression: exp.CurrentTimestamp) -> str: 1562 arg = expression.this 1563 if arg: 1564 if isinstance(arg, exp.Literal) and arg.name.lower() == "utc": 1565 return self.func("UTC_TIMESTAMP") 1566 if isinstance(arg, exp.Literal) and arg.is_number: 1567 return self.func("CURRENT_TIMESTAMP", arg) 1568 self.unsupported("CurrentTimestamp with timezone is not supported in SingleStore") 1569 1570 return self.func("CURRENT_TIMESTAMP")
1572 def standardhash_sql(self, expression: exp.StandardHash) -> str: 1573 hash_function = expression.expression 1574 if hash_function is None: 1575 return self.func("SHA", expression.this) 1576 if isinstance(hash_function, exp.Literal): 1577 if hash_function.name.lower() == "sha": 1578 return self.func("SHA", expression.this) 1579 if hash_function.name.lower() == "md5": 1580 return self.func("MD5", expression.this) 1581 1582 self.unsupported(f"{hash_function.this} hash method is not supported in SingleStore") 1583 return self.func("SHA", expression.this) 1584 1585 self.unsupported("STANDARD_HASH function is not supported in SingleStore") 1586 return self.func("SHA", expression.this)
1588 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 1589 for arg_name in ("is_database", "exists", "cluster", "identity", "option", "partition"): 1590 if expression.args.get(arg_name): 1591 self.unsupported(f"TRUNCATE TABLE does not support {arg_name}") 1592 statements = [] 1593 for table in expression.expressions: 1594 statements.append(f"TRUNCATE {self.sql(table)}") 1595 1596 return "; ".join(statements)
1598 def renamecolumn_sql(self, expression: exp.RenameColumn) -> str: 1599 if expression.args.get("exists"): 1600 self.unsupported("RENAME COLUMN does not support exists") 1601 old_column = self.sql(expression, "this") 1602 new_column = self.sql(expression, "to") 1603 return f"CHANGE {old_column} {new_column}"
1605 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 1606 for arg_name in ("drop", "comment", "visible", "using"): 1607 if expression.args.get(arg_name): 1608 self.unsupported(f"ALTER COLUMN does not support {arg_name}") 1609 alter = super().altercolumn_sql(expression) 1610 1611 collate = self.sql(expression, "collate") 1612 collate = f" COLLATE {collate}" if collate else "" 1613 return f"{alter}{collate}"
def
computedcolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.ComputedColumnConstraint) -> str:
1615 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 1616 this = self.sql(expression, "this") 1617 not_null = " NOT NULL" if expression.args.get("not_null") else "" 1618 type = self.sql(expression, "data_type") or "AUTO" 1619 return f"AS {this} PERSISTED {type}{not_null}"
Inherited Members
- sqlglot.generator.Generator
- Generator
- WINDOW_FUNCS_WITH_NULL_ORDERING
- IGNORE_NULLS_IN_FUNC
- IGNORE_NULLS_BEFORE_ORDER
- EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
- CREATE_FUNCTION_RETURN_AS
- MATCHED_BY_SOURCE
- SUPPORTS_MERGE_WHERE
- SINGLE_STRING_INTERVAL
- AUTO_REFRESH_BARE_INTERVALS
- RENAME_TABLE_WITH_DB
- GROUPINGS_SEP
- SUPPORTS_GROUPING_SETS_AS_SUFFIX
- INDEX_ON
- INOUT_SEPARATOR
- DIRECTED_JOINS
- QUERY_HINTS
- IS_BOOL_ALLOWED
- LIMIT_IS_TOP
- RETURNING_END
- EXTRACT_ALLOWS_QUOTES
- TZ_TO_WITH_TIME_ZONE
- ALTER_TABLE_INCLUDE_COLUMN_KEYWORD
- UNNEST_WITH_ORDINALITY
- SEMI_ANTI_JOIN_WITH_SIDE
- COMPUTED_COLUMN_WITH_TYPE
- SUPPORTS_TABLE_COPY
- TABLESAMPLE_REQUIRES_PARENS
- TABLESAMPLE_SIZE_IS_ROWS
- TABLESAMPLE_KEYWORDS
- 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
- INSERT_OVERWRITE
- SUPPORTS_SELECT_INTO
- SUPPORTS_UNLOGGED_TABLES
- SUPPORTS_CREATE_TABLE_LIKE
- SUPPORTS_ALTER_COLUMN_IF_EXISTS
- LIKE_PROPERTY_INSIDE_SCHEMA
- MULTI_ARG_DISTINCT
- JSON_PATH_SINGLE_QUOTE_ESCAPE
- JSON_PATH_KEY_QUOTED_FORCES_BRACKETS
- CAN_IMPLEMENT_ARRAY_ANY
- SUPPORTS_WINDOW_EXCLUDE
- SET_OP_MODIFIERS
- SET_OP_LIMITS
- SET_OP_PARENTHESIZED_OPERANDS
- COPY_PARAMS_ARE_WRAPPED
- COPY_PARAMS_EQ_REQUIRED
- COPY_HAS_INTO_KEYWORD
- STAR_EXCEPT
- HEX_FUNC
- WITH_PROPERTIES_PREFIX
- QUOTE_JSON_PATH
- SUPPORTS_EXPLODING_PROJECTIONS
- ARRAY_CONCAT_IS_VAR_LEN
- SUPPORTS_CONVERT_TIMEZONE
- SUPPORTS_UNIX_SECONDS
- ALTER_SET_WRAPPED
- NORMALIZE_EXTRACT_DATE_PARTS
- ARRAY_SIZE_NAME
- ALTER_SET_TYPE
- ARRAY_SIZE_DIM_REQUIRED
- SUPPORTS_BETWEEN_FLAGS
- SUPPORTS_LIKE_QUANTIFIERS
- SET_ASSIGNMENT_REQUIRES_VARIABLE_KEYWORD
- DECLARE_DEFAULT_ASSIGNMENT
- STAR_EXCLUDE_REQUIRES_DERIVED_TABLE
- SUPPORTS_DROP_ALTER_ICEBERG_PROPERTY
- TIME_PART_SINGULARS
- TOKEN_MAPPING
- PARAMETER_TOKEN
- NAMED_PLACEHOLDER_TOKEN
- EXPRESSION_PRECEDES_PROPERTIES_CREATABLES
- 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
- 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
- autoincrementcolumnconstraint_sql
- compresscolumnconstraint_sql
- generatedasidentitycolumnconstraint_sql
- generatedasrowcolumnconstraint_sql
- periodforsystemtimeconstraint_sql
- notnullcolumnconstraint_sql
- primarykeycolumnconstraint_sql
- uniquecolumnconstraint_sql
- inoutcolumnconstraint_sql
- createable_sql
- create_sql
- sequenceproperties_sql
- triggerproperties_sql
- triggerreferencing_sql
- triggerevent_sql
- clone_sql
- describe_sql
- heredoc_sql
- prepend_ctes
- with_sql
- cte_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
- property_name
- property_sql
- uuidproperty_sql
- likeproperty_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
- 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
- values_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
- offset_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
- after_limit_modifiers
- select_sql
- schema_sql
- schema_columns_sql
- star_sql
- parameter_sql
- sessionparameter_sql
- placeholder_sql
- subquery_sql
- qualify_sql
- unnest_sql
- prewhere_sql
- where_sql
- window_sql
- partition_by_sql
- windowspec_sql
- between_sql
- bracket_offset_expressions
- bracket_sql
- any_sql
- exists_sql
- case_sql
- constraint_sql
- nextvaluefor_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_sql
- in_unnest_op
- interval_sql
- return_sql
- reference_sql
- anonymous_sql
- paren_sql
- neg_sql
- not_sql
- alias_sql
- pivotalias_sql
- aliases_sql
- atindex_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
- strtodate_sql
- parsedatetime_sql
- command_sql
- comment_sql
- mergetreettlaction_sql
- mergetreettl_sql
- transaction_sql
- commit_sql
- rollback_sql
- modifycolumn_sql
- alterindex_sql
- alterdiststyle_sql
- altersortkey_sql
- alterset_sql
- alter_sql
- altersession_sql
- add_column_sql
- droppartition_sql
- dropprimarykey_sql
- addconstraint_sql
- addpartition_sql
- distinct_sql
- respectnulls_sql
- havingmax_sql
- intdiv_sql
- div_sql
- safedivide_sql
- overlaps_sql
- distance_sql
- distancend_sql
- dot_sql
- eq_sql
- propertyeq_sql
- escape_sql
- glob_sql
- gt_sql
- gte_sql
- is_sql
- like_sql
- ilike_sql
- match_sql
- similarto_sql
- lt_sql
- lte_sql
- mod_sql
- mul_sql
- neq_sql
- nullsafeeq_sql
- nullsafeneq_sql
- sub_sql
- trycast_sql
- jsoncast_sql
- try_sql
- log_sql
- use_sql
- binary
- ceil_floor
- function_fallback_sql
- 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
- duplicatekeyproperty_sql
- uniquekeyproperty_sql
- distributedbyproperty_sql
- oncluster_sql
- clusteredbyproperty_sql
- anyvalue_sql
- querytransform_sql
- indexconstraintoption_sql
- checkcolumnconstraint_sql
- indexcolumnconstraint_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
- 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
- json_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
- arraysize_sql
- attach_sql
- detach_sql
- attachoption_sql
- watermarkcolumnconstraint_sql
- encodeproperty_sql
- includeproperty_sql
- xmlelement_sql
- xmlkeyvalueoption_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
- install_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
- 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
- sqlglot.generators.mysql.MySQLGenerator
- SELECT_KINDS
- TRY_SUPPORTED
- SUPPORTS_DECODE_CASE
- SUPPORTS_MODIFY_COLUMN
- SUPPORTS_CHANGE_COLUMN
- AFTER_HAVING_MODIFIER_TRANSFORMS
- INTERVAL_ALLOWS_PLURAL_FORM
- LOCKING_READS_SUPPORTED
- JOIN_HINTS
- TABLE_HINTS
- DUPLICATE_KEY_UPDATE_WITH_SET
- QUERY_HINT_SEP
- VALUES_AS_TABLE
- NVL2_SUPPORTED
- LAST_DAY_SUPPORTS_DATE_PART
- JSON_TYPE_REQUIRED_FOR_EXTRACTION
- JSON_PATH_BRACKETED_KEY_SUPPORTED
- JSON_KEY_VALUE_PAIR_SEP
- SUPPORTS_TO_NUMBER
- PARSE_JSON_NAME
- PAD_FILL_PATTERN_IS_REQUIRED
- WRAP_DERIVED_VALUES
- VARCHAR_REQUIRES_SIZE
- SUPPORTS_MEDIAN
- UPDATE_STATEMENT_SUPPORTS_FROM
- UNSIGNED_TYPE_MAPPING
- TIMESTAMP_TYPE_MAPPING
- PROPERTIES_LOCATION
- LIMIT_FETCH
- LIMIT_ONLY_LITERALS
- CHAR_CAST_MAPPING
- SIGNED_CAST_MAPPING
- CAST_MAPPING
- TIMESTAMP_FUNC_TYPES
- SQL_SECURITY_VIEW_LOCATION
- makeinterval_sql
- locate_properties
- array_sql
- arraycontainsall_sql
- arraycontainedby_sql
- dpipe_sql
- extract_sql
- cast_sql
- show_sql
- alterrename_sql
- timestamptrunc_sql
- converttimezone_sql
- attimezone_sql
- isascii_sql
- ignorenulls_sql
- currentschema_sql
- partition_sql
- partitionbyrangeproperty_sql
- partitionbylistproperty_sql
- partitionlist_sql
- partitionrange_sql