Edit on GitHub

sqlglot.generators.mysql

  1from __future__ import annotations
  2
  3import typing as t
  4
  5from sqlglot import exp, generator, transforms
  6from sqlglot.dialects.dialect import (
  7    arrow_json_extract_sql,
  8    build_date_delta,
  9    build_date_delta_with_interval,
 10    date_add_interval_sql,
 11    datestrtodate_sql,
 12    length_or_char_length_sql,
 13    max_or_greatest,
 14    min_or_least,
 15    no_ilike_sql,
 16    no_paren_current_date_sql,
 17    no_pivot_sql,
 18    no_tablesample_sql,
 19    no_trycast_sql,
 20    if_sql,
 21    remove_ts_or_ds_to_date,
 22    rename_func,
 23    strposition_sql,
 24    unit_to_var,
 25    trim_sql,
 26    timestrtotime_sql,
 27)
 28from sqlglot.generator import unsupported_args
 29from collections import defaultdict
 30
 31
 32def _date_trunc_sql(self: MySQLGenerator, expression: exp.DateTrunc) -> str:
 33    expr = self.sql(expression, "this")
 34    unit_expr = expression.args.get("unit")
 35    unit = (
 36        self.weekstart_name(unit_expr)
 37        if isinstance(unit_expr, exp.WeekStart)
 38        else expression.text("unit").upper()
 39    )
 40
 41    if unit == "WEEK":
 42        concat = f"CONCAT(YEAR({expr}), ' ', WEEK({expr}, 1), ' 1')"
 43        date_format = "%Y %u %w"
 44    elif unit == "MONTH":
 45        concat = f"CONCAT(YEAR({expr}), ' ', MONTH({expr}), ' 1')"
 46        date_format = "%Y %c %e"
 47    elif unit == "QUARTER":
 48        concat = f"CONCAT(YEAR({expr}), ' ', QUARTER({expr}) * 3 - 2, ' 1')"
 49        date_format = "%Y %c %e"
 50    elif unit == "YEAR":
 51        concat = f"CONCAT(YEAR({expr}), ' 1 1')"
 52        date_format = "%Y %c %e"
 53    else:
 54        if unit != "DAY":
 55            self.unsupported(f"Unexpected interval unit: {unit}")
 56        return self.func("DATE", expr)
 57
 58    return self.func("STR_TO_DATE", concat, f"'{date_format}'")
 59
 60
 61def _str_to_date_sql(
 62    self: MySQLGenerator, expression: exp.StrToDate | exp.StrToTime | exp.TsOrDsToDate
 63) -> str:
 64    return self.func("STR_TO_DATE", expression.this, self.format_time(expression))
 65
 66
 67def _unix_to_time_sql(self: MySQLGenerator, expression: exp.UnixToTime) -> str:
 68    scale = expression.args.get("scale")
 69    timestamp = expression.this
 70
 71    if scale in (None, exp.UnixToTime.SECONDS):
 72        return self.func("FROM_UNIXTIME", timestamp, self.format_time(expression))
 73
 74    return self.func(
 75        "FROM_UNIXTIME",
 76        exp.Div(this=timestamp, expression=exp.func("POW", 10, scale)),
 77        self.format_time(expression),
 78    )
 79
 80
 81def date_add_sql(
 82    kind: str,
 83) -> t.Callable[[generator.Generator, exp.Expr], str]:
 84    def func(self: generator.Generator, expression: exp.Expr) -> str:
 85        return self.func(
 86            f"DATE_{kind}",
 87            expression.this,
 88            exp.Interval(this=expression.expression, unit=unit_to_var(expression)),
 89        )
 90
 91    return func
 92
 93
 94_MAKE_INTERVAL_UNIT_ALIASES = {
 95    "years": "year",
 96    "months": "month",
 97    "weeks": "week",
 98    "days": "day",
 99    "hours": "hour",
100    "minutes": "minute",
101    "mins": "minute",
102    "seconds": "second",
103    "secs": "second",
104}
105
106
107def _ts_or_ds_to_date_sql(self: MySQLGenerator, expression: exp.TsOrDsToDate) -> str:
108    time_format = expression.args.get("format")
109    return _str_to_date_sql(self, expression) if time_format else self.func("DATE", expression.this)
110
111
112class MySQLGenerator(generator.Generator):
113    DAYOFWEEK_NAME = "DAYOFWEEK"
114    BYTE_STRING_FUNCTION = "UNHEX"
115    VARIANCE_NAME = "VAR_SAMP"
116    SELECT_KINDS = ()
117    TRY_SUPPORTED = False
118    SUPPORTS_UESCAPE = False
119    SUPPORTS_DECODE_CASE = False
120    SUPPORTS_MODIFY_COLUMN = True
121    SUPPORTS_CHANGE_COLUMN = True
122    SUPPORTS_ALTER_COLUMN_NULLABILITY = True
123
124    AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS
125
126    INTERVAL_ALLOWS_PLURAL_FORM = False
127    LOCKING_READS_SUPPORTED = True
128    CAST_TO_INT_ROUNDS = True
129    INT_DIV_OPERATOR: str | None = "DIV"
130    NULL_ORDERING_SUPPORTED: bool | None = None
131    JOIN_HINTS = False
132    TABLE_HINTS = True
133    DUPLICATE_KEY_UPDATE_WITH_SET = False
134    QUERY_HINT_SEP = " "
135    VALUES_AS_TABLE = False
136    NVL2_SUPPORTED = False
137    LAST_DAY_SUPPORTS_DATE_PART = False
138    JSON_TYPE_REQUIRED_FOR_EXTRACTION = True
139    JSON_PATH_BRACKETED_KEY_SUPPORTED = False
140    JSON_KEY_VALUE_PAIR_SEP = ","
141    SUPPORTS_TO_NUMBER = False
142    PARSE_JSON_NAME: str | None = None
143    PAD_FILL_PATTERN_IS_REQUIRED = True
144    WRAP_DERIVED_VALUES = False
145    VARCHAR_REQUIRES_SIZE = True
146    SUPPORTS_MEDIAN = False
147    UPDATE_STATEMENT_SUPPORTS_FROM = False
148
149    ALTER_PARTITION_OPTIONS: t.ClassVar[tuple[type[exp.Expr], ...]] = (
150        exp.PartitionByListProperty,
151        exp.PartitionByRangeProperty,
152    )
153
154    TRANSFORMS = {
155        # The base Postgres-style array operators (@>, <@) don't exist in MySQL, so drop
156        # them to let arraycontainsall_sql / arraycontainedby_sql flag them as unsupported
157        **{
158            k: v
159            for k, v in generator.Generator.TRANSFORMS.items()
160            if k not in {exp.ArrayContainsAll, exp.ArrayContainedBy}
161        },
162        exp.ArrayAgg: rename_func("GROUP_CONCAT"),
163        exp.BitwiseAndAgg: rename_func("BIT_AND"),
164        exp.BitwiseOrAgg: rename_func("BIT_OR"),
165        exp.BitwiseXorAgg: rename_func("BIT_XOR"),
166        exp.BitwiseCount: rename_func("BIT_COUNT"),
167        exp.Chr: lambda self, e: self.chr_sql(e, "CHAR"),
168        exp.CurrentDate: no_paren_current_date_sql,
169        exp.CurrentVersion: rename_func("VERSION"),
170        exp.DateDiff: remove_ts_or_ds_to_date(
171            lambda self, e: self.func("DATEDIFF", e.this, e.expression), ("this", "expression")
172        ),
173        exp.DateAdd: date_add_sql("ADD"),
174        exp.DateStrToDate: datestrtodate_sql,
175        exp.DateSub: date_add_sql("SUB"),
176        exp.DateTrunc: _date_trunc_sql,
177        exp.Day: remove_ts_or_ds_to_date(),
178        exp.DayOfMonth: remove_ts_or_ds_to_date(rename_func("DAYOFMONTH")),
179        exp.DayOfWeek: remove_ts_or_ds_to_date(generator.Generator.dayofweek_sql),
180        exp.DayOfYear: remove_ts_or_ds_to_date(rename_func("DAYOFYEAR")),
181        exp.GroupConcat: lambda self, e: (
182            f"""GROUP_CONCAT({self.sql(e, "this")} SEPARATOR {self.sql(e, "separator") or "','"})"""
183        ),
184        exp.ILike: no_ilike_sql,
185        # https://dev.mysql.com/doc/refman/9.7/en/flow-control-functions.html#function_if
186        exp.If: if_sql(false_value="NULL"),
187        exp.JSONExtractScalar: arrow_json_extract_sql,
188        exp.Length: length_or_char_length_sql,
189        exp.LogicalOr: rename_func("MAX"),
190        exp.LogicalAnd: rename_func("MIN"),
191        exp.Max: max_or_greatest,
192        exp.Min: min_or_least,
193        exp.Month: remove_ts_or_ds_to_date(),
194        exp.NullSafeEQ: lambda self, e: self.binary(e, "<=>"),
195        exp.NullSafeNEQ: lambda self, e: f"NOT {self.binary(e, '<=>')}",
196        exp.NumberToStr: rename_func("FORMAT"),
197        exp.Pivot: no_pivot_sql,
198        exp.Select: transforms.preprocess(
199            [
200                transforms.eliminate_distinct_on,
201                transforms.eliminate_semi_and_anti_joins,
202                transforms.eliminate_qualify,
203                transforms.eliminate_full_outer_join,
204                transforms.unnest_generate_date_array_using_recursive_cte,
205            ]
206        ),
207        exp.Stddev: rename_func("STDDEV_SAMP"),
208        exp.StrPosition: lambda self, e: strposition_sql(
209            self, e, func_name="LOCATE", supports_position=True
210        ),
211        exp.StrToDate: _str_to_date_sql,
212        exp.StrToTime: _str_to_date_sql,
213        exp.Stuff: rename_func("INSERT"),
214        exp.SessionUser: lambda *_: "SESSION_USER()",
215        exp.TableSample: no_tablesample_sql,
216        exp.TimeFromParts: rename_func("MAKETIME"),
217        exp.TimestampAdd: date_add_interval_sql("DATE", "ADD"),
218        exp.TimestampDiff: lambda self, e: self.func(
219            "TIMESTAMPDIFF", unit_to_var(e), e.expression, e.this
220        ),
221        exp.TimestampSub: date_add_interval_sql("DATE", "SUB"),
222        exp.TimeStrToUnix: rename_func("UNIX_TIMESTAMP"),
223        exp.TimeStrToTime: lambda self, e: timestrtotime_sql(
224            self,
225            e,
226            include_precision=not e.args.get("zone"),
227        ),
228        exp.TimeToStr: remove_ts_or_ds_to_date(
229            lambda self, e: self.func("DATE_FORMAT", e.this, self.format_time(e))
230        ),
231        exp.Trim: trim_sql,
232        exp.Trunc: lambda self, e: self.func(
233            "TRUNCATE", e.this, e.args.get("decimals") or exp.Literal.number(0)
234        ),
235        exp.TryCast: no_trycast_sql,
236        exp.TsOrDsAdd: date_add_sql("ADD"),
237        exp.TsOrDsDiff: lambda self, e: self.func("DATEDIFF", e.this, e.expression),
238        exp.TsOrDsToDate: _ts_or_ds_to_date_sql,
239        exp.Unicode: lambda self, e: f"ORD(CONVERT({self.sql(e.this)} USING utf32))",
240        exp.UnixToTime: _unix_to_time_sql,
241        exp.VariancePop: rename_func("VAR_POP"),
242        exp.Week: remove_ts_or_ds_to_date(),
243        exp.WeekOfYear: remove_ts_or_ds_to_date(rename_func("WEEKOFYEAR")),
244        exp.Year: remove_ts_or_ds_to_date(),
245        exp.UtcTimestamp: rename_func("UTC_TIMESTAMP"),
246        exp.UtcTime: rename_func("UTC_TIME"),
247    }
248
249    UNSIGNED_TYPE_MAPPING: t.ClassVar = {
250        exp.DType.UBIGINT: "BIGINT",
251        exp.DType.UINT: "INT",
252        exp.DType.UMEDIUMINT: "MEDIUMINT",
253        exp.DType.USMALLINT: "SMALLINT",
254        exp.DType.UTINYINT: "TINYINT",
255        exp.DType.UDECIMAL: "DECIMAL",
256        exp.DType.UDOUBLE: "DOUBLE",
257    }
258
259    TIMESTAMP_TYPE_MAPPING: t.ClassVar = {
260        exp.DType.DATETIME2: "DATETIME",
261        exp.DType.SMALLDATETIME: "DATETIME",
262        exp.DType.TIMESTAMP: "DATETIME",
263        exp.DType.TIMESTAMPNTZ: "DATETIME",
264        exp.DType.TIMESTAMPTZ: "TIMESTAMP",
265        exp.DType.TIMESTAMPLTZ: "TIMESTAMP",
266    }
267
268    TYPE_MAPPING: t.ClassVar = {
269        exp.DType.NCHAR: "CHAR",
270        exp.DType.NVARCHAR: "VARCHAR",
271        exp.DType.INET: "INET",
272        exp.DType.ROWVERSION: "VARBINARY",
273        exp.DType.UBIGINT: "BIGINT",
274        exp.DType.UINT: "INT",
275        exp.DType.UMEDIUMINT: "MEDIUMINT",
276        exp.DType.USMALLINT: "SMALLINT",
277        exp.DType.UTINYINT: "TINYINT",
278        exp.DType.UDECIMAL: "DECIMAL",
279        exp.DType.UDOUBLE: "DOUBLE",
280        exp.DType.DATETIME2: "DATETIME",
281        exp.DType.SMALLDATETIME: "DATETIME",
282        exp.DType.TIMESTAMP: "DATETIME",
283        exp.DType.TIMESTAMPNTZ: "DATETIME",
284        exp.DType.TIMESTAMPTZ: "TIMESTAMP",
285        exp.DType.TIMESTAMPLTZ: "TIMESTAMP",
286    }
287
288    PROPERTIES_LOCATION: t.ClassVar = {
289        **generator.Generator.PROPERTIES_LOCATION,
290        exp.TransientProperty: exp.Properties.Location.UNSUPPORTED,
291        exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
292        exp.PartitionedByProperty: exp.Properties.Location.UNSUPPORTED,
293        exp.PartitionByRangeProperty: exp.Properties.Location.POST_SCHEMA,
294        exp.PartitionByListProperty: exp.Properties.Location.POST_SCHEMA,
295        exp.Property: exp.Properties.Location.POST_SCHEMA,
296    }
297
298    LIMIT_FETCH = "LIMIT"
299
300    LIMIT_ONLY_LITERALS = True
301
302    CHAR_CAST_MAPPING: t.ClassVar = dict.fromkeys(
303        (
304            exp.DType.LONGTEXT,
305            exp.DType.LONGBLOB,
306            exp.DType.MEDIUMBLOB,
307            exp.DType.MEDIUMTEXT,
308            exp.DType.TEXT,
309            exp.DType.TINYBLOB,
310            exp.DType.TINYTEXT,
311            exp.DType.VARCHAR,
312        ),
313        "CHAR",
314    )
315    SIGNED_CAST_MAPPING: t.ClassVar = dict.fromkeys(
316        (
317            exp.DType.BIGINT,
318            exp.DType.BOOLEAN,
319            exp.DType.INT,
320            exp.DType.SMALLINT,
321            exp.DType.TINYINT,
322            exp.DType.MEDIUMINT,
323        ),
324        "SIGNED",
325    )
326
327    # MySQL doesn't support many datatypes in cast.
328    # https://dev.mysql.com/doc/refman/8.0/en/cast-functions.html#function_cast
329    CAST_MAPPING: t.ClassVar = {
330        exp.DType.LONGTEXT: "CHAR",
331        exp.DType.LONGBLOB: "CHAR",
332        exp.DType.MEDIUMBLOB: "CHAR",
333        exp.DType.MEDIUMTEXT: "CHAR",
334        exp.DType.TEXT: "CHAR",
335        exp.DType.TINYBLOB: "CHAR",
336        exp.DType.TINYTEXT: "CHAR",
337        exp.DType.VARCHAR: "CHAR",
338        exp.DType.BIGINT: "SIGNED",
339        exp.DType.BOOLEAN: "SIGNED",
340        exp.DType.INT: "SIGNED",
341        exp.DType.SMALLINT: "SIGNED",
342        exp.DType.TINYINT: "SIGNED",
343        exp.DType.MEDIUMINT: "SIGNED",
344        exp.DType.UBIGINT: "UNSIGNED",
345    }
346
347    TIMESTAMP_FUNC_TYPES: t.ClassVar = {
348        exp.DType.TIMESTAMPTZ,
349        exp.DType.TIMESTAMPLTZ,
350    }
351
352    # https://dev.mysql.com/doc/refman/8.0/en/keywords.html
353    RESERVED_KEYWORDS = {
354        "accessible",
355        "add",
356        "all",
357        "alter",
358        "analyze",
359        "and",
360        "as",
361        "asc",
362        "asensitive",
363        "before",
364        "between",
365        "bigint",
366        "binary",
367        "blob",
368        "both",
369        "by",
370        "call",
371        "cascade",
372        "case",
373        "change",
374        "char",
375        "character",
376        "check",
377        "collate",
378        "column",
379        "condition",
380        "constraint",
381        "continue",
382        "convert",
383        "create",
384        "cross",
385        "cube",
386        "cume_dist",
387        "current_date",
388        "current_time",
389        "current_timestamp",
390        "current_user",
391        "cursor",
392        "database",
393        "databases",
394        "day_hour",
395        "day_microsecond",
396        "day_minute",
397        "day_second",
398        "dec",
399        "decimal",
400        "declare",
401        "default",
402        "delayed",
403        "delete",
404        "dense_rank",
405        "desc",
406        "describe",
407        "deterministic",
408        "distinct",
409        "distinctrow",
410        "div",
411        "double",
412        "drop",
413        "dual",
414        "each",
415        "else",
416        "elseif",
417        "empty",
418        "enclosed",
419        "escaped",
420        "except",
421        "exists",
422        "exit",
423        "explain",
424        "false",
425        "fetch",
426        "first_value",
427        "float",
428        "float4",
429        "float8",
430        "for",
431        "force",
432        "foreign",
433        "from",
434        "fulltext",
435        "function",
436        "generated",
437        "get",
438        "grant",
439        "group",
440        "grouping",
441        "groups",
442        "having",
443        "high_priority",
444        "hour_microsecond",
445        "hour_minute",
446        "hour_second",
447        "if",
448        "ignore",
449        "in",
450        "index",
451        "infile",
452        "inner",
453        "inout",
454        "insensitive",
455        "insert",
456        "int",
457        "int1",
458        "int2",
459        "int3",
460        "int4",
461        "int8",
462        "integer",
463        "intersect",
464        "interval",
465        "into",
466        "io_after_gtids",
467        "io_before_gtids",
468        "is",
469        "iterate",
470        "join",
471        "json_table",
472        "key",
473        "keys",
474        "kill",
475        "lag",
476        "last_value",
477        "lateral",
478        "lead",
479        "leading",
480        "leave",
481        "left",
482        "like",
483        "limit",
484        "linear",
485        "lines",
486        "load",
487        "localtime",
488        "localtimestamp",
489        "lock",
490        "long",
491        "longblob",
492        "longtext",
493        "loop",
494        "low_priority",
495        "master_bind",
496        "master_ssl_verify_server_cert",
497        "match",
498        "maxvalue",
499        "mediumblob",
500        "mediumint",
501        "mediumtext",
502        "middleint",
503        "minute_microsecond",
504        "minute_second",
505        "mod",
506        "modifies",
507        "natural",
508        "not",
509        "no_write_to_binlog",
510        "nth_value",
511        "ntile",
512        "null",
513        "numeric",
514        "of",
515        "on",
516        "optimize",
517        "optimizer_costs",
518        "option",
519        "optionally",
520        "or",
521        "order",
522        "out",
523        "outer",
524        "outfile",
525        "over",
526        "partition",
527        "percent_rank",
528        "precision",
529        "primary",
530        "procedure",
531        "purge",
532        "range",
533        "rank",
534        "read",
535        "reads",
536        "read_write",
537        "real",
538        "recursive",
539        "references",
540        "regexp",
541        "release",
542        "rename",
543        "repeat",
544        "replace",
545        "require",
546        "resignal",
547        "restrict",
548        "return",
549        "revoke",
550        "right",
551        "rlike",
552        "row",
553        "rows",
554        "row_number",
555        "schema",
556        "schemas",
557        "second_microsecond",
558        "select",
559        "sensitive",
560        "separator",
561        "set",
562        "show",
563        "signal",
564        "smallint",
565        "spatial",
566        "specific",
567        "sql",
568        "sqlexception",
569        "sqlstate",
570        "sqlwarning",
571        "sql_big_result",
572        "sql_calc_found_rows",
573        "sql_small_result",
574        "ssl",
575        "starting",
576        "stored",
577        "straight_join",
578        "system",
579        "table",
580        "terminated",
581        "then",
582        "tinyblob",
583        "tinyint",
584        "tinytext",
585        "to",
586        "trailing",
587        "trigger",
588        "true",
589        "undo",
590        "union",
591        "unique",
592        "unlock",
593        "unsigned",
594        "update",
595        "usage",
596        "use",
597        "using",
598        "utc_date",
599        "utc_time",
600        "utc_timestamp",
601        "values",
602        "varbinary",
603        "varchar",
604        "varcharacter",
605        "varying",
606        "virtual",
607        "when",
608        "where",
609        "while",
610        "window",
611        "with",
612        "write",
613        "xor",
614        "year_month",
615        "zerofill",
616    }
617
618    SQL_SECURITY_VIEW_LOCATION: t.ClassVar = exp.Properties.Location.POST_CREATE
619
620    def makeinterval_sql(self: MySQLGenerator, expression: exp.MakeInterval) -> str:
621        intervals: list[exp.Interval] = []
622        for arg_key, value in expression.args.items():
623            if value is None:
624                continue
625
626            if isinstance(value, exp.Kwarg):
627                unit_name = _MAKE_INTERVAL_UNIT_ALIASES.get(
628                    value.this.name.lower(), value.this.name.lower()
629                )
630                value = value.expression
631            else:
632                unit_name = arg_key
633
634            intervals.append(exp.Interval(this=value.copy(), unit=exp.var(unit_name.upper())))
635
636        if not intervals:
637            return self.function_fallback_sql(expression)
638
639        parent = expression.parent
640        sep = " - " if isinstance(parent, exp.Sub) and parent.expression is expression else " + "
641
642        return sep.join(self.sql(interval) for interval in intervals)
643
644    def locate_properties(self, properties: exp.Properties) -> defaultdict:
645        locations = super().locate_properties(properties)
646
647        # MySQL puts SQL SECURITY before VIEW but after the schema for functions/procedures
648        if isinstance(create := properties.parent, exp.Create) and create.kind == "VIEW":
649            post_schema = locations[exp.Properties.Location.POST_SCHEMA]
650            for i, p in enumerate(post_schema):
651                if isinstance(p, exp.SqlSecurityProperty):
652                    post_schema.pop(i)
653                    locations[self.SQL_SECURITY_VIEW_LOCATION].append(p)
654                    break
655
656        return locations
657
658    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
659        persisted = "STORED" if expression.args.get("persisted") else "VIRTUAL"
660        return f"GENERATED ALWAYS AS ({self.sql(expression.this.unnest())}) {persisted}"
661
662    def array_sql(self, expression: exp.Array) -> str:
663        self.unsupported("Arrays are not supported by MySQL")
664        return self.function_fallback_sql(expression)
665
666    def arraycontainsall_sql(self, expression: exp.ArrayContainsAll) -> str:
667        self.unsupported("Array operations are not supported by MySQL")
668        return self.function_fallback_sql(expression)
669
670    def arraycontainedby_sql(self, expression: exp.ArrayContainedBy) -> str:
671        self.unsupported("Array operations are not supported by MySQL")
672        return self.function_fallback_sql(expression)
673
674    def dpipe_sql(self, expression: exp.DPipe) -> str:
675        return self.func("CONCAT", *expression.flatten())
676
677    def extract_sql(self, expression: exp.Extract) -> str:
678        unit = expression.name
679        if unit and unit.lower() == "epoch":
680            return self.func("UNIX_TIMESTAMP", expression.expression)
681
682        return super().extract_sql(expression)
683
684    def datatype_sql(self, expression: exp.DataType) -> str:
685        if (
686            self.VARCHAR_REQUIRES_SIZE
687            and expression.is_type(exp.DType.VARCHAR)
688            and not expression.expressions
689        ):
690            # `VARCHAR` must always have a size - if it doesn't, we always generate `TEXT`
691            return "TEXT"
692
693        # https://dev.mysql.com/doc/refman/8.0/en/numeric-type-syntax.html
694        result = super().datatype_sql(expression)
695        if expression.this in self.UNSIGNED_TYPE_MAPPING:
696            result = f"{result} UNSIGNED"
697
698        return result
699
700    def jsonarraycontains_sql(self, expression: exp.JSONArrayContains) -> str:
701        return f"{self.sql(expression, 'this')} MEMBER OF({self.sql(expression, 'expression')})"
702
703    def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str:
704        if expression.to.this in self.TIMESTAMP_FUNC_TYPES:
705            return self.func("TIMESTAMP", expression.this)
706
707        to = self.CAST_MAPPING.get(expression.to.this)
708
709        if to:
710            expression.to.set("this", to)
711        return super().cast_sql(expression, safe_prefix=safe_prefix)
712
713    def show_sql(self, expression: exp.Show) -> str:
714        this = f" {expression.name}"
715        full = " FULL" if expression.args.get("full") else ""
716        global_ = " GLOBAL" if expression.args.get("global_") else ""
717
718        target = self.sql(expression, "target")
719
720        # SHOW CREATE ... takes a possibly qualified name, it has no FROM clause
721        # https://dev.mysql.com/doc/refman/8.4/en/show-create-table.html
722        if expression.name.startswith("CREATE") and (db_id := self.sql(expression, "db")):
723            target = f"{db_id}.{target}"
724            db = ""
725        else:
726            db = self._prefixed_sql("FROM", expression, "db")
727
728        target = f" {target}" if target else ""
729        if expression.name in ("COLUMNS", "INDEX"):
730            target = f" FROM{target}"
731        elif expression.name == "GRANTS":
732            target = f" FOR{target}"
733        elif expression.name in ("LINKS", "PARTITIONS"):
734            target = f" ON{target}" if target else ""
735        elif expression.name == "PROJECTIONS":
736            target = f" ON TABLE{target}" if target else ""
737
738        like = self._prefixed_sql("LIKE", expression, "like")
739        where = self.sql(expression, "where")
740
741        types = self.expressions(expression, key="types")
742        types = f" {types}" if types else types
743        query = self._prefixed_sql("FOR QUERY", expression, "query")
744
745        if expression.name == "PROFILE":
746            offset = self._prefixed_sql("OFFSET", expression, "offset")
747            limit = self._prefixed_sql("LIMIT", expression, "limit")
748        else:
749            offset = ""
750            limit = self._oldstyle_limit_sql(expression)
751
752        log = self._prefixed_sql("IN", expression, "log")
753        position = self._prefixed_sql("FROM", expression, "position")
754
755        channel = self._prefixed_sql("FOR CHANNEL", expression, "channel")
756
757        if expression.name == "ENGINE":
758            mutex_or_status = " MUTEX" if expression.args.get("mutex") else " STATUS"
759        else:
760            mutex_or_status = ""
761
762        for_table = self._prefixed_sql("FOR TABLE", expression, "for_table")
763        for_group = self._prefixed_sql("FOR GROUP", expression, "for_group")
764        for_user = self._prefixed_sql("FOR USER", expression, "for_user")
765        for_role = self._prefixed_sql("FOR ROLE", expression, "for_role")
766        into_outfile = self._prefixed_sql("INTO OUTFILE", expression, "into_outfile")
767        json = " JSON" if expression.args.get("json") else ""
768
769        return f"SHOW{full}{global_}{this}{json}{target}{for_table}{types}{db}{query}{log}{position}{channel}{mutex_or_status}{like}{where}{offset}{limit}{for_group}{for_user}{for_role}{into_outfile}"
770
771    def alterrename_sql(self, expression: exp.AlterRename, include_to: bool = True) -> str:
772        """To avoid TO keyword in ALTER ... RENAME statements.
773        It's moved from Doris, because it's the same for all MySQL, Doris, and StarRocks.
774        """
775        return super().alterrename_sql(expression, include_to=False)
776
777    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
778        dtype = self.sql(expression, "dtype")
779        if not dtype:
780            return super().altercolumn_sql(expression)
781
782        if expression.args.get("exists"):
783            self.unsupported("ALTER COLUMN IF EXISTS is not supported by this dialect")
784
785        this = self.sql(expression, "this")
786        null_constraint = self._alter_column_null_constraint_sql(expression)
787        return f"MODIFY COLUMN {this} {dtype}{null_constraint}"
788
789    def _prefixed_sql(self, prefix: str, expression: exp.Expr, arg: str) -> str:
790        sql = self.sql(expression, arg)
791        return f" {prefix} {sql}" if sql else ""
792
793    def _oldstyle_limit_sql(self, expression: exp.Show) -> str:
794        limit = self.sql(expression, "limit")
795        offset = self.sql(expression, "offset")
796        if limit:
797            limit_offset = f"{offset}, {limit}" if offset else limit
798            return f" LIMIT {limit_offset}"
799        return ""
800
801    def timestamptrunc_sql(self, expression: exp.TimestampTrunc) -> str:
802        unit = expression.args.get("unit")
803        if isinstance(unit, exp.WeekStart):
804            unit = exp.var(self.weekstart_name(unit))
805
806        # Pick an old-enough date to avoid negative timestamp diffs
807        start_ts = "'0000-01-01 00:00:00'"
808
809        # Source: https://stackoverflow.com/a/32955740
810        timestamp_diff = build_date_delta(exp.TimestampDiff)([unit, start_ts, expression.this])
811        interval = exp.Interval(this=timestamp_diff, unit=unit)
812        dateadd = build_date_delta_with_interval(exp.DateAdd)([start_ts, interval])
813
814        return self.sql(dateadd)
815
816    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
817        from_tz = expression.args.get("source_tz")
818        to_tz = expression.args.get("target_tz")
819        dt = expression.args.get("timestamp")
820
821        return self.func("CONVERT_TZ", dt, from_tz, to_tz)
822
823    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
824        self.unsupported("AT TIME ZONE is not supported by MySQL")
825        return self.sql(expression.this)
826
827    def isascii_sql(self, expression: exp.IsAscii) -> str:
828        return f"REGEXP_LIKE({self.sql(expression.this)}, '^[[:ascii:]]*$')"
829
830    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
831        # https://dev.mysql.com/doc/refman/8.4/en/window-function-descriptions.html
832        self.unsupported("MySQL does not support IGNORE NULLS.")
833        return self.sql(expression.this)
834
835    @unsupported_args("this")
836    def currentschema_sql(self, expression: exp.CurrentSchema) -> str:
837        return self.func("SCHEMA")
838
839    def partition_sql(self, expression: exp.Partition) -> str:
840        parent = expression.parent
841        if isinstance(parent, (exp.PartitionByRangeProperty, exp.PartitionByListProperty)):
842            return self.expressions(expression, flat=True)
843        return super().partition_sql(expression)
844
845    def _partition_by_sql(
846        self, expression: exp.PartitionByRangeProperty | exp.PartitionByListProperty, kind: str
847    ) -> str:
848        partitions = self.expressions(expression, key="partition_expressions", flat=True)
849        create = self.expressions(expression, key="create_expressions", flat=True)
850        return f"PARTITION BY {kind} ({partitions}) ({create})"
851
852    def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str:
853        return self._partition_by_sql(expression, "RANGE")
854
855    def partitionbylistproperty_sql(self, expression: exp.PartitionByListProperty) -> str:
856        return self._partition_by_sql(expression, "LIST")
857
858    def partitionlist_sql(self, expression: exp.PartitionList) -> str:
859        name = self.sql(expression, "this")
860        values = self.expressions(expression, flat=True)
861        return f"PARTITION {name} VALUES IN ({values})"
862
863    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
864        name = self.sql(expression, "this")
865        values = self.expressions(expression, flat=True)
866        return f"PARTITION {name} VALUES LESS THAN ({values})"
def date_add_sql( kind: str) -> Callable[[sqlglot.generator.Generator, sqlglot.expressions.core.Expr], str]:
82def date_add_sql(
83    kind: str,
84) -> t.Callable[[generator.Generator, exp.Expr], str]:
85    def func(self: generator.Generator, expression: exp.Expr) -> str:
86        return self.func(
87            f"DATE_{kind}",
88            expression.this,
89            exp.Interval(this=expression.expression, unit=unit_to_var(expression)),
90        )
91
92    return func
class MySQLGenerator(sqlglot.generator.Generator):
113class MySQLGenerator(generator.Generator):
114    DAYOFWEEK_NAME = "DAYOFWEEK"
115    BYTE_STRING_FUNCTION = "UNHEX"
116    VARIANCE_NAME = "VAR_SAMP"
117    SELECT_KINDS = ()
118    TRY_SUPPORTED = False
119    SUPPORTS_UESCAPE = False
120    SUPPORTS_DECODE_CASE = False
121    SUPPORTS_MODIFY_COLUMN = True
122    SUPPORTS_CHANGE_COLUMN = True
123    SUPPORTS_ALTER_COLUMN_NULLABILITY = True
124
125    AFTER_HAVING_MODIFIER_TRANSFORMS = generator.AFTER_HAVING_MODIFIER_TRANSFORMS
126
127    INTERVAL_ALLOWS_PLURAL_FORM = False
128    LOCKING_READS_SUPPORTED = True
129    CAST_TO_INT_ROUNDS = True
130    INT_DIV_OPERATOR: str | None = "DIV"
131    NULL_ORDERING_SUPPORTED: bool | None = None
132    JOIN_HINTS = False
133    TABLE_HINTS = True
134    DUPLICATE_KEY_UPDATE_WITH_SET = False
135    QUERY_HINT_SEP = " "
136    VALUES_AS_TABLE = False
137    NVL2_SUPPORTED = False
138    LAST_DAY_SUPPORTS_DATE_PART = False
139    JSON_TYPE_REQUIRED_FOR_EXTRACTION = True
140    JSON_PATH_BRACKETED_KEY_SUPPORTED = False
141    JSON_KEY_VALUE_PAIR_SEP = ","
142    SUPPORTS_TO_NUMBER = False
143    PARSE_JSON_NAME: str | None = None
144    PAD_FILL_PATTERN_IS_REQUIRED = True
145    WRAP_DERIVED_VALUES = False
146    VARCHAR_REQUIRES_SIZE = True
147    SUPPORTS_MEDIAN = False
148    UPDATE_STATEMENT_SUPPORTS_FROM = False
149
150    ALTER_PARTITION_OPTIONS: t.ClassVar[tuple[type[exp.Expr], ...]] = (
151        exp.PartitionByListProperty,
152        exp.PartitionByRangeProperty,
153    )
154
155    TRANSFORMS = {
156        # The base Postgres-style array operators (@>, <@) don't exist in MySQL, so drop
157        # them to let arraycontainsall_sql / arraycontainedby_sql flag them as unsupported
158        **{
159            k: v
160            for k, v in generator.Generator.TRANSFORMS.items()
161            if k not in {exp.ArrayContainsAll, exp.ArrayContainedBy}
162        },
163        exp.ArrayAgg: rename_func("GROUP_CONCAT"),
164        exp.BitwiseAndAgg: rename_func("BIT_AND"),
165        exp.BitwiseOrAgg: rename_func("BIT_OR"),
166        exp.BitwiseXorAgg: rename_func("BIT_XOR"),
167        exp.BitwiseCount: rename_func("BIT_COUNT"),
168        exp.Chr: lambda self, e: self.chr_sql(e, "CHAR"),
169        exp.CurrentDate: no_paren_current_date_sql,
170        exp.CurrentVersion: rename_func("VERSION"),
171        exp.DateDiff: remove_ts_or_ds_to_date(
172            lambda self, e: self.func("DATEDIFF", e.this, e.expression), ("this", "expression")
173        ),
174        exp.DateAdd: date_add_sql("ADD"),
175        exp.DateStrToDate: datestrtodate_sql,
176        exp.DateSub: date_add_sql("SUB"),
177        exp.DateTrunc: _date_trunc_sql,
178        exp.Day: remove_ts_or_ds_to_date(),
179        exp.DayOfMonth: remove_ts_or_ds_to_date(rename_func("DAYOFMONTH")),
180        exp.DayOfWeek: remove_ts_or_ds_to_date(generator.Generator.dayofweek_sql),
181        exp.DayOfYear: remove_ts_or_ds_to_date(rename_func("DAYOFYEAR")),
182        exp.GroupConcat: lambda self, e: (
183            f"""GROUP_CONCAT({self.sql(e, "this")} SEPARATOR {self.sql(e, "separator") or "','"})"""
184        ),
185        exp.ILike: no_ilike_sql,
186        # https://dev.mysql.com/doc/refman/9.7/en/flow-control-functions.html#function_if
187        exp.If: if_sql(false_value="NULL"),
188        exp.JSONExtractScalar: arrow_json_extract_sql,
189        exp.Length: length_or_char_length_sql,
190        exp.LogicalOr: rename_func("MAX"),
191        exp.LogicalAnd: rename_func("MIN"),
192        exp.Max: max_or_greatest,
193        exp.Min: min_or_least,
194        exp.Month: remove_ts_or_ds_to_date(),
195        exp.NullSafeEQ: lambda self, e: self.binary(e, "<=>"),
196        exp.NullSafeNEQ: lambda self, e: f"NOT {self.binary(e, '<=>')}",
197        exp.NumberToStr: rename_func("FORMAT"),
198        exp.Pivot: no_pivot_sql,
199        exp.Select: transforms.preprocess(
200            [
201                transforms.eliminate_distinct_on,
202                transforms.eliminate_semi_and_anti_joins,
203                transforms.eliminate_qualify,
204                transforms.eliminate_full_outer_join,
205                transforms.unnest_generate_date_array_using_recursive_cte,
206            ]
207        ),
208        exp.Stddev: rename_func("STDDEV_SAMP"),
209        exp.StrPosition: lambda self, e: strposition_sql(
210            self, e, func_name="LOCATE", supports_position=True
211        ),
212        exp.StrToDate: _str_to_date_sql,
213        exp.StrToTime: _str_to_date_sql,
214        exp.Stuff: rename_func("INSERT"),
215        exp.SessionUser: lambda *_: "SESSION_USER()",
216        exp.TableSample: no_tablesample_sql,
217        exp.TimeFromParts: rename_func("MAKETIME"),
218        exp.TimestampAdd: date_add_interval_sql("DATE", "ADD"),
219        exp.TimestampDiff: lambda self, e: self.func(
220            "TIMESTAMPDIFF", unit_to_var(e), e.expression, e.this
221        ),
222        exp.TimestampSub: date_add_interval_sql("DATE", "SUB"),
223        exp.TimeStrToUnix: rename_func("UNIX_TIMESTAMP"),
224        exp.TimeStrToTime: lambda self, e: timestrtotime_sql(
225            self,
226            e,
227            include_precision=not e.args.get("zone"),
228        ),
229        exp.TimeToStr: remove_ts_or_ds_to_date(
230            lambda self, e: self.func("DATE_FORMAT", e.this, self.format_time(e))
231        ),
232        exp.Trim: trim_sql,
233        exp.Trunc: lambda self, e: self.func(
234            "TRUNCATE", e.this, e.args.get("decimals") or exp.Literal.number(0)
235        ),
236        exp.TryCast: no_trycast_sql,
237        exp.TsOrDsAdd: date_add_sql("ADD"),
238        exp.TsOrDsDiff: lambda self, e: self.func("DATEDIFF", e.this, e.expression),
239        exp.TsOrDsToDate: _ts_or_ds_to_date_sql,
240        exp.Unicode: lambda self, e: f"ORD(CONVERT({self.sql(e.this)} USING utf32))",
241        exp.UnixToTime: _unix_to_time_sql,
242        exp.VariancePop: rename_func("VAR_POP"),
243        exp.Week: remove_ts_or_ds_to_date(),
244        exp.WeekOfYear: remove_ts_or_ds_to_date(rename_func("WEEKOFYEAR")),
245        exp.Year: remove_ts_or_ds_to_date(),
246        exp.UtcTimestamp: rename_func("UTC_TIMESTAMP"),
247        exp.UtcTime: rename_func("UTC_TIME"),
248    }
249
250    UNSIGNED_TYPE_MAPPING: t.ClassVar = {
251        exp.DType.UBIGINT: "BIGINT",
252        exp.DType.UINT: "INT",
253        exp.DType.UMEDIUMINT: "MEDIUMINT",
254        exp.DType.USMALLINT: "SMALLINT",
255        exp.DType.UTINYINT: "TINYINT",
256        exp.DType.UDECIMAL: "DECIMAL",
257        exp.DType.UDOUBLE: "DOUBLE",
258    }
259
260    TIMESTAMP_TYPE_MAPPING: t.ClassVar = {
261        exp.DType.DATETIME2: "DATETIME",
262        exp.DType.SMALLDATETIME: "DATETIME",
263        exp.DType.TIMESTAMP: "DATETIME",
264        exp.DType.TIMESTAMPNTZ: "DATETIME",
265        exp.DType.TIMESTAMPTZ: "TIMESTAMP",
266        exp.DType.TIMESTAMPLTZ: "TIMESTAMP",
267    }
268
269    TYPE_MAPPING: t.ClassVar = {
270        exp.DType.NCHAR: "CHAR",
271        exp.DType.NVARCHAR: "VARCHAR",
272        exp.DType.INET: "INET",
273        exp.DType.ROWVERSION: "VARBINARY",
274        exp.DType.UBIGINT: "BIGINT",
275        exp.DType.UINT: "INT",
276        exp.DType.UMEDIUMINT: "MEDIUMINT",
277        exp.DType.USMALLINT: "SMALLINT",
278        exp.DType.UTINYINT: "TINYINT",
279        exp.DType.UDECIMAL: "DECIMAL",
280        exp.DType.UDOUBLE: "DOUBLE",
281        exp.DType.DATETIME2: "DATETIME",
282        exp.DType.SMALLDATETIME: "DATETIME",
283        exp.DType.TIMESTAMP: "DATETIME",
284        exp.DType.TIMESTAMPNTZ: "DATETIME",
285        exp.DType.TIMESTAMPTZ: "TIMESTAMP",
286        exp.DType.TIMESTAMPLTZ: "TIMESTAMP",
287    }
288
289    PROPERTIES_LOCATION: t.ClassVar = {
290        **generator.Generator.PROPERTIES_LOCATION,
291        exp.TransientProperty: exp.Properties.Location.UNSUPPORTED,
292        exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
293        exp.PartitionedByProperty: exp.Properties.Location.UNSUPPORTED,
294        exp.PartitionByRangeProperty: exp.Properties.Location.POST_SCHEMA,
295        exp.PartitionByListProperty: exp.Properties.Location.POST_SCHEMA,
296        exp.Property: exp.Properties.Location.POST_SCHEMA,
297    }
298
299    LIMIT_FETCH = "LIMIT"
300
301    LIMIT_ONLY_LITERALS = True
302
303    CHAR_CAST_MAPPING: t.ClassVar = dict.fromkeys(
304        (
305            exp.DType.LONGTEXT,
306            exp.DType.LONGBLOB,
307            exp.DType.MEDIUMBLOB,
308            exp.DType.MEDIUMTEXT,
309            exp.DType.TEXT,
310            exp.DType.TINYBLOB,
311            exp.DType.TINYTEXT,
312            exp.DType.VARCHAR,
313        ),
314        "CHAR",
315    )
316    SIGNED_CAST_MAPPING: t.ClassVar = dict.fromkeys(
317        (
318            exp.DType.BIGINT,
319            exp.DType.BOOLEAN,
320            exp.DType.INT,
321            exp.DType.SMALLINT,
322            exp.DType.TINYINT,
323            exp.DType.MEDIUMINT,
324        ),
325        "SIGNED",
326    )
327
328    # MySQL doesn't support many datatypes in cast.
329    # https://dev.mysql.com/doc/refman/8.0/en/cast-functions.html#function_cast
330    CAST_MAPPING: t.ClassVar = {
331        exp.DType.LONGTEXT: "CHAR",
332        exp.DType.LONGBLOB: "CHAR",
333        exp.DType.MEDIUMBLOB: "CHAR",
334        exp.DType.MEDIUMTEXT: "CHAR",
335        exp.DType.TEXT: "CHAR",
336        exp.DType.TINYBLOB: "CHAR",
337        exp.DType.TINYTEXT: "CHAR",
338        exp.DType.VARCHAR: "CHAR",
339        exp.DType.BIGINT: "SIGNED",
340        exp.DType.BOOLEAN: "SIGNED",
341        exp.DType.INT: "SIGNED",
342        exp.DType.SMALLINT: "SIGNED",
343        exp.DType.TINYINT: "SIGNED",
344        exp.DType.MEDIUMINT: "SIGNED",
345        exp.DType.UBIGINT: "UNSIGNED",
346    }
347
348    TIMESTAMP_FUNC_TYPES: t.ClassVar = {
349        exp.DType.TIMESTAMPTZ,
350        exp.DType.TIMESTAMPLTZ,
351    }
352
353    # https://dev.mysql.com/doc/refman/8.0/en/keywords.html
354    RESERVED_KEYWORDS = {
355        "accessible",
356        "add",
357        "all",
358        "alter",
359        "analyze",
360        "and",
361        "as",
362        "asc",
363        "asensitive",
364        "before",
365        "between",
366        "bigint",
367        "binary",
368        "blob",
369        "both",
370        "by",
371        "call",
372        "cascade",
373        "case",
374        "change",
375        "char",
376        "character",
377        "check",
378        "collate",
379        "column",
380        "condition",
381        "constraint",
382        "continue",
383        "convert",
384        "create",
385        "cross",
386        "cube",
387        "cume_dist",
388        "current_date",
389        "current_time",
390        "current_timestamp",
391        "current_user",
392        "cursor",
393        "database",
394        "databases",
395        "day_hour",
396        "day_microsecond",
397        "day_minute",
398        "day_second",
399        "dec",
400        "decimal",
401        "declare",
402        "default",
403        "delayed",
404        "delete",
405        "dense_rank",
406        "desc",
407        "describe",
408        "deterministic",
409        "distinct",
410        "distinctrow",
411        "div",
412        "double",
413        "drop",
414        "dual",
415        "each",
416        "else",
417        "elseif",
418        "empty",
419        "enclosed",
420        "escaped",
421        "except",
422        "exists",
423        "exit",
424        "explain",
425        "false",
426        "fetch",
427        "first_value",
428        "float",
429        "float4",
430        "float8",
431        "for",
432        "force",
433        "foreign",
434        "from",
435        "fulltext",
436        "function",
437        "generated",
438        "get",
439        "grant",
440        "group",
441        "grouping",
442        "groups",
443        "having",
444        "high_priority",
445        "hour_microsecond",
446        "hour_minute",
447        "hour_second",
448        "if",
449        "ignore",
450        "in",
451        "index",
452        "infile",
453        "inner",
454        "inout",
455        "insensitive",
456        "insert",
457        "int",
458        "int1",
459        "int2",
460        "int3",
461        "int4",
462        "int8",
463        "integer",
464        "intersect",
465        "interval",
466        "into",
467        "io_after_gtids",
468        "io_before_gtids",
469        "is",
470        "iterate",
471        "join",
472        "json_table",
473        "key",
474        "keys",
475        "kill",
476        "lag",
477        "last_value",
478        "lateral",
479        "lead",
480        "leading",
481        "leave",
482        "left",
483        "like",
484        "limit",
485        "linear",
486        "lines",
487        "load",
488        "localtime",
489        "localtimestamp",
490        "lock",
491        "long",
492        "longblob",
493        "longtext",
494        "loop",
495        "low_priority",
496        "master_bind",
497        "master_ssl_verify_server_cert",
498        "match",
499        "maxvalue",
500        "mediumblob",
501        "mediumint",
502        "mediumtext",
503        "middleint",
504        "minute_microsecond",
505        "minute_second",
506        "mod",
507        "modifies",
508        "natural",
509        "not",
510        "no_write_to_binlog",
511        "nth_value",
512        "ntile",
513        "null",
514        "numeric",
515        "of",
516        "on",
517        "optimize",
518        "optimizer_costs",
519        "option",
520        "optionally",
521        "or",
522        "order",
523        "out",
524        "outer",
525        "outfile",
526        "over",
527        "partition",
528        "percent_rank",
529        "precision",
530        "primary",
531        "procedure",
532        "purge",
533        "range",
534        "rank",
535        "read",
536        "reads",
537        "read_write",
538        "real",
539        "recursive",
540        "references",
541        "regexp",
542        "release",
543        "rename",
544        "repeat",
545        "replace",
546        "require",
547        "resignal",
548        "restrict",
549        "return",
550        "revoke",
551        "right",
552        "rlike",
553        "row",
554        "rows",
555        "row_number",
556        "schema",
557        "schemas",
558        "second_microsecond",
559        "select",
560        "sensitive",
561        "separator",
562        "set",
563        "show",
564        "signal",
565        "smallint",
566        "spatial",
567        "specific",
568        "sql",
569        "sqlexception",
570        "sqlstate",
571        "sqlwarning",
572        "sql_big_result",
573        "sql_calc_found_rows",
574        "sql_small_result",
575        "ssl",
576        "starting",
577        "stored",
578        "straight_join",
579        "system",
580        "table",
581        "terminated",
582        "then",
583        "tinyblob",
584        "tinyint",
585        "tinytext",
586        "to",
587        "trailing",
588        "trigger",
589        "true",
590        "undo",
591        "union",
592        "unique",
593        "unlock",
594        "unsigned",
595        "update",
596        "usage",
597        "use",
598        "using",
599        "utc_date",
600        "utc_time",
601        "utc_timestamp",
602        "values",
603        "varbinary",
604        "varchar",
605        "varcharacter",
606        "varying",
607        "virtual",
608        "when",
609        "where",
610        "while",
611        "window",
612        "with",
613        "write",
614        "xor",
615        "year_month",
616        "zerofill",
617    }
618
619    SQL_SECURITY_VIEW_LOCATION: t.ClassVar = exp.Properties.Location.POST_CREATE
620
621    def makeinterval_sql(self: MySQLGenerator, expression: exp.MakeInterval) -> str:
622        intervals: list[exp.Interval] = []
623        for arg_key, value in expression.args.items():
624            if value is None:
625                continue
626
627            if isinstance(value, exp.Kwarg):
628                unit_name = _MAKE_INTERVAL_UNIT_ALIASES.get(
629                    value.this.name.lower(), value.this.name.lower()
630                )
631                value = value.expression
632            else:
633                unit_name = arg_key
634
635            intervals.append(exp.Interval(this=value.copy(), unit=exp.var(unit_name.upper())))
636
637        if not intervals:
638            return self.function_fallback_sql(expression)
639
640        parent = expression.parent
641        sep = " - " if isinstance(parent, exp.Sub) and parent.expression is expression else " + "
642
643        return sep.join(self.sql(interval) for interval in intervals)
644
645    def locate_properties(self, properties: exp.Properties) -> defaultdict:
646        locations = super().locate_properties(properties)
647
648        # MySQL puts SQL SECURITY before VIEW but after the schema for functions/procedures
649        if isinstance(create := properties.parent, exp.Create) and create.kind == "VIEW":
650            post_schema = locations[exp.Properties.Location.POST_SCHEMA]
651            for i, p in enumerate(post_schema):
652                if isinstance(p, exp.SqlSecurityProperty):
653                    post_schema.pop(i)
654                    locations[self.SQL_SECURITY_VIEW_LOCATION].append(p)
655                    break
656
657        return locations
658
659    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
660        persisted = "STORED" if expression.args.get("persisted") else "VIRTUAL"
661        return f"GENERATED ALWAYS AS ({self.sql(expression.this.unnest())}) {persisted}"
662
663    def array_sql(self, expression: exp.Array) -> str:
664        self.unsupported("Arrays are not supported by MySQL")
665        return self.function_fallback_sql(expression)
666
667    def arraycontainsall_sql(self, expression: exp.ArrayContainsAll) -> str:
668        self.unsupported("Array operations are not supported by MySQL")
669        return self.function_fallback_sql(expression)
670
671    def arraycontainedby_sql(self, expression: exp.ArrayContainedBy) -> str:
672        self.unsupported("Array operations are not supported by MySQL")
673        return self.function_fallback_sql(expression)
674
675    def dpipe_sql(self, expression: exp.DPipe) -> str:
676        return self.func("CONCAT", *expression.flatten())
677
678    def extract_sql(self, expression: exp.Extract) -> str:
679        unit = expression.name
680        if unit and unit.lower() == "epoch":
681            return self.func("UNIX_TIMESTAMP", expression.expression)
682
683        return super().extract_sql(expression)
684
685    def datatype_sql(self, expression: exp.DataType) -> str:
686        if (
687            self.VARCHAR_REQUIRES_SIZE
688            and expression.is_type(exp.DType.VARCHAR)
689            and not expression.expressions
690        ):
691            # `VARCHAR` must always have a size - if it doesn't, we always generate `TEXT`
692            return "TEXT"
693
694        # https://dev.mysql.com/doc/refman/8.0/en/numeric-type-syntax.html
695        result = super().datatype_sql(expression)
696        if expression.this in self.UNSIGNED_TYPE_MAPPING:
697            result = f"{result} UNSIGNED"
698
699        return result
700
701    def jsonarraycontains_sql(self, expression: exp.JSONArrayContains) -> str:
702        return f"{self.sql(expression, 'this')} MEMBER OF({self.sql(expression, 'expression')})"
703
704    def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str:
705        if expression.to.this in self.TIMESTAMP_FUNC_TYPES:
706            return self.func("TIMESTAMP", expression.this)
707
708        to = self.CAST_MAPPING.get(expression.to.this)
709
710        if to:
711            expression.to.set("this", to)
712        return super().cast_sql(expression, safe_prefix=safe_prefix)
713
714    def show_sql(self, expression: exp.Show) -> str:
715        this = f" {expression.name}"
716        full = " FULL" if expression.args.get("full") else ""
717        global_ = " GLOBAL" if expression.args.get("global_") else ""
718
719        target = self.sql(expression, "target")
720
721        # SHOW CREATE ... takes a possibly qualified name, it has no FROM clause
722        # https://dev.mysql.com/doc/refman/8.4/en/show-create-table.html
723        if expression.name.startswith("CREATE") and (db_id := self.sql(expression, "db")):
724            target = f"{db_id}.{target}"
725            db = ""
726        else:
727            db = self._prefixed_sql("FROM", expression, "db")
728
729        target = f" {target}" if target else ""
730        if expression.name in ("COLUMNS", "INDEX"):
731            target = f" FROM{target}"
732        elif expression.name == "GRANTS":
733            target = f" FOR{target}"
734        elif expression.name in ("LINKS", "PARTITIONS"):
735            target = f" ON{target}" if target else ""
736        elif expression.name == "PROJECTIONS":
737            target = f" ON TABLE{target}" if target else ""
738
739        like = self._prefixed_sql("LIKE", expression, "like")
740        where = self.sql(expression, "where")
741
742        types = self.expressions(expression, key="types")
743        types = f" {types}" if types else types
744        query = self._prefixed_sql("FOR QUERY", expression, "query")
745
746        if expression.name == "PROFILE":
747            offset = self._prefixed_sql("OFFSET", expression, "offset")
748            limit = self._prefixed_sql("LIMIT", expression, "limit")
749        else:
750            offset = ""
751            limit = self._oldstyle_limit_sql(expression)
752
753        log = self._prefixed_sql("IN", expression, "log")
754        position = self._prefixed_sql("FROM", expression, "position")
755
756        channel = self._prefixed_sql("FOR CHANNEL", expression, "channel")
757
758        if expression.name == "ENGINE":
759            mutex_or_status = " MUTEX" if expression.args.get("mutex") else " STATUS"
760        else:
761            mutex_or_status = ""
762
763        for_table = self._prefixed_sql("FOR TABLE", expression, "for_table")
764        for_group = self._prefixed_sql("FOR GROUP", expression, "for_group")
765        for_user = self._prefixed_sql("FOR USER", expression, "for_user")
766        for_role = self._prefixed_sql("FOR ROLE", expression, "for_role")
767        into_outfile = self._prefixed_sql("INTO OUTFILE", expression, "into_outfile")
768        json = " JSON" if expression.args.get("json") else ""
769
770        return f"SHOW{full}{global_}{this}{json}{target}{for_table}{types}{db}{query}{log}{position}{channel}{mutex_or_status}{like}{where}{offset}{limit}{for_group}{for_user}{for_role}{into_outfile}"
771
772    def alterrename_sql(self, expression: exp.AlterRename, include_to: bool = True) -> str:
773        """To avoid TO keyword in ALTER ... RENAME statements.
774        It's moved from Doris, because it's the same for all MySQL, Doris, and StarRocks.
775        """
776        return super().alterrename_sql(expression, include_to=False)
777
778    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
779        dtype = self.sql(expression, "dtype")
780        if not dtype:
781            return super().altercolumn_sql(expression)
782
783        if expression.args.get("exists"):
784            self.unsupported("ALTER COLUMN IF EXISTS is not supported by this dialect")
785
786        this = self.sql(expression, "this")
787        null_constraint = self._alter_column_null_constraint_sql(expression)
788        return f"MODIFY COLUMN {this} {dtype}{null_constraint}"
789
790    def _prefixed_sql(self, prefix: str, expression: exp.Expr, arg: str) -> str:
791        sql = self.sql(expression, arg)
792        return f" {prefix} {sql}" if sql else ""
793
794    def _oldstyle_limit_sql(self, expression: exp.Show) -> str:
795        limit = self.sql(expression, "limit")
796        offset = self.sql(expression, "offset")
797        if limit:
798            limit_offset = f"{offset}, {limit}" if offset else limit
799            return f" LIMIT {limit_offset}"
800        return ""
801
802    def timestamptrunc_sql(self, expression: exp.TimestampTrunc) -> str:
803        unit = expression.args.get("unit")
804        if isinstance(unit, exp.WeekStart):
805            unit = exp.var(self.weekstart_name(unit))
806
807        # Pick an old-enough date to avoid negative timestamp diffs
808        start_ts = "'0000-01-01 00:00:00'"
809
810        # Source: https://stackoverflow.com/a/32955740
811        timestamp_diff = build_date_delta(exp.TimestampDiff)([unit, start_ts, expression.this])
812        interval = exp.Interval(this=timestamp_diff, unit=unit)
813        dateadd = build_date_delta_with_interval(exp.DateAdd)([start_ts, interval])
814
815        return self.sql(dateadd)
816
817    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
818        from_tz = expression.args.get("source_tz")
819        to_tz = expression.args.get("target_tz")
820        dt = expression.args.get("timestamp")
821
822        return self.func("CONVERT_TZ", dt, from_tz, to_tz)
823
824    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
825        self.unsupported("AT TIME ZONE is not supported by MySQL")
826        return self.sql(expression.this)
827
828    def isascii_sql(self, expression: exp.IsAscii) -> str:
829        return f"REGEXP_LIKE({self.sql(expression.this)}, '^[[:ascii:]]*$')"
830
831    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
832        # https://dev.mysql.com/doc/refman/8.4/en/window-function-descriptions.html
833        self.unsupported("MySQL does not support IGNORE NULLS.")
834        return self.sql(expression.this)
835
836    @unsupported_args("this")
837    def currentschema_sql(self, expression: exp.CurrentSchema) -> str:
838        return self.func("SCHEMA")
839
840    def partition_sql(self, expression: exp.Partition) -> str:
841        parent = expression.parent
842        if isinstance(parent, (exp.PartitionByRangeProperty, exp.PartitionByListProperty)):
843            return self.expressions(expression, flat=True)
844        return super().partition_sql(expression)
845
846    def _partition_by_sql(
847        self, expression: exp.PartitionByRangeProperty | exp.PartitionByListProperty, kind: str
848    ) -> str:
849        partitions = self.expressions(expression, key="partition_expressions", flat=True)
850        create = self.expressions(expression, key="create_expressions", flat=True)
851        return f"PARTITION BY {kind} ({partitions}) ({create})"
852
853    def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str:
854        return self._partition_by_sql(expression, "RANGE")
855
856    def partitionbylistproperty_sql(self, expression: exp.PartitionByListProperty) -> str:
857        return self._partition_by_sql(expression, "LIST")
858
859    def partitionlist_sql(self, expression: exp.PartitionList) -> str:
860        name = self.sql(expression, "this")
861        values = self.expressions(expression, flat=True)
862        return f"PARTITION {name} VALUES IN ({values})"
863
864    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
865        name = self.sql(expression, "this")
866        values = self.expressions(expression, flat=True)
867        return f"PARTITION {name} VALUES LESS THAN ({values})"

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
DAYOFWEEK_NAME = 'DAYOFWEEK'
BYTE_STRING_FUNCTION = 'UNHEX'
VARIANCE_NAME = 'VAR_SAMP'
SELECT_KINDS = ()
TRY_SUPPORTED = False
SUPPORTS_UESCAPE = False
SUPPORTS_DECODE_CASE = False
SUPPORTS_MODIFY_COLUMN = True
SUPPORTS_CHANGE_COLUMN = True
SUPPORTS_ALTER_COLUMN_NULLABILITY = True
AFTER_HAVING_MODIFIER_TRANSFORMS = {'windows': <function <lambda>>, 'qualify': <function <lambda>>}
INTERVAL_ALLOWS_PLURAL_FORM = False
LOCKING_READS_SUPPORTED = True
CAST_TO_INT_ROUNDS = True
INT_DIV_OPERATOR: str | None = 'DIV'
NULL_ORDERING_SUPPORTED: bool | None = None
JOIN_HINTS = False
TABLE_HINTS = True
DUPLICATE_KEY_UPDATE_WITH_SET = False
QUERY_HINT_SEP = ' '
VALUES_AS_TABLE = False
NVL2_SUPPORTED = False
LAST_DAY_SUPPORTS_DATE_PART = False
JSON_TYPE_REQUIRED_FOR_EXTRACTION = True
JSON_PATH_BRACKETED_KEY_SUPPORTED = False
JSON_KEY_VALUE_PAIR_SEP = ','
SUPPORTS_TO_NUMBER = False
PARSE_JSON_NAME: str | None = None
PAD_FILL_PATTERN_IS_REQUIRED = True
WRAP_DERIVED_VALUES = False
VARCHAR_REQUIRES_SIZE = True
SUPPORTS_MEDIAN = False
UPDATE_STATEMENT_SUPPORTS_FROM = False
TRANSFORMS = {<class 'sqlglot.expressions.query.JSONPathFilter'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathKey'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathRecursive'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathRoot'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathScript'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathSelector'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathSlice'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathSubscript'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathUnion'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathWildcard'>: <function <lambda>>, <class 'sqlglot.expressions.core.Adjacent'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.AllowedValuesProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.AnalyzeColumns'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.AnalyzeWith'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayOverlaps'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.AssumeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.BinaryColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CalledOnNullInputProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.math.Ceil'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.ConnectByRoot'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.string.ConvertToCharset'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CopyTagsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CredentialsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.CurrentCatalog'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.SessionUser'>: <function 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.IgnoreGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Intersect'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.datatypes.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.Int64'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsAnyTopKeys'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsAllTopKeys'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsTopKey'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBDeleteAtPath'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBPathExists'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONObject'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONObjectAgg'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.MaskingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.NetFunc'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.NetworkProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.Operator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ExtendsLeft'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ExtendsRight'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.PartitionedByBucket'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.PartitionByTruncate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.PositionalColumn'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ProjectionPolicyColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.InvisibleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ZeroFillColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Put'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.RowAccessProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.SafeFunc'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SecureProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SecurityIntegrationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SharingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Stream'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StreamingTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StrictProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ddl.SwapTable'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.TableColumn'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.VirtualProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ddl.TriggerExecute'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.UsingTemplateProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.UsingData'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcDate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcTime'>: <function 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.WithoutRowidProperty'>: <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.temporal.CurrentDate'>: <function no_paren_current_date_sql>, <class 'sqlglot.expressions.functions.CurrentVersion'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.temporal.DateDiff'>: <function remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.temporal.DateAdd'>: <function date_add_sql.<locals>.func>, <class 'sqlglot.expressions.temporal.DateStrToDate'>: <function datestrtodate_sql>, <class 'sqlglot.expressions.temporal.DateSub'>: <function date_add_sql.<locals>.func>, <class 'sqlglot.expressions.temporal.DateTrunc'>: <function _date_trunc_sql>, <class 'sqlglot.expressions.temporal.Day'>: <function remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.temporal.DayOfMonth'>: <function remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.temporal.DayOfWeek'>: <function remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.temporal.DayOfYear'>: <function remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.aggregate.GroupConcat'>: <function MySQLGenerator.<lambda>>, <class 'sqlglot.expressions.core.ILike'>: <function no_ilike_sql>, <class 'sqlglot.expressions.functions.If'>: <function if_sql.<locals>._if_sql>, <class 'sqlglot.expressions.json.JSONExtractScalar'>: <function arrow_json_extract_sql>, <class 'sqlglot.expressions.string.Length'>: <function length_or_char_length_sql>, <class 'sqlglot.expressions.aggregate.LogicalOr'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.aggregate.LogicalAnd'>: <function rename_func.<locals>.<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.aggregate.Stddev'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.string.StrPosition'>: <function MySQLGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.StrToDate'>: <function _str_to_date_sql>, <class 'sqlglot.expressions.temporal.StrToTime'>: <function _str_to_date_sql>, <class 'sqlglot.expressions.string.Stuff'>: <function rename_func.<locals>.<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 remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.string.Trim'>: <function trim_sql>, <class 'sqlglot.expressions.math.Trunc'>: <function MySQLGenerator.<lambda>>, <class 'sqlglot.expressions.functions.TryCast'>: <function no_trycast_sql>, <class 'sqlglot.expressions.temporal.TsOrDsAdd'>: <function date_add_sql.<locals>.func>, <class 'sqlglot.expressions.temporal.TsOrDsDiff'>: <function MySQLGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.TsOrDsToDate'>: <function _ts_or_ds_to_date_sql>, <class 'sqlglot.expressions.string.Unicode'>: <function MySQLGenerator.<lambda>>, <class 'sqlglot.expressions.temporal.UnixToTime'>: <function _unix_to_time_sql>, <class 'sqlglot.expressions.aggregate.VariancePop'>: <function rename_func.<locals>.<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>}
UNSIGNED_TYPE_MAPPING: ClassVar = {<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'}
TIMESTAMP_TYPE_MAPPING: ClassVar = {<DType.DATETIME2: 'DATETIME2'>: 'DATETIME', <DType.SMALLDATETIME: 'SMALLDATETIME'>: 'DATETIME', <DType.TIMESTAMP: 'TIMESTAMP'>: 'DATETIME', <DType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>: 'DATETIME', <DType.TIMESTAMPTZ: 'TIMESTAMPTZ'>: 'TIMESTAMP', <DType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>: 'TIMESTAMP'}
TYPE_MAPPING: ClassVar = {<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'>: 'DATETIME', <DType.TIMESTAMPNTZ: 'TIMESTAMPNTZ'>: 'DATETIME', <DType.TIMESTAMPTZ: 'TIMESTAMPTZ'>: 'TIMESTAMP', <DType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>: 'TIMESTAMP'}
PROPERTIES_LOCATION: ClassVar = {<class 'sqlglot.expressions.properties.AggregateKeyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AllowedValuesProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AlgorithmProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ApiProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ApplicationProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.AutoIncrementProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AutoRefreshProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.BackupProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.BlockCompressionProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.CalledOnNullInputProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.CatalogProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.CharacterSetProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ChecksumProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.CollateProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ComputeProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.CopyGrantsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.CopyTagsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.query.Cluster'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ClusteredByProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ClusterProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DistributedByProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DuplicateKeyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DataBlocksizeProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.DatabaseProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DataDeletionProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DefinerProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DictRange'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DictProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DynamicProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DistKeyProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.DistStyleProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.EmptyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.EncodeProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.EngineProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.EnviromentProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.HandlerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ParameterStyleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ExecuteAsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ExternalProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.FallbackProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.FileFormatProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.FreespaceProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.GlobalProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.HeapProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.HybridProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.InheritsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.IcebergProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.IgnoreGrantsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.IncludeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.InteractiveProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.IsolatedLoadingProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.JournalProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.LanguageProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LikeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LocationProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LockProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LockingProperty'>: <PropertiesLocation.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.properties.LogProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.MaskingProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.MaterializedProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.MergeBlockRatioProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.ModuleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.NetworkProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.NoPrimaryIndexProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.OnProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.OnCommitProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.OptionsProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.query.Order'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.OutputModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.PartitionedByProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.PartitionedOfProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.PhysicalProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.constraints.PrimaryKey'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.Property'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RefreshTriggerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RemoteWithConnectionModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ReturnsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RollupProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.RowAccessProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.RowFormatProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RowFormatDelimitedProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RowFormatSerdeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SampleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SchemaCommentProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SecureProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.SecurityIntegrationProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.SerdeProperties'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ddl.Set'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SettingsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SetProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.SetConfigProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SharingProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.ddl.SequenceProperties'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.ddl.TriggerProperties'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.SortKeyProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.SqlReadWriteProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SqlSecurityProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StabilityProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StorageHandlerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StorageProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.StreamingTableProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.StrictProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.Tags'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.TableSpaceProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.TemporaryProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ToTableProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.TransientProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.TransformModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ddl.MergeTreeTTL'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.UnloggedProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.UsingProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.UsingTemplateProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ViewAttributeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.VirtualProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.VolatileProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.WithDataProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.WithJournalTableProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.WithProcedureOptions'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithSchemaBindingProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithSystemVersioningProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithoutRowidProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.ForceProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.PartitionByRangeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.PartitionByListProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>}
LIMIT_FETCH = 'LIMIT'
LIMIT_ONLY_LITERALS = True
CHAR_CAST_MAPPING: ClassVar = {<DType.LONGTEXT: 'LONGTEXT'>: 'CHAR', <DType.LONGBLOB: 'LONGBLOB'>: 'CHAR', <DType.MEDIUMBLOB: 'MEDIUMBLOB'>: 'CHAR', <DType.MEDIUMTEXT: 'MEDIUMTEXT'>: 'CHAR', <DType.TEXT: 'TEXT'>: 'CHAR', <DType.TINYBLOB: 'TINYBLOB'>: 'CHAR', <DType.TINYTEXT: 'TINYTEXT'>: 'CHAR', <DType.VARCHAR: 'VARCHAR'>: 'CHAR'}
SIGNED_CAST_MAPPING: ClassVar = {<DType.BIGINT: 'BIGINT'>: 'SIGNED', <DType.BOOLEAN: 'BOOLEAN'>: 'SIGNED', <DType.INT: 'INT'>: 'SIGNED', <DType.SMALLINT: 'SMALLINT'>: 'SIGNED', <DType.TINYINT: 'TINYINT'>: 'SIGNED', <DType.MEDIUMINT: 'MEDIUMINT'>: 'SIGNED'}
CAST_MAPPING: ClassVar = {<DType.LONGTEXT: 'LONGTEXT'>: 'CHAR', <DType.LONGBLOB: 'LONGBLOB'>: 'CHAR', <DType.MEDIUMBLOB: 'MEDIUMBLOB'>: 'CHAR', <DType.MEDIUMTEXT: 'MEDIUMTEXT'>: 'CHAR', <DType.TEXT: 'TEXT'>: 'CHAR', <DType.TINYBLOB: 'TINYBLOB'>: 'CHAR', <DType.TINYTEXT: 'TINYTEXT'>: 'CHAR', <DType.VARCHAR: 'VARCHAR'>: 'CHAR', <DType.BIGINT: 'BIGINT'>: 'SIGNED', <DType.BOOLEAN: 'BOOLEAN'>: 'SIGNED', <DType.INT: 'INT'>: 'SIGNED', <DType.SMALLINT: 'SMALLINT'>: 'SIGNED', <DType.TINYINT: 'TINYINT'>: 'SIGNED', <DType.MEDIUMINT: 'MEDIUMINT'>: 'SIGNED', <DType.UBIGINT: 'UBIGINT'>: 'UNSIGNED'}
TIMESTAMP_FUNC_TYPES: ClassVar = {<DType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <DType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>}
RESERVED_KEYWORDS = {'precision', 'real', 'sqlwarning', 'inout', 'master_ssl_verify_server_cert', 'float', 'purge', 'system', 'references', 'utc_time', 'desc', 'where', 'char', 'lock', 'index', 'virtual', 'int1', 'database', 'read_write', 'restrict', 'schema', 'day_second', 'decimal', 'asensitive', 'longblob', 'binary', 'year_month', 'as', 'rows', 'cross', 'load', 'varying', 'order', 'null', 'check', 'starting', 'window', 'replace', 'spatial', 'mod', 'varbinary', 'empty', 'loop', 'ntile', 'of', 'by', 'hour_second', 'int8', 'into', 'grant', 'io_after_gtids', 'sqlexception', 'lateral', 'mediumtext', 'character', 'insert', 'enclosed', 'localtimestamp', 'low_priority', 'integer', 'sensitive', 'sqlstate', 'day_hour', 'to', 'using', 'int2', 'from', 'continue', 'int', 'long', 'master_bind', 'inner', 'recursive', 'exit', 'reads', 'unsigned', 'cume_dist', 'out', 'high_priority', 'release', 'natural', 'select', 'sql_calc_found_rows', 'generated', 'option', 'terminated', 'regexp', 'true', 'cube', 'get', 'lines', 'lead', 'on', 'div', 'like', 'cursor', 'and', 'separator', 'alter', 'rlike', 'escaped', 'dense_rank', 'tinyblob', 'show', 'between', 'zerofill', 'key', 'except', 'leave', 'foreign', 'varchar', 'float8', 'create', 'insensitive', 'return', 'range', 'with', 'keys', 'groups', 'dec', 'all', 'mediumblob', 'current_date', 'for', 'update', 'union', 'schemas', 'numeric', 'cascade', 'signal', 'rename', 'write', 'rank', 'hour_minute', 'second_microsecond', 'or', 'intersect', 'int4', 'is', 'last_value', 'outer', 'both', 'stored', 'analyze', 'modifies', 'trigger', 'call', 'distinct', 'percent_rank', 'current_timestamp', 'dual', 'distinctrow', 'localtime', 'asc', 'column', 'no_write_to_binlog', 'sql_big_result', 'ignore', 'elseif', 'maxvalue', 'leading', 'kill', 'deterministic', 'bigint', 'iterate', 'read', 'right', 'optimize', 'lag', 'first_value', 'day_microsecond', 'values', 'utc_timestamp', 'function', 'having', 'procedure', 'tinyint', 'false', 'revoke', 'unique', 'nth_value', 'left', 'partition', 'repeat', 'trailing', 'declare', 'double', 'float4', 'then', 'delayed', 'smallint', 'int3', 'require', 'tinytext', 'undo', 'infile', 'limit', 'hour_microsecond', 'explain', 'set', 'sql', 'delete', 'optionally', 'minute_second', 'utc_date', 'describe', 'exists', 'when', 'in', 'join', 'current_user', 'collate', 'varcharacter', 'accessible', 'fetch', 'middleint', 'straight_join', 'longtext', 'linear', 'before', 'databases', 'outfile', 'convert', 'each', 'resignal', 'io_before_gtids', 'minute_microsecond', 'primary', 'condition', 'unlock', 'fulltext', 'blob', 'use', 'while', 'json_table', 'else', 'usage', 'case', 'xor', 'change', 'match', 'not', 'sql_small_result', 'constraint', 'group', 'grouping', 'specific', 'optimizer_costs', 'if', 'current_time', 'table', 'interval', 'over', 'force', 'day_minute', 'row', 'row_number', 'mediumint', 'drop', 'add', 'default', 'ssl'}
SQL_SECURITY_VIEW_LOCATION: ClassVar = <PropertiesLocation.POST_CREATE: 'POST_CREATE'>
def makeinterval_sql( self: MySQLGenerator, expression: sqlglot.expressions.temporal.MakeInterval) -> str:
621    def makeinterval_sql(self: MySQLGenerator, expression: exp.MakeInterval) -> str:
622        intervals: list[exp.Interval] = []
623        for arg_key, value in expression.args.items():
624            if value is None:
625                continue
626
627            if isinstance(value, exp.Kwarg):
628                unit_name = _MAKE_INTERVAL_UNIT_ALIASES.get(
629                    value.this.name.lower(), value.this.name.lower()
630                )
631                value = value.expression
632            else:
633                unit_name = arg_key
634
635            intervals.append(exp.Interval(this=value.copy(), unit=exp.var(unit_name.upper())))
636
637        if not intervals:
638            return self.function_fallback_sql(expression)
639
640        parent = expression.parent
641        sep = " - " if isinstance(parent, exp.Sub) and parent.expression is expression else " + "
642
643        return sep.join(self.sql(interval) for interval in intervals)
def locate_properties( self, properties: sqlglot.expressions.properties.Properties) -> collections.defaultdict:
645    def locate_properties(self, properties: exp.Properties) -> defaultdict:
646        locations = super().locate_properties(properties)
647
648        # MySQL puts SQL SECURITY before VIEW but after the schema for functions/procedures
649        if isinstance(create := properties.parent, exp.Create) and create.kind == "VIEW":
650            post_schema = locations[exp.Properties.Location.POST_SCHEMA]
651            for i, p in enumerate(post_schema):
652                if isinstance(p, exp.SqlSecurityProperty):
653                    post_schema.pop(i)
654                    locations[self.SQL_SECURITY_VIEW_LOCATION].append(p)
655                    break
656
657        return locations
def computedcolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.ComputedColumnConstraint) -> str:
659    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
660        persisted = "STORED" if expression.args.get("persisted") else "VIRTUAL"
661        return f"GENERATED ALWAYS AS ({self.sql(expression.this.unnest())}) {persisted}"
def array_sql(self, expression: sqlglot.expressions.array.Array) -> str:
663    def array_sql(self, expression: exp.Array) -> str:
664        self.unsupported("Arrays are not supported by MySQL")
665        return self.function_fallback_sql(expression)
def arraycontainsall_sql(self, expression: sqlglot.expressions.array.ArrayContainsAll) -> str:
667    def arraycontainsall_sql(self, expression: exp.ArrayContainsAll) -> str:
668        self.unsupported("Array operations are not supported by MySQL")
669        return self.function_fallback_sql(expression)
def arraycontainedby_sql(self, expression: sqlglot.expressions.array.ArrayContainedBy) -> str:
671    def arraycontainedby_sql(self, expression: exp.ArrayContainedBy) -> str:
672        self.unsupported("Array operations are not supported by MySQL")
673        return self.function_fallback_sql(expression)
def dpipe_sql(self, expression: sqlglot.expressions.core.DPipe) -> str:
675    def dpipe_sql(self, expression: exp.DPipe) -> str:
676        return self.func("CONCAT", *expression.flatten())
def extract_sql(self, expression: sqlglot.expressions.temporal.Extract) -> str:
678    def extract_sql(self, expression: exp.Extract) -> str:
679        unit = expression.name
680        if unit and unit.lower() == "epoch":
681            return self.func("UNIX_TIMESTAMP", expression.expression)
682
683        return super().extract_sql(expression)
def datatype_sql(self, expression: sqlglot.expressions.datatypes.DataType) -> str:
685    def datatype_sql(self, expression: exp.DataType) -> str:
686        if (
687            self.VARCHAR_REQUIRES_SIZE
688            and expression.is_type(exp.DType.VARCHAR)
689            and not expression.expressions
690        ):
691            # `VARCHAR` must always have a size - if it doesn't, we always generate `TEXT`
692            return "TEXT"
693
694        # https://dev.mysql.com/doc/refman/8.0/en/numeric-type-syntax.html
695        result = super().datatype_sql(expression)
696        if expression.this in self.UNSIGNED_TYPE_MAPPING:
697            result = f"{result} UNSIGNED"
698
699        return result
def jsonarraycontains_sql(self, expression: sqlglot.expressions.json.JSONArrayContains) -> str:
701    def jsonarraycontains_sql(self, expression: exp.JSONArrayContains) -> str:
702        return f"{self.sql(expression, 'this')} MEMBER OF({self.sql(expression, 'expression')})"
def cast_sql( self, expression: sqlglot.expressions.functions.Cast, safe_prefix: str | None = None) -> str:
704    def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str:
705        if expression.to.this in self.TIMESTAMP_FUNC_TYPES:
706            return self.func("TIMESTAMP", expression.this)
707
708        to = self.CAST_MAPPING.get(expression.to.this)
709
710        if to:
711            expression.to.set("this", to)
712        return super().cast_sql(expression, safe_prefix=safe_prefix)
def show_sql(self, expression: sqlglot.expressions.ddl.Show) -> str:
714    def show_sql(self, expression: exp.Show) -> str:
715        this = f" {expression.name}"
716        full = " FULL" if expression.args.get("full") else ""
717        global_ = " GLOBAL" if expression.args.get("global_") else ""
718
719        target = self.sql(expression, "target")
720
721        # SHOW CREATE ... takes a possibly qualified name, it has no FROM clause
722        # https://dev.mysql.com/doc/refman/8.4/en/show-create-table.html
723        if expression.name.startswith("CREATE") and (db_id := self.sql(expression, "db")):
724            target = f"{db_id}.{target}"
725            db = ""
726        else:
727            db = self._prefixed_sql("FROM", expression, "db")
728
729        target = f" {target}" if target else ""
730        if expression.name in ("COLUMNS", "INDEX"):
731            target = f" FROM{target}"
732        elif expression.name == "GRANTS":
733            target = f" FOR{target}"
734        elif expression.name in ("LINKS", "PARTITIONS"):
735            target = f" ON{target}" if target else ""
736        elif expression.name == "PROJECTIONS":
737            target = f" ON TABLE{target}" if target else ""
738
739        like = self._prefixed_sql("LIKE", expression, "like")
740        where = self.sql(expression, "where")
741
742        types = self.expressions(expression, key="types")
743        types = f" {types}" if types else types
744        query = self._prefixed_sql("FOR QUERY", expression, "query")
745
746        if expression.name == "PROFILE":
747            offset = self._prefixed_sql("OFFSET", expression, "offset")
748            limit = self._prefixed_sql("LIMIT", expression, "limit")
749        else:
750            offset = ""
751            limit = self._oldstyle_limit_sql(expression)
752
753        log = self._prefixed_sql("IN", expression, "log")
754        position = self._prefixed_sql("FROM", expression, "position")
755
756        channel = self._prefixed_sql("FOR CHANNEL", expression, "channel")
757
758        if expression.name == "ENGINE":
759            mutex_or_status = " MUTEX" if expression.args.get("mutex") else " STATUS"
760        else:
761            mutex_or_status = ""
762
763        for_table = self._prefixed_sql("FOR TABLE", expression, "for_table")
764        for_group = self._prefixed_sql("FOR GROUP", expression, "for_group")
765        for_user = self._prefixed_sql("FOR USER", expression, "for_user")
766        for_role = self._prefixed_sql("FOR ROLE", expression, "for_role")
767        into_outfile = self._prefixed_sql("INTO OUTFILE", expression, "into_outfile")
768        json = " JSON" if expression.args.get("json") else ""
769
770        return f"SHOW{full}{global_}{this}{json}{target}{for_table}{types}{db}{query}{log}{position}{channel}{mutex_or_status}{like}{where}{offset}{limit}{for_group}{for_user}{for_role}{into_outfile}"
def alterrename_sql( self, expression: sqlglot.expressions.ddl.AlterRename, include_to: bool = True) -> str:
772    def alterrename_sql(self, expression: exp.AlterRename, include_to: bool = True) -> str:
773        """To avoid TO keyword in ALTER ... RENAME statements.
774        It's moved from Doris, because it's the same for all MySQL, Doris, and StarRocks.
775        """
776        return super().alterrename_sql(expression, include_to=False)

To avoid TO keyword in ALTER ... RENAME statements. It's moved from Doris, because it's the same for all MySQL, Doris, and StarRocks.

def altercolumn_sql(self, expression: sqlglot.expressions.ddl.AlterColumn) -> str:
778    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
779        dtype = self.sql(expression, "dtype")
780        if not dtype:
781            return super().altercolumn_sql(expression)
782
783        if expression.args.get("exists"):
784            self.unsupported("ALTER COLUMN IF EXISTS is not supported by this dialect")
785
786        this = self.sql(expression, "this")
787        null_constraint = self._alter_column_null_constraint_sql(expression)
788        return f"MODIFY COLUMN {this} {dtype}{null_constraint}"
def timestamptrunc_sql(self, expression: sqlglot.expressions.temporal.TimestampTrunc) -> str:
802    def timestamptrunc_sql(self, expression: exp.TimestampTrunc) -> str:
803        unit = expression.args.get("unit")
804        if isinstance(unit, exp.WeekStart):
805            unit = exp.var(self.weekstart_name(unit))
806
807        # Pick an old-enough date to avoid negative timestamp diffs
808        start_ts = "'0000-01-01 00:00:00'"
809
810        # Source: https://stackoverflow.com/a/32955740
811        timestamp_diff = build_date_delta(exp.TimestampDiff)([unit, start_ts, expression.this])
812        interval = exp.Interval(this=timestamp_diff, unit=unit)
813        dateadd = build_date_delta_with_interval(exp.DateAdd)([start_ts, interval])
814
815        return self.sql(dateadd)
def converttimezone_sql(self, expression: sqlglot.expressions.temporal.ConvertTimezone) -> str:
817    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
818        from_tz = expression.args.get("source_tz")
819        to_tz = expression.args.get("target_tz")
820        dt = expression.args.get("timestamp")
821
822        return self.func("CONVERT_TZ", dt, from_tz, to_tz)
def attimezone_sql(self, expression: sqlglot.expressions.core.AtTimeZone) -> str:
824    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
825        self.unsupported("AT TIME ZONE is not supported by MySQL")
826        return self.sql(expression.this)
def isascii_sql(self, expression: sqlglot.expressions.string.IsAscii) -> str:
828    def isascii_sql(self, expression: exp.IsAscii) -> str:
829        return f"REGEXP_LIKE({self.sql(expression.this)}, '^[[:ascii:]]*$')"
def ignorenulls_sql(self, expression: sqlglot.expressions.core.IgnoreNulls) -> str:
831    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
832        # https://dev.mysql.com/doc/refman/8.4/en/window-function-descriptions.html
833        self.unsupported("MySQL does not support IGNORE NULLS.")
834        return self.sql(expression.this)
@unsupported_args('this')
def currentschema_sql(self, expression: sqlglot.expressions.functions.CurrentSchema) -> str:
836    @unsupported_args("this")
837    def currentschema_sql(self, expression: exp.CurrentSchema) -> str:
838        return self.func("SCHEMA")
def partition_sql(self, expression: sqlglot.expressions.query.Partition) -> str:
840    def partition_sql(self, expression: exp.Partition) -> str:
841        parent = expression.parent
842        if isinstance(parent, (exp.PartitionByRangeProperty, exp.PartitionByListProperty)):
843            return self.expressions(expression, flat=True)
844        return super().partition_sql(expression)
def partitionbyrangeproperty_sql( self, expression: sqlglot.expressions.properties.PartitionByRangeProperty) -> str:
853    def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str:
854        return self._partition_by_sql(expression, "RANGE")
def partitionbylistproperty_sql( self, expression: sqlglot.expressions.properties.PartitionByListProperty) -> str:
856    def partitionbylistproperty_sql(self, expression: exp.PartitionByListProperty) -> str:
857        return self._partition_by_sql(expression, "LIST")
def partitionlist_sql(self, expression: sqlglot.expressions.properties.PartitionList) -> str:
859    def partitionlist_sql(self, expression: exp.PartitionList) -> str:
860        name = self.sql(expression, "this")
861        values = self.expressions(expression, flat=True)
862        return f"PARTITION {name} VALUES IN ({values})"
def partitionrange_sql(self, expression: sqlglot.expressions.query.PartitionRange) -> str:
864    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
865        name = self.sql(expression, "this")
866        values = self.expressions(expression, flat=True)
867        return f"PARTITION {name} VALUES LESS THAN ({values})"
Inherited Members
sqlglot.generator.Generator
Generator
WINDOW_FUNCS_WITH_NULL_ORDERING
WINDOW_FUNCS_REQUIRING_ORDER
IGNORE_NULLS_IN_FUNC
IGNORE_NULLS_BEFORE_ORDER
EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
CREATE_FUNCTION_RETURN_AS
MATCHED_BY_SOURCE
SUPPORTS_MERGE_WHERE
MERGE_SCHEMA_EVOLUTION_MIN_VERSION
MERGE_ALL_BY_NAME
SINGLE_STRING_INTERVAL
AUTO_REFRESH_BARE_INTERVALS
RENAME_TABLE_WITH_DB
GROUPINGS_SEP
SUPPORTS_GROUPING_SETS_AS_SUFFIX
INDEX_ON
INOUT_SEPARATOR
DIRECTED_JOINS
SUPPORTS_NEAREST_JOIN
SUPPORTS_MATCH_CONDITION
MATCH_CONDITION_IN_ON
QUERY_HINTS
IS_BOOL_ALLOWED
SAFE_INT_DIVISION
LIMIT_IS_TOP
RETURNING_END
EXTRACT_ALLOWS_QUOTES
TZ_TO_WITH_TIME_ZONE
ALTER_TABLE_INCLUDE_COLUMN_KEYWORD
ALTER_TABLE_ADD_COLUMNS_WRAPPED
UNNEST_WITH_ORDINALITY
SEMI_ANTI_JOIN_WITH_SIDE
COMPUTED_COLUMN_WITH_TYPE
SUPPORTS_TABLE_COPY
TABLESAMPLE_REQUIRES_PARENS
TABLESAMPLE_SIZE_IS_ROWS
TABLESAMPLE_KEYWORDS
TABLESAMPLE_WITH_METHOD
TABLESAMPLE_SEED_KEYWORD
HISTORICAL_DATA_POST_ALIAS
COLLATE_IS_FUNC
DATA_TYPE_SPECIFIERS_ALLOWED
ENSURE_BOOLS
CTE_RECURSIVE_KEYWORD_REQUIRED
SUPPORTS_SINGLE_ARG_CONCAT
SUPPORTS_TABLE_ALIAS_COLUMNS
SUPPORTS_NAMED_CTE_COLUMNS
UNPIVOT_ALIASES_ARE_IDENTIFIERS
PIVOT_ALIAS_WITH_AS
INSERT_OVERWRITE
SUPPORTS_SELECT_INTO
SUPPORTS_OPTIMIZE
SUPPORTS_EXECUTE_IMMEDIATE
SUPPORTS_UNLOGGED_TABLES
SUPPORTS_CREATE_TABLE_LIKE
SUPPORTS_ALTER_COLUMN_IF_EXISTS
LIKE_PROPERTY_INSIDE_SCHEMA
MULTI_ARG_DISTINCT
SUPPORTS_NESTED_JSON_SELECT
JSON_PATH_SINGLE_QUOTE_ESCAPE
JSON_PATH_KEY_QUOTED_FORCES_BRACKETS
SUPPORTED_JSON_PATH_PARTS
CAN_IMPLEMENT_ARRAY_ANY
SUPPORTS_WINDOW_EXCLUDE
SET_OP_MODIFIERS
SET_OP_LIMITS
SET_OP_PARENTHESIZED_OPERANDS
COPY_PARAMS_ARE_WRAPPED
COPY_PARAMS_EQ_REQUIRED
COPY_HAS_INTO_KEYWORD
UNICODE_SUBSTITUTE
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
DAYOFWEEK_ZERO_BASED
VARIANCE_RETURNS_ZERO_ON_SINGLE_VALUE
ALTER_SET_TYPE
ARRAY_SIZE_DIM_REQUIRED
SUPPORTS_MULTI_ARG_CHR
SUPPORTS_BETWEEN_FLAGS
SUPPORTS_LIKE_QUANTIFIERS
MATCH_AGAINST_TABLE_PREFIX
SET_ASSIGNMENT_REQUIRES_VARIABLE_KEYWORD
DECLARE_DEFAULT_ASSIGNMENT
STAR_EXCLUDE_REQUIRES_DERIVED_TABLE
SUPPORTS_DROP_ALTER_ICEBERG_PROPERTY
UNSUPPORTED_TYPES
TYPE_PARAM_SETTINGS
TIME_PART_SINGULARS
TOKEN_MAPPING
STRUCT_DELIMITER
PARAMETER_TOKEN
NAMED_PLACEHOLDER_TOKEN
EXPRESSION_PRECEDES_PROPERTIES_CREATABLES
WITH_SEPARATED_COMMENTS
EXCLUDE_COMMENTS
UNWRAPPED_INTERVAL_VALUES
PARAMETERIZABLE_TEXT_TYPES
EXPRESSIONS_WITHOUT_NESTED_CTES
RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS
MOD_OPERATOR
BARE_OPERATORS
MOD_PAREN_PARENT_TYPES
SAFE_JSON_PATH_KEY_RE
SENTINEL_LINE_BREAK
pretty
identify
normalize
pad
unsupported_level
max_unsupported
leading_comma
max_text_width
comments
dialect
normalize_functions
unsupported_messages
generate
preprocess
unsupported
sep
seg
sanitize_comment
maybe_comment
wrap
no_identify
normalize_func
indent
sql
uncache_sql
cache_sql
characterset_sql
column_parts
column_sql
pseudocolumn_sql
columnposition_sql
columndef_sql
columnconstraint_sql
autoincrementcolumnconstraint_sql
compresscolumnconstraint_sql
generatedasidentitycolumnconstraint_sql
generatedasrowcolumnconstraint_sql
periodforsystemtimeconstraint_sql
notnullcolumnconstraint_sql
primarykeycolumnconstraint_sql
uniquecolumnconstraint_sql
inoutcolumnconstraint_sql
createable_sql
create_sql
sequenceproperties_sql
triggerproperties_sql
triggerreferencing_sql
triggerevent_sql
clone_sql
describe_sql
heredoc_sql
prepend_ctes
with_sql
cte_sql
tablealias_sql
bitstring_sql
hexstring_sql
bytestring_sql
unicodestring_sql
rawstring_sql
datatypeparam_sql
datatype_param_bound_limiter
directory_sql
delete_sql
drop_sql
set_operation
set_operations
fetch_sql
limitoptions_sql
filter_sql
per_sql
hint_sql
indexparameters_sql
index_sql
dynamicidentifier_sql
identifier_sql
hex_sql
lowerhex_sql
inputoutputformat_sql
national_sql
properties_sql
root_properties
properties
with_properties
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
lockingstatement_sql
withdataproperty_sql
withsystemversioningproperty_sql
insert_sql
introducer_sql
kill_sql
pseudotype_sql
objectidentifier_sql
onconflict_sql
returning_sql
rowformatdelimitedproperty_sql
withtablehint_sql
indextablehint_sql
historicaldata_sql
table_parts
table_sql
tableargument_sql
tablefromrows_sql
tablesample_sql
pivot_sql
version_sql
tuple_sql
update_sql
values_sql
var_sql
into_sql
from_sql
groupingsets_sql
rollup_sql
rollupindex_sql
rollupproperty_sql
cube_sql
group_sql
having_sql
connectto_sql
disconnect_sql
connect_sql
prior_sql
join_sql
nearest_sql
lambda_sql
lateral_op
lateral_sql
limit_sql
offset_sql
setitem_sql
set_sql
queryband_sql
pragma_sql
lock_sql
literal_sql
escape_str
loaddata_sql
null_sql
boolean_sql
booland_sql
boolor_sql
order_sql
withfill_sql
cluster_sql
clusterproperty_sql
distribute_sql
sort_sql
ordered_sql
matchrecognizemeasure_sql
matchrecognize_sql
query_modifiers
options_modifier
forclause_sql
queryoption_sql
offset_limit_modifiers
after_limit_modifiers
select_sql
schema_sql
schema_columns_sql
star_sql
parameter_sql
sessionparameter_sql
placeholder_sql
subquery_sql
qualify_sql
unnest_sql
prewhere_sql
where_sql
window_sql
partition_by_sql
partitionbyexcluding_sql
windowspec_sql
withingroup_sql
between_sql
bracket_offset_expressions
bracket_sql
all_sql
any_sql
exists_sql
case_sql
constraint_sql
nextvaluefor_sql
dayofweek_sql
extract_date_part
trim_sql
convert_concat_args
concat_sql
concatws_sql
check_sql
foreignkey_sql
primarykey_sql
timeserieskey_sql
if_sql
matchagainst_sql
jsonkeyvalue_sql
jsonpath_sql
json_path_part
format_sql
formatjson_sql
formatphrase_sql
teradataconversion_sql
teradatatitle_sql
teradatanamed_sql
jsonarray_sql
jsonarrayagg_sql
jsoncolumndef_sql
jsonschema_sql
jsontable_sql
openjsoncolumndef_sql
openjson_sql
in_sql
in_unnest_op
interval_sql
return_sql
reference_sql
anonymous_sql
paren_sql
pos_sql
neg_sql
not_sql
alias_sql
pivotalias_sql
aliases_sql
atindex_sql
fromtimezone_sql
fromiso8601date_sql
fromiso8601timestamp_sql
fromiso8601timestampnanos_sql
add_sql
and_sql
or_sql
xor_sql
connector_sql
bitwiseand_sql
bitwiseleftshift_sql
bitwisenot_sql
bitwiseor_sql
bitwiserightshift_sql
bitwisexor_sql
strtotime_sql
strtodate_sql
parsedatetime_sql
currentdate_sql
collate_sql
command_sql
optimize_sql
comment_sql
mergetreettlaction_sql
mergetreettl_sql
transaction_sql
commit_sql
rollback_sql
modifycolumn_sql
alterindex_sql
alterdiststyle_sql
altersortkey_sql
renamecolumn_sql
alterset_sql
alter_sql
altersession_sql
add_column_sql
droppartition_sql
dropprimarykey_sql
addconstraint_sql
replacecolumns_sql
addpartition_sql
distinct_sql
respectnulls_sql
havingmax_sql
intdiv_sql
nullif_zero_divisor
div_sql
safedivide_sql
overlaps_sql
distance_sql
distancend_sql
dot_sql
nestedjsonselect_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
function_name
func
format_args
too_wide
format_time
expressions
op_expressions
naked_property
tag_sql
token_sql
userdefinedfunction_sql
macrooverloads_sql
macrooverload_sql
joinhint_sql
kwarg_sql
when_sql
whens_sql
merge_sql
tochar_sql
tonumber_sql
dictproperty_sql
dictrange_sql
dictsubproperty_sql
aggregatekeyproperty_sql
duplicatekeyproperty_sql
uniquekeyproperty_sql
distributedbyproperty_sql
oncluster_sql
clusteredbyproperty_sql
anyvalue_sql
querytransform_sql
indexconstraintoption_sql
checkcolumnconstraint_sql
indexcolumnconstraint_sql
nvl2_sql
nthvalue_sql
comprehension_sql
columnprefix_sql
opclass_sql
predict_sql
generateembedding_sql
generatetext_sql
generatetable_sql
generatebool_sql
generateint_sql
generatedouble_sql
mltranslate_sql
mlforecast_sql
aiforecast_sql
featuresattime_sql
vectorsearch_sql
forin_sql
refresh_sql
toarray_sql
tsordstotime_sql
tsordstotimestamp_sql
tsordstodatetime_sql
tsordstodate_sql
unixdate_sql
lastday_sql
dateadd_sql
arrayinsert_sql
arrayany_sql
struct_sql
truncatetable_sql
convert_sql
copyparameter_sql
credentials_sql
copy_sql
semicolon_sql
datadeletionproperty_sql
maskingpolicycolumnconstraint_sql
gapfill_sql
scope_resolution
scoperesolution_sql
parsejson_sql
rand_sql
changes_sql
pad_sql
summarize_sql
explodinggenerateseries_sql
json_sql
jsonvalue_sql
skipjsoncolumn_sql
conditionalinsert_sql
multitableinserts_sql
oncondition_sql
jsonextractquote_sql
jsonexists_sql
min_sql
max_sql
arrayagg_sql
timeslice_sql
slice_sql
apply_sql
grant_sql
revoke_sql
grantprivilege_sql
grantprincipal_sql
columns_sql
overlay_sql
todouble_sql
string_sql
median_sql
overflowtruncatebehavior_sql
unixseconds_sql
arraysort_sql
variance_sql
arraysize_sql
attach_sql
detach_sql
attachoption_sql
watermarkcolumnconstraint_sql
encodeproperty_sql
includeproperty_sql
xmlelement_sql
xmlkeyvalueoption_sql
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
liststage_sql
get_put_sql
translatecharacters_sql
decodecase_sql
semanticview_sql
getextract_sql
datefromunixdate_sql
space_sql
buildproperty_sql
refreshtriggerproperty_sql
modelattribute_sql
directorystage_sql
uuid_sql
initcap_sql
localtime_sql
localtimestamp_sql
weekstart_name
weekstart_sql
datetrunc_sql
chr_sql
weightstring_sql
block_sql
functionspecification_sql
storedprocedure_sql
ifblock_sql
casestatement_sql
whileblock_sql
loopblock_sql
repeatblock_sql
leave_sql
iterate_sql
execute_sql
executesql_sql
executeimmediate_sql
altermodifysqlsecurity_sql
usingproperty_sql
renameindex_sql