Edit on GitHub

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