sqlglot.dialects.mysql API documentation

Edit on GitHub

# sqlglot.dialects.mysql

View Source

      1from __future__ import annotations
      2
      3import typing as t
      4
      5from sqlglot import exp, generator, parser, tokens, transforms
      6from sqlglot.dialects.dialect import (
      7    Dialect,
      8    arrow_json_extract_scalar_sql,
      9    date_add_interval_sql,
     10    datestrtodate_sql,
     11    format_time_lambda,
     12    isnull_to_is_null,
     13    json_keyvalue_comma_sql,
     14    locate_to_strposition,
     15    max_or_greatest,
     16    min_or_least,
     17    no_ilike_sql,
     18    no_paren_current_date_sql,
     19    no_pivot_sql,
     20    no_tablesample_sql,
     21    no_trycast_sql,
     22    parse_date_delta_with_interval,
     23    rename_func,
     24    strposition_to_locate_sql,
     25)
     26from sqlglot.helper import seq_get
     27from sqlglot.tokens import TokenType
     28
     29
     30def _show_parser(*args: t.Any, **kwargs: t.Any) -> t.Callable[[MySQL.Parser], exp.Show]:
     31    def _parse(self: MySQL.Parser) -> exp.Show:
     32        return self._parse_show_mysql(*args, **kwargs)
     33
     34    return _parse
     35
     36
     37def _date_trunc_sql(self: MySQL.Generator, expression: exp.DateTrunc) -> str:
     38    expr = self.sql(expression, "this")
     39    unit = expression.text("unit")
     40
     41    if unit == "day":
     42        return f"DATE({expr})"
     43
     44    if unit == "week":
     45        concat = f"CONCAT(YEAR({expr}), ' ', WEEK({expr}, 1), ' 1')"
     46        date_format = "%Y %u %w"
     47    elif unit == "month":
     48        concat = f"CONCAT(YEAR({expr}), ' ', MONTH({expr}), ' 1')"
     49        date_format = "%Y %c %e"
     50    elif unit == "quarter":
     51        concat = f"CONCAT(YEAR({expr}), ' ', QUARTER({expr}) * 3 - 2, ' 1')"
     52        date_format = "%Y %c %e"
     53    elif unit == "year":
     54        concat = f"CONCAT(YEAR({expr}), ' 1 1')"
     55        date_format = "%Y %c %e"
     56    else:
     57        self.unsupported(f"Unexpected interval unit: {unit}")
     58        return f"DATE({expr})"
     59
     60    return f"STR_TO_DATE({concat}, '{date_format}')"
     61
     62
     63# All specifiers for time parts (as opposed to date parts)
     64# https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-format
     65TIME_SPECIFIERS = {"f", "H", "h", "I", "i", "k", "l", "p", "r", "S", "s", "T"}
     66
     67
     68def _has_time_specifier(date_format: str) -> bool:
     69    i = 0
     70    length = len(date_format)
     71
     72    while i < length:
     73        if date_format[i] == "%":
     74            i += 1
     75            if i < length and date_format[i] in TIME_SPECIFIERS:
     76                return True
     77        i += 1
     78    return False
     79
     80
     81def _str_to_date(args: t.List) -> exp.StrToDate | exp.StrToTime:
     82    mysql_date_format = seq_get(args, 1)
     83    date_format = MySQL.format_time(mysql_date_format)
     84    this = seq_get(args, 0)
     85
     86    if mysql_date_format and _has_time_specifier(mysql_date_format.name):
     87        return exp.StrToTime(this=this, format=date_format)
     88
     89    return exp.StrToDate(this=this, format=date_format)
     90
     91
     92def _str_to_date_sql(
     93    self: MySQL.Generator, expression: exp.StrToDate | exp.StrToTime | exp.TsOrDsToDate
     94) -> str:
     95    date_format = self.format_time(expression)
     96    return f"STR_TO_DATE({self.sql(expression.this)}, {date_format})"
     97
     98
     99def _trim_sql(self: MySQL.Generator, expression: exp.Trim) -> str:
    100    target = self.sql(expression, "this")
    101    trim_type = self.sql(expression, "position")
    102    remove_chars = self.sql(expression, "expression")
    103
    104    # Use TRIM/LTRIM/RTRIM syntax if the expression isn't mysql-specific
    105    if not remove_chars:
    106        return self.trim_sql(expression)
    107
    108    trim_type = f"{trim_type} " if trim_type else ""
    109    remove_chars = f"{remove_chars} " if remove_chars else ""
    110    from_part = "FROM " if trim_type or remove_chars else ""
    111    return f"TRIM({trim_type}{remove_chars}{from_part}{target})"
    112
    113
    114def _date_add_sql(
    115    kind: str,
    116) -> t.Callable[[MySQL.Generator, exp.Expression], str]:
    117    def func(self: MySQL.Generator, expression: exp.Expression) -> str:
    118        this = self.sql(expression, "this")
    119        unit = expression.text("unit").upper() or "DAY"
    120        return (
    121            f"DATE_{kind}({this}, {self.sql(exp.Interval(this=expression.expression, unit=unit))})"
    122        )
    123
    124    return func
    125
    126
    127def _ts_or_ds_to_date_sql(self: MySQL.Generator, expression: exp.TsOrDsToDate) -> str:
    128    time_format = expression.args.get("format")
    129    if time_format:
    130        return _str_to_date_sql(self, expression)
    131    return f"DATE({self.sql(expression, 'this')})"
    132
    133
    134def _remove_ts_or_ds_to_date(
    135    to_sql: t.Optional[t.Callable[[MySQL.Generator, exp.Expression], str]] = None,
    136    args: t.Tuple[str, ...] = ("this",),
    137) -> t.Callable[[MySQL.Generator, exp.Func], str]:
    138    def func(self: MySQL.Generator, expression: exp.Func) -> str:
    139        for arg_key in args:
    140            arg = expression.args.get(arg_key)
    141            if isinstance(arg, exp.TsOrDsToDate) and not arg.args.get("format"):
    142                expression.set(arg_key, arg.this)
    143
    144        return to_sql(self, expression) if to_sql else self.function_fallback_sql(expression)
    145
    146    return func
    147
    148
    149class MySQL(Dialect):
    150    # https://dev.mysql.com/doc/refman/8.0/en/identifiers.html
    151    IDENTIFIERS_CAN_START_WITH_DIGIT = True
    152
    153    TIME_FORMAT = "'%Y-%m-%d %T'"
    154    DPIPE_IS_STRING_CONCAT = False
    155    SUPPORTS_USER_DEFINED_TYPES = False
    156    SUPPORTS_SEMI_ANTI_JOIN = False
    157
    158    # https://prestodb.io/docs/current/functions/datetime.html#mysql-date-functions
    159    TIME_MAPPING = {
    160        "%M": "%B",
    161        "%c": "%-m",
    162        "%e": "%-d",
    163        "%h": "%I",
    164        "%i": "%M",
    165        "%s": "%S",
    166        "%u": "%W",
    167        "%k": "%-H",
    168        "%l": "%-I",
    169        "%T": "%H:%M:%S",
    170        "%W": "%a",
    171    }
    172
    173    class Tokenizer(tokens.Tokenizer):
    174        QUOTES = ["'", '"']
    175        COMMENTS = ["--", "#", ("/*", "*/")]
    176        IDENTIFIERS = ["`"]
    177        STRING_ESCAPES = ["'", '"', "\\"]
    178        BIT_STRINGS = [("b'", "'"), ("B'", "'"), ("0b", "")]
    179        HEX_STRINGS = [("x'", "'"), ("X'", "'"), ("0x", "")]
    180
    181        KEYWORDS = {
    182            **tokens.Tokenizer.KEYWORDS,
    183            "CHARSET": TokenType.CHARACTER_SET,
    184            "ENUM": TokenType.ENUM,
    185            "FORCE": TokenType.FORCE,
    186            "IGNORE": TokenType.IGNORE,
    187            "LOCK TABLES": TokenType.COMMAND,
    188            "LONGBLOB": TokenType.LONGBLOB,
    189            "LONGTEXT": TokenType.LONGTEXT,
    190            "MEDIUMBLOB": TokenType.MEDIUMBLOB,
    191            "TINYBLOB": TokenType.TINYBLOB,
    192            "TINYTEXT": TokenType.TINYTEXT,
    193            "MEDIUMTEXT": TokenType.MEDIUMTEXT,
    194            "MEDIUMINT": TokenType.MEDIUMINT,
    195            "MEMBER OF": TokenType.MEMBER_OF,
    196            "SEPARATOR": TokenType.SEPARATOR,
    197            "START": TokenType.BEGIN,
    198            "SIGNED": TokenType.BIGINT,
    199            "SIGNED INTEGER": TokenType.BIGINT,
    200            "UNLOCK TABLES": TokenType.COMMAND,
    201            "UNSIGNED": TokenType.UBIGINT,
    202            "UNSIGNED INTEGER": TokenType.UBIGINT,
    203            "YEAR": TokenType.YEAR,
    204            "_ARMSCII8": TokenType.INTRODUCER,
    205            "_ASCII": TokenType.INTRODUCER,
    206            "_BIG5": TokenType.INTRODUCER,
    207            "_BINARY": TokenType.INTRODUCER,
    208            "_CP1250": TokenType.INTRODUCER,
    209            "_CP1251": TokenType.INTRODUCER,
    210            "_CP1256": TokenType.INTRODUCER,
    211            "_CP1257": TokenType.INTRODUCER,
    212            "_CP850": TokenType.INTRODUCER,
    213            "_CP852": TokenType.INTRODUCER,
    214            "_CP866": TokenType.INTRODUCER,
    215            "_CP932": TokenType.INTRODUCER,
    216            "_DEC8": TokenType.INTRODUCER,
    217            "_EUCJPMS": TokenType.INTRODUCER,
    218            "_EUCKR": TokenType.INTRODUCER,
    219            "_GB18030": TokenType.INTRODUCER,
    220            "_GB2312": TokenType.INTRODUCER,
    221            "_GBK": TokenType.INTRODUCER,
    222            "_GEOSTD8": TokenType.INTRODUCER,
    223            "_GREEK": TokenType.INTRODUCER,
    224            "_HEBREW": TokenType.INTRODUCER,
    225            "_HP8": TokenType.INTRODUCER,
    226            "_KEYBCS2": TokenType.INTRODUCER,
    227            "_KOI8R": TokenType.INTRODUCER,
    228            "_KOI8U": TokenType.INTRODUCER,
    229            "_LATIN1": TokenType.INTRODUCER,
    230            "_LATIN2": TokenType.INTRODUCER,
    231            "_LATIN5": TokenType.INTRODUCER,
    232            "_LATIN7": TokenType.INTRODUCER,
    233            "_MACCE": TokenType.INTRODUCER,
    234            "_MACROMAN": TokenType.INTRODUCER,
    235            "_SJIS": TokenType.INTRODUCER,
    236            "_SWE7": TokenType.INTRODUCER,
    237            "_TIS620": TokenType.INTRODUCER,
    238            "_UCS2": TokenType.INTRODUCER,
    239            "_UJIS": TokenType.INTRODUCER,
    240            # https://dev.mysql.com/doc/refman/8.0/en/string-literals.html
    241            "_UTF8": TokenType.INTRODUCER,
    242            "_UTF16": TokenType.INTRODUCER,
    243            "_UTF16LE": TokenType.INTRODUCER,
    244            "_UTF32": TokenType.INTRODUCER,
    245            "_UTF8MB3": TokenType.INTRODUCER,
    246            "_UTF8MB4": TokenType.INTRODUCER,
    247            "@@": TokenType.SESSION_PARAMETER,
    248        }
    249
    250        COMMANDS = tokens.Tokenizer.COMMANDS - {TokenType.SHOW}
    251
    252    class Parser(parser.Parser):
    253        FUNC_TOKENS = {
    254            *parser.Parser.FUNC_TOKENS,
    255            TokenType.DATABASE,
    256            TokenType.SCHEMA,
    257            TokenType.VALUES,
    258        }
    259
    260        CONJUNCTION = {
    261            **parser.Parser.CONJUNCTION,
    262            TokenType.DAMP: exp.And,
    263            TokenType.XOR: exp.Xor,
    264            TokenType.DPIPE: exp.Or,
    265        }
    266
    267        # MySQL uses || as a synonym to the logical OR operator
    268        # https://dev.mysql.com/doc/refman/8.0/en/logical-operators.html#operator_or
    269        BITWISE = parser.Parser.BITWISE.copy()
    270        BITWISE.pop(TokenType.DPIPE)
    271
    272        TABLE_ALIAS_TOKENS = (
    273            parser.Parser.TABLE_ALIAS_TOKENS - parser.Parser.TABLE_INDEX_HINT_TOKENS
    274        )
    275
    276        RANGE_PARSERS = {
    277            **parser.Parser.RANGE_PARSERS,
    278            TokenType.MEMBER_OF: lambda self, this: self.expression(
    279                exp.JSONArrayContains,
    280                this=this,
    281                expression=self._parse_wrapped(self._parse_expression),
    282            ),
    283        }
    284
    285        FUNCTIONS = {
    286            **parser.Parser.FUNCTIONS,
    287            "DATE": lambda args: exp.TsOrDsToDate(this=seq_get(args, 0)),
    288            "DATE_ADD": parse_date_delta_with_interval(exp.DateAdd),
    289            "DATE_FORMAT": format_time_lambda(exp.TimeToStr, "mysql"),
    290            "DATE_SUB": parse_date_delta_with_interval(exp.DateSub),
    291            "INSTR": lambda args: exp.StrPosition(substr=seq_get(args, 1), this=seq_get(args, 0)),
    292            "ISNULL": isnull_to_is_null,
    293            "LOCATE": locate_to_strposition,
    294            "MONTHNAME": lambda args: exp.TimeToStr(
    295                this=exp.TsOrDsToDate(this=seq_get(args, 0)),
    296                format=exp.Literal.string("%B"),
    297            ),
    298            "STR_TO_DATE": _str_to_date,
    299            "TO_DAYS": lambda args: exp.paren(
    300                exp.DateDiff(
    301                    this=exp.TsOrDsToDate(this=seq_get(args, 0)),
    302                    expression=exp.TsOrDsToDate(this=exp.Literal.string("0000-01-01")),
    303                    unit=exp.var("DAY"),
    304                )
    305                + 1
    306            ),
    307            "DAY": lambda args: exp.Day(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    308            "DAYOFMONTH": lambda args: exp.DayOfMonth(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    309            "DAYOFWEEK": lambda args: exp.DayOfWeek(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    310            "DAYOFYEAR": lambda args: exp.DayOfYear(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    311            "MONTH": lambda args: exp.Month(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    312            "WEEK": lambda args: exp.Week(
    313                this=exp.TsOrDsToDate(this=seq_get(args, 0)), mode=seq_get(args, 1)
    314            ),
    315            "WEEKOFYEAR": lambda args: exp.WeekOfYear(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    316            "YEAR": lambda args: exp.Year(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    317        }
    318
    319        FUNCTION_PARSERS = {
    320            **parser.Parser.FUNCTION_PARSERS,
    321            "CHAR": lambda self: self._parse_chr(),
    322            "GROUP_CONCAT": lambda self: self.expression(
    323                exp.GroupConcat,
    324                this=self._parse_lambda(),
    325                separator=self._match(TokenType.SEPARATOR) and self._parse_field(),
    326            ),
    327            # https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_values
    328            "VALUES": lambda self: self.expression(
    329                exp.Anonymous, this="VALUES", expressions=[self._parse_id_var()]
    330            ),
    331        }
    332
    333        STATEMENT_PARSERS = {
    334            **parser.Parser.STATEMENT_PARSERS,
    335            TokenType.SHOW: lambda self: self._parse_show(),
    336        }
    337
    338        SHOW_PARSERS = {
    339            "BINARY LOGS": _show_parser("BINARY LOGS"),
    340            "MASTER LOGS": _show_parser("BINARY LOGS"),
    341            "BINLOG EVENTS": _show_parser("BINLOG EVENTS"),
    342            "CHARACTER SET": _show_parser("CHARACTER SET"),
    343            "CHARSET": _show_parser("CHARACTER SET"),
    344            "COLLATION": _show_parser("COLLATION"),
    345            "FULL COLUMNS": _show_parser("COLUMNS", target="FROM", full=True),
    346            "COLUMNS": _show_parser("COLUMNS", target="FROM"),
    347            "CREATE DATABASE": _show_parser("CREATE DATABASE", target=True),
    348            "CREATE EVENT": _show_parser("CREATE EVENT", target=True),
    349            "CREATE FUNCTION": _show_parser("CREATE FUNCTION", target=True),
    350            "CREATE PROCEDURE": _show_parser("CREATE PROCEDURE", target=True),
    351            "CREATE TABLE": _show_parser("CREATE TABLE", target=True),
    352            "CREATE TRIGGER": _show_parser("CREATE TRIGGER", target=True),
    353            "CREATE VIEW": _show_parser("CREATE VIEW", target=True),
    354            "DATABASES": _show_parser("DATABASES"),
    355            "ENGINE": _show_parser("ENGINE", target=True),
    356            "STORAGE ENGINES": _show_parser("ENGINES"),
    357            "ENGINES": _show_parser("ENGINES"),
    358            "ERRORS": _show_parser("ERRORS"),
    359            "EVENTS": _show_parser("EVENTS"),
    360            "FUNCTION CODE": _show_parser("FUNCTION CODE", target=True),
    361            "FUNCTION STATUS": _show_parser("FUNCTION STATUS"),
    362            "GRANTS": _show_parser("GRANTS", target="FOR"),
    363            "INDEX": _show_parser("INDEX", target="FROM"),
    364            "MASTER STATUS": _show_parser("MASTER STATUS"),
    365            "OPEN TABLES": _show_parser("OPEN TABLES"),
    366            "PLUGINS": _show_parser("PLUGINS"),
    367            "PROCEDURE CODE": _show_parser("PROCEDURE CODE", target=True),
    368            "PROCEDURE STATUS": _show_parser("PROCEDURE STATUS"),
    369            "PRIVILEGES": _show_parser("PRIVILEGES"),
    370            "FULL PROCESSLIST": _show_parser("PROCESSLIST", full=True),
    371            "PROCESSLIST": _show_parser("PROCESSLIST"),
    372            "PROFILE": _show_parser("PROFILE"),
    373            "PROFILES": _show_parser("PROFILES"),
    374            "RELAYLOG EVENTS": _show_parser("RELAYLOG EVENTS"),
    375            "REPLICAS": _show_parser("REPLICAS"),
    376            "SLAVE HOSTS": _show_parser("REPLICAS"),
    377            "REPLICA STATUS": _show_parser("REPLICA STATUS"),
    378            "SLAVE STATUS": _show_parser("REPLICA STATUS"),
    379            "GLOBAL STATUS": _show_parser("STATUS", global_=True),
    380            "SESSION STATUS": _show_parser("STATUS"),
    381            "STATUS": _show_parser("STATUS"),
    382            "TABLE STATUS": _show_parser("TABLE STATUS"),
    383            "FULL TABLES": _show_parser("TABLES", full=True),
    384            "TABLES": _show_parser("TABLES"),
    385            "TRIGGERS": _show_parser("TRIGGERS"),
    386            "GLOBAL VARIABLES": _show_parser("VARIABLES", global_=True),
    387            "SESSION VARIABLES": _show_parser("VARIABLES"),
    388            "VARIABLES": _show_parser("VARIABLES"),
    389            "WARNINGS": _show_parser("WARNINGS"),
    390        }
    391
    392        SET_PARSERS = {
    393            **parser.Parser.SET_PARSERS,
    394            "PERSIST": lambda self: self._parse_set_item_assignment("PERSIST"),
    395            "PERSIST_ONLY": lambda self: self._parse_set_item_assignment("PERSIST_ONLY"),
    396            "CHARACTER SET": lambda self: self._parse_set_item_charset("CHARACTER SET"),
    397            "CHARSET": lambda self: self._parse_set_item_charset("CHARACTER SET"),
    398            "NAMES": lambda self: self._parse_set_item_names(),
    399        }
    400
    401        CONSTRAINT_PARSERS = {
    402            **parser.Parser.CONSTRAINT_PARSERS,
    403            "FULLTEXT": lambda self: self._parse_index_constraint(kind="FULLTEXT"),
    404            "INDEX": lambda self: self._parse_index_constraint(),
    405            "KEY": lambda self: self._parse_index_constraint(),
    406            "SPATIAL": lambda self: self._parse_index_constraint(kind="SPATIAL"),
    407        }
    408
    409        SCHEMA_UNNAMED_CONSTRAINTS = {
    410            *parser.Parser.SCHEMA_UNNAMED_CONSTRAINTS,
    411            "FULLTEXT",
    412            "INDEX",
    413            "KEY",
    414            "SPATIAL",
    415        }
    416
    417        PROFILE_TYPES = {
    418            "ALL",
    419            "BLOCK IO",
    420            "CONTEXT SWITCHES",
    421            "CPU",
    422            "IPC",
    423            "MEMORY",
    424            "PAGE FAULTS",
    425            "SOURCE",
    426            "SWAPS",
    427        }
    428
    429        TYPE_TOKENS = {
    430            *parser.Parser.TYPE_TOKENS,
    431            TokenType.SET,
    432        }
    433
    434        ENUM_TYPE_TOKENS = {
    435            *parser.Parser.ENUM_TYPE_TOKENS,
    436            TokenType.SET,
    437        }
    438
    439        LOG_DEFAULTS_TO_LN = True
    440
    441        def _parse_primary_key_part(self) -> t.Optional[exp.Expression]:
    442            this = self._parse_id_var()
    443            if not self._match(TokenType.L_PAREN):
    444                return this
    445
    446            expression = self._parse_number()
    447            self._match_r_paren()
    448            return self.expression(exp.ColumnPrefix, this=this, expression=expression)
    449
    450        def _parse_index_constraint(
    451            self, kind: t.Optional[str] = None
    452        ) -> exp.IndexColumnConstraint:
    453            if kind:
    454                self._match_texts({"INDEX", "KEY"})
    455
    456            this = self._parse_id_var(any_token=False)
    457            index_type = self._match(TokenType.USING) and self._advance_any() and self._prev.text
    458            schema = self._parse_schema()
    459
    460            options = []
    461            while True:
    462                if self._match_text_seq("KEY_BLOCK_SIZE"):
    463                    self._match(TokenType.EQ)
    464                    opt = exp.IndexConstraintOption(key_block_size=self._parse_number())
    465                elif self._match(TokenType.USING):
    466                    opt = exp.IndexConstraintOption(using=self._advance_any() and self._prev.text)
    467                elif self._match_text_seq("WITH", "PARSER"):
    468                    opt = exp.IndexConstraintOption(parser=self._parse_var(any_token=True))
    469                elif self._match(TokenType.COMMENT):
    470                    opt = exp.IndexConstraintOption(comment=self._parse_string())
    471                elif self._match_text_seq("VISIBLE"):
    472                    opt = exp.IndexConstraintOption(visible=True)
    473                elif self._match_text_seq("INVISIBLE"):
    474                    opt = exp.IndexConstraintOption(visible=False)
    475                elif self._match_text_seq("ENGINE_ATTRIBUTE"):
    476                    self._match(TokenType.EQ)
    477                    opt = exp.IndexConstraintOption(engine_attr=self._parse_string())
    478                elif self._match_text_seq("ENGINE_ATTRIBUTE"):
    479                    self._match(TokenType.EQ)
    480                    opt = exp.IndexConstraintOption(engine_attr=self._parse_string())
    481                elif self._match_text_seq("SECONDARY_ENGINE_ATTRIBUTE"):
    482                    self._match(TokenType.EQ)
    483                    opt = exp.IndexConstraintOption(secondary_engine_attr=self._parse_string())
    484                else:
    485                    opt = None
    486
    487                if not opt:
    488                    break
    489
    490                options.append(opt)
    491
    492            return self.expression(
    493                exp.IndexColumnConstraint,
    494                this=this,
    495                schema=schema,
    496                kind=kind,
    497                index_type=index_type,
    498                options=options,
    499            )
    500
    501        def _parse_show_mysql(
    502            self,
    503            this: str,
    504            target: bool | str = False,
    505            full: t.Optional[bool] = None,
    506            global_: t.Optional[bool] = None,
    507        ) -> exp.Show:
    508            if target:
    509                if isinstance(target, str):
    510                    self._match_text_seq(target)
    511                target_id = self._parse_id_var()
    512            else:
    513                target_id = None
    514
    515            log = self._parse_string() if self._match_text_seq("IN") else None
    516
    517            if this in {"BINLOG EVENTS", "RELAYLOG EVENTS"}:
    518                position = self._parse_number() if self._match_text_seq("FROM") else None
    519                db = None
    520            else:
    521                position = None
    522                db = None
    523
    524                if self._match(TokenType.FROM):
    525                    db = self._parse_id_var()
    526                elif self._match(TokenType.DOT):
    527                    db = target_id
    528                    target_id = self._parse_id_var()
    529
    530            channel = self._parse_id_var() if self._match_text_seq("FOR", "CHANNEL") else None
    531
    532            like = self._parse_string() if self._match_text_seq("LIKE") else None
    533            where = self._parse_where()
    534
    535            if this == "PROFILE":
    536                types = self._parse_csv(lambda: self._parse_var_from_options(self.PROFILE_TYPES))
    537                query = self._parse_number() if self._match_text_seq("FOR", "QUERY") else None
    538                offset = self._parse_number() if self._match_text_seq("OFFSET") else None
    539                limit = self._parse_number() if self._match_text_seq("LIMIT") else None
    540            else:
    541                types, query = None, None
    542                offset, limit = self._parse_oldstyle_limit()
    543
    544            mutex = True if self._match_text_seq("MUTEX") else None
    545            mutex = False if self._match_text_seq("STATUS") else mutex
    546
    547            return self.expression(
    548                exp.Show,
    549                this=this,
    550                target=target_id,
    551                full=full,
    552                log=log,
    553                position=position,
    554                db=db,
    555                channel=channel,
    556                like=like,
    557                where=where,
    558                types=types,
    559                query=query,
    560                offset=offset,
    561                limit=limit,
    562                mutex=mutex,
    563                **{"global": global_},  # type: ignore
    564            )
    565
    566        def _parse_oldstyle_limit(
    567            self,
    568        ) -> t.Tuple[t.Optional[exp.Expression], t.Optional[exp.Expression]]:
    569            limit = None
    570            offset = None
    571            if self._match_text_seq("LIMIT"):
    572                parts = self._parse_csv(self._parse_number)
    573                if len(parts) == 1:
    574                    limit = parts[0]
    575                elif len(parts) == 2:
    576                    limit = parts[1]
    577                    offset = parts[0]
    578
    579            return offset, limit
    580
    581        def _parse_set_item_charset(self, kind: str) -> exp.Expression:
    582            this = self._parse_string() or self._parse_id_var()
    583            return self.expression(exp.SetItem, this=this, kind=kind)
    584
    585        def _parse_set_item_names(self) -> exp.Expression:
    586            charset = self._parse_string() or self._parse_id_var()
    587            if self._match_text_seq("COLLATE"):
    588                collate = self._parse_string() or self._parse_id_var()
    589            else:
    590                collate = None
    591
    592            return self.expression(exp.SetItem, this=charset, collate=collate, kind="NAMES")
    593
    594        def _parse_type(self, parse_interval: bool = True) -> t.Optional[exp.Expression]:
    595            # mysql binary is special and can work anywhere, even in order by operations
    596            # it operates like a no paren func
    597            if self._match(TokenType.BINARY, advance=False):
    598                data_type = self._parse_types(check_func=True, allow_identifiers=False)
    599
    600                if isinstance(data_type, exp.DataType):
    601                    return self.expression(exp.Cast, this=self._parse_column(), to=data_type)
    602
    603            return super()._parse_type(parse_interval=parse_interval)
    604
    605        def _parse_chr(self) -> t.Optional[exp.Expression]:
    606            expressions = self._parse_csv(self._parse_conjunction)
    607            kwargs: t.Dict[str, t.Any] = {"this": seq_get(expressions, 0)}
    608
    609            if len(expressions) > 1:
    610                kwargs["expressions"] = expressions[1:]
    611
    612            if self._match(TokenType.USING):
    613                kwargs["charset"] = self._parse_var()
    614
    615            return self.expression(exp.Chr, **kwargs)
    616
    617    class Generator(generator.Generator):
    618        LOCKING_READS_SUPPORTED = True
    619        NULL_ORDERING_SUPPORTED = False
    620        JOIN_HINTS = False
    621        TABLE_HINTS = True
    622        DUPLICATE_KEY_UPDATE_WITH_SET = False
    623        QUERY_HINT_SEP = " "
    624        VALUES_AS_TABLE = False
    625        NVL2_SUPPORTED = False
    626
    627        TRANSFORMS = {
    628            **generator.Generator.TRANSFORMS,
    629            exp.CurrentDate: no_paren_current_date_sql,
    630            exp.DateDiff: _remove_ts_or_ds_to_date(
    631                lambda self, e: self.func("DATEDIFF", e.this, e.expression), ("this", "expression")
    632            ),
    633            exp.DateAdd: _remove_ts_or_ds_to_date(_date_add_sql("ADD")),
    634            exp.DateStrToDate: datestrtodate_sql,
    635            exp.DateSub: _remove_ts_or_ds_to_date(_date_add_sql("SUB")),
    636            exp.DateTrunc: _date_trunc_sql,
    637            exp.Day: _remove_ts_or_ds_to_date(),
    638            exp.DayOfMonth: _remove_ts_or_ds_to_date(rename_func("DAYOFMONTH")),
    639            exp.DayOfWeek: _remove_ts_or_ds_to_date(rename_func("DAYOFWEEK")),
    640            exp.DayOfYear: _remove_ts_or_ds_to_date(rename_func("DAYOFYEAR")),
    641            exp.GroupConcat: lambda self, e: f"""GROUP_CONCAT({self.sql(e, "this")} SEPARATOR {self.sql(e, "separator") or "','"})""",
    642            exp.ILike: no_ilike_sql,
    643            exp.JSONExtractScalar: arrow_json_extract_scalar_sql,
    644            exp.JSONKeyValue: json_keyvalue_comma_sql,
    645            exp.Max: max_or_greatest,
    646            exp.Min: min_or_least,
    647            exp.Month: _remove_ts_or_ds_to_date(),
    648            exp.NullSafeEQ: lambda self, e: self.binary(e, "<=>"),
    649            exp.NullSafeNEQ: lambda self, e: self.not_sql(self.binary(e, "<=>")),
    650            exp.Pivot: no_pivot_sql,
    651            exp.Select: transforms.preprocess(
    652                [
    653                    transforms.eliminate_distinct_on,
    654                    transforms.eliminate_semi_and_anti_joins,
    655                    transforms.eliminate_qualify,
    656                    transforms.eliminate_full_outer_join,
    657                ]
    658            ),
    659            exp.StrPosition: strposition_to_locate_sql,
    660            exp.StrToDate: _str_to_date_sql,
    661            exp.StrToTime: _str_to_date_sql,
    662            exp.Stuff: rename_func("INSERT"),
    663            exp.TableSample: no_tablesample_sql,
    664            exp.TimestampAdd: date_add_interval_sql("DATE", "ADD"),
    665            exp.TimestampSub: date_add_interval_sql("DATE", "SUB"),
    666            exp.TimeStrToUnix: rename_func("UNIX_TIMESTAMP"),
    667            exp.TimeStrToTime: lambda self, e: self.sql(exp.cast(e.this, "datetime", copy=True)),
    668            exp.TimeToStr: _remove_ts_or_ds_to_date(
    669                lambda self, e: self.func("DATE_FORMAT", e.this, self.format_time(e))
    670            ),
    671            exp.Trim: _trim_sql,
    672            exp.TryCast: no_trycast_sql,
    673            exp.TsOrDsAdd: _date_add_sql("ADD"),
    674            exp.TsOrDsToDate: _ts_or_ds_to_date_sql,
    675            exp.Week: _remove_ts_or_ds_to_date(),
    676            exp.WeekOfYear: _remove_ts_or_ds_to_date(rename_func("WEEKOFYEAR")),
    677            exp.Year: _remove_ts_or_ds_to_date(),
    678        }
    679
    680        UNSIGNED_TYPE_MAPPING = {
    681            exp.DataType.Type.UBIGINT: "BIGINT",
    682            exp.DataType.Type.UINT: "INT",
    683            exp.DataType.Type.UMEDIUMINT: "MEDIUMINT",
    684            exp.DataType.Type.USMALLINT: "SMALLINT",
    685            exp.DataType.Type.UTINYINT: "TINYINT",
    686            exp.DataType.Type.UDECIMAL: "DECIMAL",
    687        }
    688
    689        TIMESTAMP_TYPE_MAPPING = {
    690            exp.DataType.Type.TIMESTAMP: "DATETIME",
    691            exp.DataType.Type.TIMESTAMPTZ: "TIMESTAMP",
    692            exp.DataType.Type.TIMESTAMPLTZ: "TIMESTAMP",
    693        }
    694
    695        TYPE_MAPPING = {
    696            **generator.Generator.TYPE_MAPPING,
    697            **UNSIGNED_TYPE_MAPPING,
    698            **TIMESTAMP_TYPE_MAPPING,
    699        }
    700
    701        TYPE_MAPPING.pop(exp.DataType.Type.MEDIUMTEXT)
    702        TYPE_MAPPING.pop(exp.DataType.Type.LONGTEXT)
    703        TYPE_MAPPING.pop(exp.DataType.Type.TINYTEXT)
    704        TYPE_MAPPING.pop(exp.DataType.Type.MEDIUMBLOB)
    705        TYPE_MAPPING.pop(exp.DataType.Type.LONGBLOB)
    706        TYPE_MAPPING.pop(exp.DataType.Type.TINYBLOB)
    707
    708        PROPERTIES_LOCATION = {
    709            **generator.Generator.PROPERTIES_LOCATION,
    710            exp.TransientProperty: exp.Properties.Location.UNSUPPORTED,
    711            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    712        }
    713
    714        LIMIT_FETCH = "LIMIT"
    715
    716        LIMIT_ONLY_LITERALS = True
    717
    718        # MySQL doesn't support many datatypes in cast.
    719        # https://dev.mysql.com/doc/refman/8.0/en/cast-functions.html#function_cast
    720        CAST_MAPPING = {
    721            exp.DataType.Type.BIGINT: "SIGNED",
    722            exp.DataType.Type.BOOLEAN: "SIGNED",
    723            exp.DataType.Type.INT: "SIGNED",
    724            exp.DataType.Type.TEXT: "CHAR",
    725            exp.DataType.Type.UBIGINT: "UNSIGNED",
    726            exp.DataType.Type.VARCHAR: "CHAR",
    727        }
    728
    729        TIMESTAMP_FUNC_TYPES = {
    730            exp.DataType.Type.TIMESTAMPTZ,
    731            exp.DataType.Type.TIMESTAMPLTZ,
    732        }
    733
    734        def datatype_sql(self, expression: exp.DataType) -> str:
    735            # https://dev.mysql.com/doc/refman/8.0/en/numeric-type-syntax.html
    736            result = super().datatype_sql(expression)
    737            if expression.this in self.UNSIGNED_TYPE_MAPPING:
    738                result = f"{result} UNSIGNED"
    739            return result
    740
    741        def xor_sql(self, expression: exp.Xor) -> str:
    742            if expression.expressions:
    743                return self.expressions(expression, sep=" XOR ")
    744            return super().xor_sql(expression)
    745
    746        def jsonarraycontains_sql(self, expression: exp.JSONArrayContains) -> str:
    747            return f"{self.sql(expression, 'this')} MEMBER OF({self.sql(expression, 'expression')})"
    748
    749        def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    750            if expression.to.this in self.TIMESTAMP_FUNC_TYPES:
    751                return self.func("TIMESTAMP", expression.this)
    752
    753            to = self.CAST_MAPPING.get(expression.to.this)
    754
    755            if to:
    756                expression.to.set("this", to)
    757            return super().cast_sql(expression)
    758
    759        def show_sql(self, expression: exp.Show) -> str:
    760            this = f" {expression.name}"
    761            full = " FULL" if expression.args.get("full") else ""
    762            global_ = " GLOBAL" if expression.args.get("global") else ""
    763
    764            target = self.sql(expression, "target")
    765            target = f" {target}" if target else ""
    766            if expression.name in {"COLUMNS", "INDEX"}:
    767                target = f" FROM{target}"
    768            elif expression.name == "GRANTS":
    769                target = f" FOR{target}"
    770
    771            db = self._prefixed_sql("FROM", expression, "db")
    772
    773            like = self._prefixed_sql("LIKE", expression, "like")
    774            where = self.sql(expression, "where")
    775
    776            types = self.expressions(expression, key="types")
    777            types = f" {types}" if types else types
    778            query = self._prefixed_sql("FOR QUERY", expression, "query")
    779
    780            if expression.name == "PROFILE":
    781                offset = self._prefixed_sql("OFFSET", expression, "offset")
    782                limit = self._prefixed_sql("LIMIT", expression, "limit")
    783            else:
    784                offset = ""
    785                limit = self._oldstyle_limit_sql(expression)
    786
    787            log = self._prefixed_sql("IN", expression, "log")
    788            position = self._prefixed_sql("FROM", expression, "position")
    789
    790            channel = self._prefixed_sql("FOR CHANNEL", expression, "channel")
    791
    792            if expression.name == "ENGINE":
    793                mutex_or_status = " MUTEX" if expression.args.get("mutex") else " STATUS"
    794            else:
    795                mutex_or_status = ""
    796
    797            return f"SHOW{full}{global_}{this}{target}{types}{db}{query}{log}{position}{channel}{mutex_or_status}{like}{where}{offset}{limit}"
    798
    799        def _prefixed_sql(self, prefix: str, expression: exp.Expression, arg: str) -> str:
    800            sql = self.sql(expression, arg)
    801            return f" {prefix} {sql}" if sql else ""
    802
    803        def _oldstyle_limit_sql(self, expression: exp.Show) -> str:
    804            limit = self.sql(expression, "limit")
    805            offset = self.sql(expression, "offset")
    806            if limit:
    807                limit_offset = f"{offset}, {limit}" if offset else limit
    808                return f" LIMIT {limit_offset}"
    809            return ""
    810
    811        def chr_sql(self, expression: exp.Chr) -> str:
    812            this = self.expressions(sqls=[expression.this] + expression.expressions)
    813            charset = expression.args.get("charset")
    814            using = f" USING {self.sql(charset)}" if charset else ""
    815            return f"CHAR({this}{using})"

TIME_SPECIFIERS = {'s', 'T', 'i', 'I', 'H', 'k', 'l', 'p', 'r', 'f', 'h', 'S'}
class MySQL(sqlglot.dialects.dialect.Dialect): View Source

    150class MySQL(Dialect):
    151    # https://dev.mysql.com/doc/refman/8.0/en/identifiers.html
    152    IDENTIFIERS_CAN_START_WITH_DIGIT = True
    153
    154    TIME_FORMAT = "'%Y-%m-%d %T'"
    155    DPIPE_IS_STRING_CONCAT = False
    156    SUPPORTS_USER_DEFINED_TYPES = False
    157    SUPPORTS_SEMI_ANTI_JOIN = False
    158
    159    # https://prestodb.io/docs/current/functions/datetime.html#mysql-date-functions
    160    TIME_MAPPING = {
    161        "%M": "%B",
    162        "%c": "%-m",
    163        "%e": "%-d",
    164        "%h": "%I",
    165        "%i": "%M",
    166        "%s": "%S",
    167        "%u": "%W",
    168        "%k": "%-H",
    169        "%l": "%-I",
    170        "%T": "%H:%M:%S",
    171        "%W": "%a",
    172    }
    173
    174    class Tokenizer(tokens.Tokenizer):
    175        QUOTES = ["'", '"']
    176        COMMENTS = ["--", "#", ("/*", "*/")]
    177        IDENTIFIERS = ["`"]
    178        STRING_ESCAPES = ["'", '"', "\\"]
    179        BIT_STRINGS = [("b'", "'"), ("B'", "'"), ("0b", "")]
    180        HEX_STRINGS = [("x'", "'"), ("X'", "'"), ("0x", "")]
    181
    182        KEYWORDS = {
    183            **tokens.Tokenizer.KEYWORDS,
    184            "CHARSET": TokenType.CHARACTER_SET,
    185            "ENUM": TokenType.ENUM,
    186            "FORCE": TokenType.FORCE,
    187            "IGNORE": TokenType.IGNORE,
    188            "LOCK TABLES": TokenType.COMMAND,
    189            "LONGBLOB": TokenType.LONGBLOB,
    190            "LONGTEXT": TokenType.LONGTEXT,
    191            "MEDIUMBLOB": TokenType.MEDIUMBLOB,
    192            "TINYBLOB": TokenType.TINYBLOB,
    193            "TINYTEXT": TokenType.TINYTEXT,
    194            "MEDIUMTEXT": TokenType.MEDIUMTEXT,
    195            "MEDIUMINT": TokenType.MEDIUMINT,
    196            "MEMBER OF": TokenType.MEMBER_OF,
    197            "SEPARATOR": TokenType.SEPARATOR,
    198            "START": TokenType.BEGIN,
    199            "SIGNED": TokenType.BIGINT,
    200            "SIGNED INTEGER": TokenType.BIGINT,
    201            "UNLOCK TABLES": TokenType.COMMAND,
    202            "UNSIGNED": TokenType.UBIGINT,
    203            "UNSIGNED INTEGER": TokenType.UBIGINT,
    204            "YEAR": TokenType.YEAR,
    205            "_ARMSCII8": TokenType.INTRODUCER,
    206            "_ASCII": TokenType.INTRODUCER,
    207            "_BIG5": TokenType.INTRODUCER,
    208            "_BINARY": TokenType.INTRODUCER,
    209            "_CP1250": TokenType.INTRODUCER,
    210            "_CP1251": TokenType.INTRODUCER,
    211            "_CP1256": TokenType.INTRODUCER,
    212            "_CP1257": TokenType.INTRODUCER,
    213            "_CP850": TokenType.INTRODUCER,
    214            "_CP852": TokenType.INTRODUCER,
    215            "_CP866": TokenType.INTRODUCER,
    216            "_CP932": TokenType.INTRODUCER,
    217            "_DEC8": TokenType.INTRODUCER,
    218            "_EUCJPMS": TokenType.INTRODUCER,
    219            "_EUCKR": TokenType.INTRODUCER,
    220            "_GB18030": TokenType.INTRODUCER,
    221            "_GB2312": TokenType.INTRODUCER,
    222            "_GBK": TokenType.INTRODUCER,
    223            "_GEOSTD8": TokenType.INTRODUCER,
    224            "_GREEK": TokenType.INTRODUCER,
    225            "_HEBREW": TokenType.INTRODUCER,
    226            "_HP8": TokenType.INTRODUCER,
    227            "_KEYBCS2": TokenType.INTRODUCER,
    228            "_KOI8R": TokenType.INTRODUCER,
    229            "_KOI8U": TokenType.INTRODUCER,
    230            "_LATIN1": TokenType.INTRODUCER,
    231            "_LATIN2": TokenType.INTRODUCER,
    232            "_LATIN5": TokenType.INTRODUCER,
    233            "_LATIN7": TokenType.INTRODUCER,
    234            "_MACCE": TokenType.INTRODUCER,
    235            "_MACROMAN": TokenType.INTRODUCER,
    236            "_SJIS": TokenType.INTRODUCER,
    237            "_SWE7": TokenType.INTRODUCER,
    238            "_TIS620": TokenType.INTRODUCER,
    239            "_UCS2": TokenType.INTRODUCER,
    240            "_UJIS": TokenType.INTRODUCER,
    241            # https://dev.mysql.com/doc/refman/8.0/en/string-literals.html
    242            "_UTF8": TokenType.INTRODUCER,
    243            "_UTF16": TokenType.INTRODUCER,
    244            "_UTF16LE": TokenType.INTRODUCER,
    245            "_UTF32": TokenType.INTRODUCER,
    246            "_UTF8MB3": TokenType.INTRODUCER,
    247            "_UTF8MB4": TokenType.INTRODUCER,
    248            "@@": TokenType.SESSION_PARAMETER,
    249        }
    250
    251        COMMANDS = tokens.Tokenizer.COMMANDS - {TokenType.SHOW}
    252
    253    class Parser(parser.Parser):
    254        FUNC_TOKENS = {
    255            *parser.Parser.FUNC_TOKENS,
    256            TokenType.DATABASE,
    257            TokenType.SCHEMA,
    258            TokenType.VALUES,
    259        }
    260
    261        CONJUNCTION = {
    262            **parser.Parser.CONJUNCTION,
    263            TokenType.DAMP: exp.And,
    264            TokenType.XOR: exp.Xor,
    265            TokenType.DPIPE: exp.Or,
    266        }
    267
    268        # MySQL uses || as a synonym to the logical OR operator
    269        # https://dev.mysql.com/doc/refman/8.0/en/logical-operators.html#operator_or
    270        BITWISE = parser.Parser.BITWISE.copy()
    271        BITWISE.pop(TokenType.DPIPE)
    272
    273        TABLE_ALIAS_TOKENS = (
    274            parser.Parser.TABLE_ALIAS_TOKENS - parser.Parser.TABLE_INDEX_HINT_TOKENS
    275        )
    276
    277        RANGE_PARSERS = {
    278            **parser.Parser.RANGE_PARSERS,
    279            TokenType.MEMBER_OF: lambda self, this: self.expression(
    280                exp.JSONArrayContains,
    281                this=this,
    282                expression=self._parse_wrapped(self._parse_expression),
    283            ),
    284        }
    285
    286        FUNCTIONS = {
    287            **parser.Parser.FUNCTIONS,
    288            "DATE": lambda args: exp.TsOrDsToDate(this=seq_get(args, 0)),
    289            "DATE_ADD": parse_date_delta_with_interval(exp.DateAdd),
    290            "DATE_FORMAT": format_time_lambda(exp.TimeToStr, "mysql"),
    291            "DATE_SUB": parse_date_delta_with_interval(exp.DateSub),
    292            "INSTR": lambda args: exp.StrPosition(substr=seq_get(args, 1), this=seq_get(args, 0)),
    293            "ISNULL": isnull_to_is_null,
    294            "LOCATE": locate_to_strposition,
    295            "MONTHNAME": lambda args: exp.TimeToStr(
    296                this=exp.TsOrDsToDate(this=seq_get(args, 0)),
    297                format=exp.Literal.string("%B"),
    298            ),
    299            "STR_TO_DATE": _str_to_date,
    300            "TO_DAYS": lambda args: exp.paren(
    301                exp.DateDiff(
    302                    this=exp.TsOrDsToDate(this=seq_get(args, 0)),
    303                    expression=exp.TsOrDsToDate(this=exp.Literal.string("0000-01-01")),
    304                    unit=exp.var("DAY"),
    305                )
    306                + 1
    307            ),
    308            "DAY": lambda args: exp.Day(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    309            "DAYOFMONTH": lambda args: exp.DayOfMonth(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    310            "DAYOFWEEK": lambda args: exp.DayOfWeek(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    311            "DAYOFYEAR": lambda args: exp.DayOfYear(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    312            "MONTH": lambda args: exp.Month(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    313            "WEEK": lambda args: exp.Week(
    314                this=exp.TsOrDsToDate(this=seq_get(args, 0)), mode=seq_get(args, 1)
    315            ),
    316            "WEEKOFYEAR": lambda args: exp.WeekOfYear(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    317            "YEAR": lambda args: exp.Year(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    318        }
    319
    320        FUNCTION_PARSERS = {
    321            **parser.Parser.FUNCTION_PARSERS,
    322            "CHAR": lambda self: self._parse_chr(),
    323            "GROUP_CONCAT": lambda self: self.expression(
    324                exp.GroupConcat,
    325                this=self._parse_lambda(),
    326                separator=self._match(TokenType.SEPARATOR) and self._parse_field(),
    327            ),
    328            # https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_values
    329            "VALUES": lambda self: self.expression(
    330                exp.Anonymous, this="VALUES", expressions=[self._parse_id_var()]
    331            ),
    332        }
    333
    334        STATEMENT_PARSERS = {
    335            **parser.Parser.STATEMENT_PARSERS,
    336            TokenType.SHOW: lambda self: self._parse_show(),
    337        }
    338
    339        SHOW_PARSERS = {
    340            "BINARY LOGS": _show_parser("BINARY LOGS"),
    341            "MASTER LOGS": _show_parser("BINARY LOGS"),
    342            "BINLOG EVENTS": _show_parser("BINLOG EVENTS"),
    343            "CHARACTER SET": _show_parser("CHARACTER SET"),
    344            "CHARSET": _show_parser("CHARACTER SET"),
    345            "COLLATION": _show_parser("COLLATION"),
    346            "FULL COLUMNS": _show_parser("COLUMNS", target="FROM", full=True),
    347            "COLUMNS": _show_parser("COLUMNS", target="FROM"),
    348            "CREATE DATABASE": _show_parser("CREATE DATABASE", target=True),
    349            "CREATE EVENT": _show_parser("CREATE EVENT", target=True),
    350            "CREATE FUNCTION": _show_parser("CREATE FUNCTION", target=True),
    351            "CREATE PROCEDURE": _show_parser("CREATE PROCEDURE", target=True),
    352            "CREATE TABLE": _show_parser("CREATE TABLE", target=True),
    353            "CREATE TRIGGER": _show_parser("CREATE TRIGGER", target=True),
    354            "CREATE VIEW": _show_parser("CREATE VIEW", target=True),
    355            "DATABASES": _show_parser("DATABASES"),
    356            "ENGINE": _show_parser("ENGINE", target=True),
    357            "STORAGE ENGINES": _show_parser("ENGINES"),
    358            "ENGINES": _show_parser("ENGINES"),
    359            "ERRORS": _show_parser("ERRORS"),
    360            "EVENTS": _show_parser("EVENTS"),
    361            "FUNCTION CODE": _show_parser("FUNCTION CODE", target=True),
    362            "FUNCTION STATUS": _show_parser("FUNCTION STATUS"),
    363            "GRANTS": _show_parser("GRANTS", target="FOR"),
    364            "INDEX": _show_parser("INDEX", target="FROM"),
    365            "MASTER STATUS": _show_parser("MASTER STATUS"),
    366            "OPEN TABLES": _show_parser("OPEN TABLES"),
    367            "PLUGINS": _show_parser("PLUGINS"),
    368            "PROCEDURE CODE": _show_parser("PROCEDURE CODE", target=True),
    369            "PROCEDURE STATUS": _show_parser("PROCEDURE STATUS"),
    370            "PRIVILEGES": _show_parser("PRIVILEGES"),
    371            "FULL PROCESSLIST": _show_parser("PROCESSLIST", full=True),
    372            "PROCESSLIST": _show_parser("PROCESSLIST"),
    373            "PROFILE": _show_parser("PROFILE"),
    374            "PROFILES": _show_parser("PROFILES"),
    375            "RELAYLOG EVENTS": _show_parser("RELAYLOG EVENTS"),
    376            "REPLICAS": _show_parser("REPLICAS"),
    377            "SLAVE HOSTS": _show_parser("REPLICAS"),
    378            "REPLICA STATUS": _show_parser("REPLICA STATUS"),
    379            "SLAVE STATUS": _show_parser("REPLICA STATUS"),
    380            "GLOBAL STATUS": _show_parser("STATUS", global_=True),
    381            "SESSION STATUS": _show_parser("STATUS"),
    382            "STATUS": _show_parser("STATUS"),
    383            "TABLE STATUS": _show_parser("TABLE STATUS"),
    384            "FULL TABLES": _show_parser("TABLES", full=True),
    385            "TABLES": _show_parser("TABLES"),
    386            "TRIGGERS": _show_parser("TRIGGERS"),
    387            "GLOBAL VARIABLES": _show_parser("VARIABLES", global_=True),
    388            "SESSION VARIABLES": _show_parser("VARIABLES"),
    389            "VARIABLES": _show_parser("VARIABLES"),
    390            "WARNINGS": _show_parser("WARNINGS"),
    391        }
    392
    393        SET_PARSERS = {
    394            **parser.Parser.SET_PARSERS,
    395            "PERSIST": lambda self: self._parse_set_item_assignment("PERSIST"),
    396            "PERSIST_ONLY": lambda self: self._parse_set_item_assignment("PERSIST_ONLY"),
    397            "CHARACTER SET": lambda self: self._parse_set_item_charset("CHARACTER SET"),
    398            "CHARSET": lambda self: self._parse_set_item_charset("CHARACTER SET"),
    399            "NAMES": lambda self: self._parse_set_item_names(),
    400        }
    401
    402        CONSTRAINT_PARSERS = {
    403            **parser.Parser.CONSTRAINT_PARSERS,
    404            "FULLTEXT": lambda self: self._parse_index_constraint(kind="FULLTEXT"),
    405            "INDEX": lambda self: self._parse_index_constraint(),
    406            "KEY": lambda self: self._parse_index_constraint(),
    407            "SPATIAL": lambda self: self._parse_index_constraint(kind="SPATIAL"),
    408        }
    409
    410        SCHEMA_UNNAMED_CONSTRAINTS = {
    411            *parser.Parser.SCHEMA_UNNAMED_CONSTRAINTS,
    412            "FULLTEXT",
    413            "INDEX",
    414            "KEY",
    415            "SPATIAL",
    416        }
    417
    418        PROFILE_TYPES = {
    419            "ALL",
    420            "BLOCK IO",
    421            "CONTEXT SWITCHES",
    422            "CPU",
    423            "IPC",
    424            "MEMORY",
    425            "PAGE FAULTS",
    426            "SOURCE",
    427            "SWAPS",
    428        }
    429
    430        TYPE_TOKENS = {
    431            *parser.Parser.TYPE_TOKENS,
    432            TokenType.SET,
    433        }
    434
    435        ENUM_TYPE_TOKENS = {
    436            *parser.Parser.ENUM_TYPE_TOKENS,
    437            TokenType.SET,
    438        }
    439
    440        LOG_DEFAULTS_TO_LN = True
    441
    442        def _parse_primary_key_part(self) -> t.Optional[exp.Expression]:
    443            this = self._parse_id_var()
    444            if not self._match(TokenType.L_PAREN):
    445                return this
    446
    447            expression = self._parse_number()
    448            self._match_r_paren()
    449            return self.expression(exp.ColumnPrefix, this=this, expression=expression)
    450
    451        def _parse_index_constraint(
    452            self, kind: t.Optional[str] = None
    453        ) -> exp.IndexColumnConstraint:
    454            if kind:
    455                self._match_texts({"INDEX", "KEY"})
    456
    457            this = self._parse_id_var(any_token=False)
    458            index_type = self._match(TokenType.USING) and self._advance_any() and self._prev.text
    459            schema = self._parse_schema()
    460
    461            options = []
    462            while True:
    463                if self._match_text_seq("KEY_BLOCK_SIZE"):
    464                    self._match(TokenType.EQ)
    465                    opt = exp.IndexConstraintOption(key_block_size=self._parse_number())
    466                elif self._match(TokenType.USING):
    467                    opt = exp.IndexConstraintOption(using=self._advance_any() and self._prev.text)
    468                elif self._match_text_seq("WITH", "PARSER"):
    469                    opt = exp.IndexConstraintOption(parser=self._parse_var(any_token=True))
    470                elif self._match(TokenType.COMMENT):
    471                    opt = exp.IndexConstraintOption(comment=self._parse_string())
    472                elif self._match_text_seq("VISIBLE"):
    473                    opt = exp.IndexConstraintOption(visible=True)
    474                elif self._match_text_seq("INVISIBLE"):
    475                    opt = exp.IndexConstraintOption(visible=False)
    476                elif self._match_text_seq("ENGINE_ATTRIBUTE"):
    477                    self._match(TokenType.EQ)
    478                    opt = exp.IndexConstraintOption(engine_attr=self._parse_string())
    479                elif self._match_text_seq("ENGINE_ATTRIBUTE"):
    480                    self._match(TokenType.EQ)
    481                    opt = exp.IndexConstraintOption(engine_attr=self._parse_string())
    482                elif self._match_text_seq("SECONDARY_ENGINE_ATTRIBUTE"):
    483                    self._match(TokenType.EQ)
    484                    opt = exp.IndexConstraintOption(secondary_engine_attr=self._parse_string())
    485                else:
    486                    opt = None
    487
    488                if not opt:
    489                    break
    490
    491                options.append(opt)
    492
    493            return self.expression(
    494                exp.IndexColumnConstraint,
    495                this=this,
    496                schema=schema,
    497                kind=kind,
    498                index_type=index_type,
    499                options=options,
    500            )
    501
    502        def _parse_show_mysql(
    503            self,
    504            this: str,
    505            target: bool | str = False,
    506            full: t.Optional[bool] = None,
    507            global_: t.Optional[bool] = None,
    508        ) -> exp.Show:
    509            if target:
    510                if isinstance(target, str):
    511                    self._match_text_seq(target)
    512                target_id = self._parse_id_var()
    513            else:
    514                target_id = None
    515
    516            log = self._parse_string() if self._match_text_seq("IN") else None
    517
    518            if this in {"BINLOG EVENTS", "RELAYLOG EVENTS"}:
    519                position = self._parse_number() if self._match_text_seq("FROM") else None
    520                db = None
    521            else:
    522                position = None
    523                db = None
    524
    525                if self._match(TokenType.FROM):
    526                    db = self._parse_id_var()
    527                elif self._match(TokenType.DOT):
    528                    db = target_id
    529                    target_id = self._parse_id_var()
    530
    531            channel = self._parse_id_var() if self._match_text_seq("FOR", "CHANNEL") else None
    532
    533            like = self._parse_string() if self._match_text_seq("LIKE") else None
    534            where = self._parse_where()
    535
    536            if this == "PROFILE":
    537                types = self._parse_csv(lambda: self._parse_var_from_options(self.PROFILE_TYPES))
    538                query = self._parse_number() if self._match_text_seq("FOR", "QUERY") else None
    539                offset = self._parse_number() if self._match_text_seq("OFFSET") else None
    540                limit = self._parse_number() if self._match_text_seq("LIMIT") else None
    541            else:
    542                types, query = None, None
    543                offset, limit = self._parse_oldstyle_limit()
    544
    545            mutex = True if self._match_text_seq("MUTEX") else None
    546            mutex = False if self._match_text_seq("STATUS") else mutex
    547
    548            return self.expression(
    549                exp.Show,
    550                this=this,
    551                target=target_id,
    552                full=full,
    553                log=log,
    554                position=position,
    555                db=db,
    556                channel=channel,
    557                like=like,
    558                where=where,
    559                types=types,
    560                query=query,
    561                offset=offset,
    562                limit=limit,
    563                mutex=mutex,
    564                **{"global": global_},  # type: ignore
    565            )
    566
    567        def _parse_oldstyle_limit(
    568            self,
    569        ) -> t.Tuple[t.Optional[exp.Expression], t.Optional[exp.Expression]]:
    570            limit = None
    571            offset = None
    572            if self._match_text_seq("LIMIT"):
    573                parts = self._parse_csv(self._parse_number)
    574                if len(parts) == 1:
    575                    limit = parts[0]
    576                elif len(parts) == 2:
    577                    limit = parts[1]
    578                    offset = parts[0]
    579
    580            return offset, limit
    581
    582        def _parse_set_item_charset(self, kind: str) -> exp.Expression:
    583            this = self._parse_string() or self._parse_id_var()
    584            return self.expression(exp.SetItem, this=this, kind=kind)
    585
    586        def _parse_set_item_names(self) -> exp.Expression:
    587            charset = self._parse_string() or self._parse_id_var()
    588            if self._match_text_seq("COLLATE"):
    589                collate = self._parse_string() or self._parse_id_var()
    590            else:
    591                collate = None
    592
    593            return self.expression(exp.SetItem, this=charset, collate=collate, kind="NAMES")
    594
    595        def _parse_type(self, parse_interval: bool = True) -> t.Optional[exp.Expression]:
    596            # mysql binary is special and can work anywhere, even in order by operations
    597            # it operates like a no paren func
    598            if self._match(TokenType.BINARY, advance=False):
    599                data_type = self._parse_types(check_func=True, allow_identifiers=False)
    600
    601                if isinstance(data_type, exp.DataType):
    602                    return self.expression(exp.Cast, this=self._parse_column(), to=data_type)
    603
    604            return super()._parse_type(parse_interval=parse_interval)
    605
    606        def _parse_chr(self) -> t.Optional[exp.Expression]:
    607            expressions = self._parse_csv(self._parse_conjunction)
    608            kwargs: t.Dict[str, t.Any] = {"this": seq_get(expressions, 0)}
    609
    610            if len(expressions) > 1:
    611                kwargs["expressions"] = expressions[1:]
    612
    613            if self._match(TokenType.USING):
    614                kwargs["charset"] = self._parse_var()
    615
    616            return self.expression(exp.Chr, **kwargs)
    617
    618    class Generator(generator.Generator):
    619        LOCKING_READS_SUPPORTED = True
    620        NULL_ORDERING_SUPPORTED = False
    621        JOIN_HINTS = False
    622        TABLE_HINTS = True
    623        DUPLICATE_KEY_UPDATE_WITH_SET = False
    624        QUERY_HINT_SEP = " "
    625        VALUES_AS_TABLE = False
    626        NVL2_SUPPORTED = False
    627
    628        TRANSFORMS = {
    629            **generator.Generator.TRANSFORMS,
    630            exp.CurrentDate: no_paren_current_date_sql,
    631            exp.DateDiff: _remove_ts_or_ds_to_date(
    632                lambda self, e: self.func("DATEDIFF", e.this, e.expression), ("this", "expression")
    633            ),
    634            exp.DateAdd: _remove_ts_or_ds_to_date(_date_add_sql("ADD")),
    635            exp.DateStrToDate: datestrtodate_sql,
    636            exp.DateSub: _remove_ts_or_ds_to_date(_date_add_sql("SUB")),
    637            exp.DateTrunc: _date_trunc_sql,
    638            exp.Day: _remove_ts_or_ds_to_date(),
    639            exp.DayOfMonth: _remove_ts_or_ds_to_date(rename_func("DAYOFMONTH")),
    640            exp.DayOfWeek: _remove_ts_or_ds_to_date(rename_func("DAYOFWEEK")),
    641            exp.DayOfYear: _remove_ts_or_ds_to_date(rename_func("DAYOFYEAR")),
    642            exp.GroupConcat: lambda self, e: f"""GROUP_CONCAT({self.sql(e, "this")} SEPARATOR {self.sql(e, "separator") or "','"})""",
    643            exp.ILike: no_ilike_sql,
    644            exp.JSONExtractScalar: arrow_json_extract_scalar_sql,
    645            exp.JSONKeyValue: json_keyvalue_comma_sql,
    646            exp.Max: max_or_greatest,
    647            exp.Min: min_or_least,
    648            exp.Month: _remove_ts_or_ds_to_date(),
    649            exp.NullSafeEQ: lambda self, e: self.binary(e, "<=>"),
    650            exp.NullSafeNEQ: lambda self, e: self.not_sql(self.binary(e, "<=>")),
    651            exp.Pivot: no_pivot_sql,
    652            exp.Select: transforms.preprocess(
    653                [
    654                    transforms.eliminate_distinct_on,
    655                    transforms.eliminate_semi_and_anti_joins,
    656                    transforms.eliminate_qualify,
    657                    transforms.eliminate_full_outer_join,
    658                ]
    659            ),
    660            exp.StrPosition: strposition_to_locate_sql,
    661            exp.StrToDate: _str_to_date_sql,
    662            exp.StrToTime: _str_to_date_sql,
    663            exp.Stuff: rename_func("INSERT"),
    664            exp.TableSample: no_tablesample_sql,
    665            exp.TimestampAdd: date_add_interval_sql("DATE", "ADD"),
    666            exp.TimestampSub: date_add_interval_sql("DATE", "SUB"),
    667            exp.TimeStrToUnix: rename_func("UNIX_TIMESTAMP"),
    668            exp.TimeStrToTime: lambda self, e: self.sql(exp.cast(e.this, "datetime", copy=True)),
    669            exp.TimeToStr: _remove_ts_or_ds_to_date(
    670                lambda self, e: self.func("DATE_FORMAT", e.this, self.format_time(e))
    671            ),
    672            exp.Trim: _trim_sql,
    673            exp.TryCast: no_trycast_sql,
    674            exp.TsOrDsAdd: _date_add_sql("ADD"),
    675            exp.TsOrDsToDate: _ts_or_ds_to_date_sql,
    676            exp.Week: _remove_ts_or_ds_to_date(),
    677            exp.WeekOfYear: _remove_ts_or_ds_to_date(rename_func("WEEKOFYEAR")),
    678            exp.Year: _remove_ts_or_ds_to_date(),
    679        }
    680
    681        UNSIGNED_TYPE_MAPPING = {
    682            exp.DataType.Type.UBIGINT: "BIGINT",
    683            exp.DataType.Type.UINT: "INT",
    684            exp.DataType.Type.UMEDIUMINT: "MEDIUMINT",
    685            exp.DataType.Type.USMALLINT: "SMALLINT",
    686            exp.DataType.Type.UTINYINT: "TINYINT",
    687            exp.DataType.Type.UDECIMAL: "DECIMAL",
    688        }
    689
    690        TIMESTAMP_TYPE_MAPPING = {
    691            exp.DataType.Type.TIMESTAMP: "DATETIME",
    692            exp.DataType.Type.TIMESTAMPTZ: "TIMESTAMP",
    693            exp.DataType.Type.TIMESTAMPLTZ: "TIMESTAMP",
    694        }
    695
    696        TYPE_MAPPING = {
    697            **generator.Generator.TYPE_MAPPING,
    698            **UNSIGNED_TYPE_MAPPING,
    699            **TIMESTAMP_TYPE_MAPPING,
    700        }
    701
    702        TYPE_MAPPING.pop(exp.DataType.Type.MEDIUMTEXT)
    703        TYPE_MAPPING.pop(exp.DataType.Type.LONGTEXT)
    704        TYPE_MAPPING.pop(exp.DataType.Type.TINYTEXT)
    705        TYPE_MAPPING.pop(exp.DataType.Type.MEDIUMBLOB)
    706        TYPE_MAPPING.pop(exp.DataType.Type.LONGBLOB)
    707        TYPE_MAPPING.pop(exp.DataType.Type.TINYBLOB)
    708
    709        PROPERTIES_LOCATION = {
    710            **generator.Generator.PROPERTIES_LOCATION,
    711            exp.TransientProperty: exp.Properties.Location.UNSUPPORTED,
    712            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    713        }
    714
    715        LIMIT_FETCH = "LIMIT"
    716
    717        LIMIT_ONLY_LITERALS = True
    718
    719        # MySQL doesn't support many datatypes in cast.
    720        # https://dev.mysql.com/doc/refman/8.0/en/cast-functions.html#function_cast
    721        CAST_MAPPING = {
    722            exp.DataType.Type.BIGINT: "SIGNED",
    723            exp.DataType.Type.BOOLEAN: "SIGNED",
    724            exp.DataType.Type.INT: "SIGNED",
    725            exp.DataType.Type.TEXT: "CHAR",
    726            exp.DataType.Type.UBIGINT: "UNSIGNED",
    727            exp.DataType.Type.VARCHAR: "CHAR",
    728        }
    729
    730        TIMESTAMP_FUNC_TYPES = {
    731            exp.DataType.Type.TIMESTAMPTZ,
    732            exp.DataType.Type.TIMESTAMPLTZ,
    733        }
    734
    735        def datatype_sql(self, expression: exp.DataType) -> str:
    736            # https://dev.mysql.com/doc/refman/8.0/en/numeric-type-syntax.html
    737            result = super().datatype_sql(expression)
    738            if expression.this in self.UNSIGNED_TYPE_MAPPING:
    739                result = f"{result} UNSIGNED"
    740            return result
    741
    742        def xor_sql(self, expression: exp.Xor) -> str:
    743            if expression.expressions:
    744                return self.expressions(expression, sep=" XOR ")
    745            return super().xor_sql(expression)
    746
    747        def jsonarraycontains_sql(self, expression: exp.JSONArrayContains) -> str:
    748            return f"{self.sql(expression, 'this')} MEMBER OF({self.sql(expression, 'expression')})"
    749
    750        def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    751            if expression.to.this in self.TIMESTAMP_FUNC_TYPES:
    752                return self.func("TIMESTAMP", expression.this)
    753
    754            to = self.CAST_MAPPING.get(expression.to.this)
    755
    756            if to:
    757                expression.to.set("this", to)
    758            return super().cast_sql(expression)
    759
    760        def show_sql(self, expression: exp.Show) -> str:
    761            this = f" {expression.name}"
    762            full = " FULL" if expression.args.get("full") else ""
    763            global_ = " GLOBAL" if expression.args.get("global") else ""
    764
    765            target = self.sql(expression, "target")
    766            target = f" {target}" if target else ""
    767            if expression.name in {"COLUMNS", "INDEX"}:
    768                target = f" FROM{target}"
    769            elif expression.name == "GRANTS":
    770                target = f" FOR{target}"
    771
    772            db = self._prefixed_sql("FROM", expression, "db")
    773
    774            like = self._prefixed_sql("LIKE", expression, "like")
    775            where = self.sql(expression, "where")
    776
    777            types = self.expressions(expression, key="types")
    778            types = f" {types}" if types else types
    779            query = self._prefixed_sql("FOR QUERY", expression, "query")
    780
    781            if expression.name == "PROFILE":
    782                offset = self._prefixed_sql("OFFSET", expression, "offset")
    783                limit = self._prefixed_sql("LIMIT", expression, "limit")
    784            else:
    785                offset = ""
    786                limit = self._oldstyle_limit_sql(expression)
    787
    788            log = self._prefixed_sql("IN", expression, "log")
    789            position = self._prefixed_sql("FROM", expression, "position")
    790
    791            channel = self._prefixed_sql("FOR CHANNEL", expression, "channel")
    792
    793            if expression.name == "ENGINE":
    794                mutex_or_status = " MUTEX" if expression.args.get("mutex") else " STATUS"
    795            else:
    796                mutex_or_status = ""
    797
    798            return f"SHOW{full}{global_}{this}{target}{types}{db}{query}{log}{position}{channel}{mutex_or_status}{like}{where}{offset}{limit}"
    799
    800        def _prefixed_sql(self, prefix: str, expression: exp.Expression, arg: str) -> str:
    801            sql = self.sql(expression, arg)
    802            return f" {prefix} {sql}" if sql else ""
    803
    804        def _oldstyle_limit_sql(self, expression: exp.Show) -> str:
    805            limit = self.sql(expression, "limit")
    806            offset = self.sql(expression, "offset")
    807            if limit:
    808                limit_offset = f"{offset}, {limit}" if offset else limit
    809                return f" LIMIT {limit_offset}"
    810            return ""
    811
    812        def chr_sql(self, expression: exp.Chr) -> str:
    813            this = self.expressions(sqls=[expression.this] + expression.expressions)
    814            charset = expression.args.get("charset")
    815            using = f" USING {self.sql(charset)}" if charset else ""
    816            return f"CHAR({this}{using})"

IDENTIFIERS_CAN_START_WITH_DIGIT = True
TIME_FORMAT = "'%Y-%m-%d %T'"
DPIPE_IS_STRING_CONCAT = False
SUPPORTS_USER_DEFINED_TYPES = False
SUPPORTS_SEMI_ANTI_JOIN = False
TIME_MAPPING: Dict[str, str] = {'%M': '%B', '%c': '%-m', '%e': '%-d', '%h': '%I', '%i': '%M', '%s': '%S', '%u': '%W', '%k': '%-H', '%l': '%-I', '%T': '%H:%M:%S', '%W': '%a'}
tokenizer_class = <class 'MySQL.Tokenizer'>
parser_class = <class 'MySQL.Parser'>
generator_class = <class 'MySQL.Generator'>
TIME_TRIE: Dict = {'%': {'M': {0: True}, 'c': {0: True}, 'e': {0: True}, 'h': {0: True}, 'i': {0: True}, 's': {0: True}, 'u': {0: True}, 'k': {0: True}, 'l': {0: True}, 'T': {0: True}, 'W': {0: True}}}
FORMAT_TRIE: Dict = {'%': {'M': {0: True}, 'c': {0: True}, 'e': {0: True}, 'h': {0: True}, 'i': {0: True}, 's': {0: True}, 'u': {0: True}, 'k': {0: True}, 'l': {0: True}, 'T': {0: True}, 'W': {0: True}}}
INVERSE_TIME_MAPPING: Dict[str, str] = {'%B': '%M', '%-m': '%c', '%-d': '%e', '%I': '%h', '%M': '%i', '%S': '%s', '%W': '%u', '%-H': '%k', '%-I': '%l', '%H:%M:%S': '%T', '%a': '%W'}
INVERSE_TIME_TRIE: Dict = {'%': {'B': {0: True}, '-': {'m': {0: True}, 'd': {0: True}, 'H': {0: True}, 'I': {0: True}}, 'I': {0: True}, 'M': {0: True}, 'S': {0: True}, 'W': {0: True}, 'H': {':': {'%': {'M': {':': {'%': {'S': {0: True}}}}}}}, 'a': {0: True}}}
INVERSE_ESCAPE_SEQUENCES: Dict[str, str] = {}
QUOTE_START = "'"
QUOTE_END = "'"
IDENTIFIER_START = '`'
IDENTIFIER_END = '`'
BIT_START = "b'"
BIT_END = "'"
HEX_START = "x'"
HEX_END = "'"
BYTE_START = None
BYTE_END = None

##### Inherited Members

sqlglot.dialects.dialect.Dialect
  INDEX_OFFSET
  UNNEST_COLUMN_ONLY
  ALIAS_POST_TABLESAMPLE
  RESOLVES_IDENTIFIERS_AS_UPPERCASE
  STRICT_STRING_CONCAT
  NORMALIZE_FUNCTIONS
  LOG_BASE_FIRST
  NULL_ORDERING
  DATE_FORMAT
  DATEINT_FORMAT
  FORMAT_MAPPING
  ESCAPE_SEQUENCES
  PSEUDOCOLUMNS
  get_or_raise
  format_time
  normalize_identifier
  case_sensitive
  can_identify
  quote_identifier
  parse
  parse_into
  generate
  transpile
  tokenize
  tokenizer
  parser
  generator

class MySQL.Tokenizer(sqlglot.tokens.Tokenizer): View Source

    174    class Tokenizer(tokens.Tokenizer):
    175        QUOTES = ["'", '"']
    176        COMMENTS = ["--", "#", ("/*", "*/")]
    177        IDENTIFIERS = ["`"]
    178        STRING_ESCAPES = ["'", '"', "\\"]
    179        BIT_STRINGS = [("b'", "'"), ("B'", "'"), ("0b", "")]
    180        HEX_STRINGS = [("x'", "'"), ("X'", "'"), ("0x", "")]
    181
    182        KEYWORDS = {
    183            **tokens.Tokenizer.KEYWORDS,
    184            "CHARSET": TokenType.CHARACTER_SET,
    185            "ENUM": TokenType.ENUM,
    186            "FORCE": TokenType.FORCE,
    187            "IGNORE": TokenType.IGNORE,
    188            "LOCK TABLES": TokenType.COMMAND,
    189            "LONGBLOB": TokenType.LONGBLOB,
    190            "LONGTEXT": TokenType.LONGTEXT,
    191            "MEDIUMBLOB": TokenType.MEDIUMBLOB,
    192            "TINYBLOB": TokenType.TINYBLOB,
    193            "TINYTEXT": TokenType.TINYTEXT,
    194            "MEDIUMTEXT": TokenType.MEDIUMTEXT,
    195            "MEDIUMINT": TokenType.MEDIUMINT,
    196            "MEMBER OF": TokenType.MEMBER_OF,
    197            "SEPARATOR": TokenType.SEPARATOR,
    198            "START": TokenType.BEGIN,
    199            "SIGNED": TokenType.BIGINT,
    200            "SIGNED INTEGER": TokenType.BIGINT,
    201            "UNLOCK TABLES": TokenType.COMMAND,
    202            "UNSIGNED": TokenType.UBIGINT,
    203            "UNSIGNED INTEGER": TokenType.UBIGINT,
    204            "YEAR": TokenType.YEAR,
    205            "_ARMSCII8": TokenType.INTRODUCER,
    206            "_ASCII": TokenType.INTRODUCER,
    207            "_BIG5": TokenType.INTRODUCER,
    208            "_BINARY": TokenType.INTRODUCER,
    209            "_CP1250": TokenType.INTRODUCER,
    210            "_CP1251": TokenType.INTRODUCER,
    211            "_CP1256": TokenType.INTRODUCER,
    212            "_CP1257": TokenType.INTRODUCER,
    213            "_CP850": TokenType.INTRODUCER,
    214            "_CP852": TokenType.INTRODUCER,
    215            "_CP866": TokenType.INTRODUCER,
    216            "_CP932": TokenType.INTRODUCER,
    217            "_DEC8": TokenType.INTRODUCER,
    218            "_EUCJPMS": TokenType.INTRODUCER,
    219            "_EUCKR": TokenType.INTRODUCER,
    220            "_GB18030": TokenType.INTRODUCER,
    221            "_GB2312": TokenType.INTRODUCER,
    222            "_GBK": TokenType.INTRODUCER,
    223            "_GEOSTD8": TokenType.INTRODUCER,
    224            "_GREEK": TokenType.INTRODUCER,
    225            "_HEBREW": TokenType.INTRODUCER,
    226            "_HP8": TokenType.INTRODUCER,
    227            "_KEYBCS2": TokenType.INTRODUCER,
    228            "_KOI8R": TokenType.INTRODUCER,
    229            "_KOI8U": TokenType.INTRODUCER,
    230            "_LATIN1": TokenType.INTRODUCER,
    231            "_LATIN2": TokenType.INTRODUCER,
    232            "_LATIN5": TokenType.INTRODUCER,
    233            "_LATIN7": TokenType.INTRODUCER,
    234            "_MACCE": TokenType.INTRODUCER,
    235            "_MACROMAN": TokenType.INTRODUCER,
    236            "_SJIS": TokenType.INTRODUCER,
    237            "_SWE7": TokenType.INTRODUCER,
    238            "_TIS620": TokenType.INTRODUCER,
    239            "_UCS2": TokenType.INTRODUCER,
    240            "_UJIS": TokenType.INTRODUCER,
    241            # https://dev.mysql.com/doc/refman/8.0/en/string-literals.html
    242            "_UTF8": TokenType.INTRODUCER,
    243            "_UTF16": TokenType.INTRODUCER,
    244            "_UTF16LE": TokenType.INTRODUCER,
    245            "_UTF32": TokenType.INTRODUCER,
    246            "_UTF8MB3": TokenType.INTRODUCER,
    247            "_UTF8MB4": TokenType.INTRODUCER,
    248            "@@": TokenType.SESSION_PARAMETER,
    249        }
    250
    251        COMMANDS = tokens.Tokenizer.COMMANDS - {TokenType.SHOW}

QUOTES = ["'", '"']
COMMENTS = ['--', '#', ('/*', '*/')]
IDENTIFIERS = ['`']
STRING_ESCAPES = ["'", '"', '\\']
BIT_STRINGS = [("b'", "'"), ("B'", "'"), ('0b', '')]
HEX_STRINGS = [("x'", "'"), ("X'", "'"), ('0x', '')]
KEYWORDS = {'{%': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%-': <TokenType.BLOCK_START: 'BLOCK_START'>, '%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '+%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '{{+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{{-': <TokenType.BLOCK_START: 'BLOCK_START'>, '+}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '/*+': <TokenType.HINT: 'HINT'>, '==': <TokenType.EQ: 'EQ'>, '::': <TokenType.DCOLON: 'DCOLON'>, '||': <TokenType.DPIPE: 'DPIPE'>, '>=': <TokenType.GTE: 'GTE'>, '<=': <TokenType.LTE: 'LTE'>, '<>': <TokenType.NEQ: 'NEQ'>, '!=': <TokenType.NEQ: 'NEQ'>, '<=>': <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>, '->': <TokenType.ARROW: 'ARROW'>, '->>': <TokenType.DARROW: 'DARROW'>, '=>': <TokenType.FARROW: 'FARROW'>, '#>': <TokenType.HASH_ARROW: 'HASH_ARROW'>, '#>>': <TokenType.DHASH_ARROW: 'DHASH_ARROW'>, '<->': <TokenType.LR_ARROW: 'LR_ARROW'>, '&&': <TokenType.DAMP: 'DAMP'>, '??': <TokenType.DQMARK: 'DQMARK'>, 'ALL': <TokenType.ALL: 'ALL'>, 'ALWAYS': <TokenType.ALWAYS: 'ALWAYS'>, 'AND': <TokenType.AND: 'AND'>, 'ANTI': <TokenType.ANTI: 'ANTI'>, 'ANY': <TokenType.ANY: 'ANY'>, 'ASC': <TokenType.ASC: 'ASC'>, 'AS': <TokenType.ALIAS: 'ALIAS'>, 'ASOF': <TokenType.ASOF: 'ASOF'>, 'AUTOINCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'AUTO_INCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'BEGIN': <TokenType.BEGIN: 'BEGIN'>, 'BETWEEN': <TokenType.BETWEEN: 'BETWEEN'>, 'CACHE': <TokenType.CACHE: 'CACHE'>, 'UNCACHE': <TokenType.UNCACHE: 'UNCACHE'>, 'CASE': <TokenType.CASE: 'CASE'>, 'CHARACTER SET': <TokenType.CHARACTER_SET: 'CHARACTER_SET'>, 'CLUSTER BY': <TokenType.CLUSTER_BY: 'CLUSTER_BY'>, 'COLLATE': <TokenType.COLLATE: 'COLLATE'>, 'COLUMN': <TokenType.COLUMN: 'COLUMN'>, 'COMMIT': <TokenType.COMMIT: 'COMMIT'>, 'CONNECT BY': <TokenType.CONNECT_BY: 'CONNECT_BY'>, 'CONSTRAINT': <TokenType.CONSTRAINT: 'CONSTRAINT'>, 'CREATE': <TokenType.CREATE: 'CREATE'>, 'CROSS': <TokenType.CROSS: 'CROSS'>, 'CUBE': <TokenType.CUBE: 'CUBE'>, 'CURRENT_DATE': <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, 'CURRENT_TIME': <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, 'CURRENT_TIMESTAMP': <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, 'CURRENT_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>, 'DATABASE': <TokenType.DATABASE: 'DATABASE'>, 'DEFAULT': <TokenType.DEFAULT: 'DEFAULT'>, 'DELETE': <TokenType.DELETE: 'DELETE'>, 'DESC': <TokenType.DESC: 'DESC'>, 'DESCRIBE': <TokenType.DESCRIBE: 'DESCRIBE'>, 'DISTINCT': <TokenType.DISTINCT: 'DISTINCT'>, 'DISTRIBUTE BY': <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>, 'DIV': <TokenType.DIV: 'DIV'>, 'DROP': <TokenType.DROP: 'DROP'>, 'ELSE': <TokenType.ELSE: 'ELSE'>, 'END': <TokenType.END: 'END'>, 'ESCAPE': <TokenType.ESCAPE: 'ESCAPE'>, 'EXCEPT': <TokenType.EXCEPT: 'EXCEPT'>, 'EXECUTE': <TokenType.EXECUTE: 'EXECUTE'>, 'EXISTS': <TokenType.EXISTS: 'EXISTS'>, 'FALSE': <TokenType.FALSE: 'FALSE'>, 'FETCH': <TokenType.FETCH: 'FETCH'>, 'FILTER': <TokenType.FILTER: 'FILTER'>, 'FIRST': <TokenType.FIRST: 'FIRST'>, 'FULL': <TokenType.FULL: 'FULL'>, 'FUNCTION': <TokenType.FUNCTION: 'FUNCTION'>, 'FOR': <TokenType.FOR: 'FOR'>, 'FOREIGN KEY': <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, 'FORMAT': <TokenType.FORMAT: 'FORMAT'>, 'FROM': <TokenType.FROM: 'FROM'>, 'GEOGRAPHY': <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, 'GEOMETRY': <TokenType.GEOMETRY: 'GEOMETRY'>, 'GLOB': <TokenType.GLOB: 'GLOB'>, 'GROUP BY': <TokenType.GROUP_BY: 'GROUP_BY'>, 'GROUPING SETS': <TokenType.GROUPING_SETS: 'GROUPING_SETS'>, 'HAVING': <TokenType.HAVING: 'HAVING'>, 'ILIKE': <TokenType.ILIKE: 'ILIKE'>, 'IN': <TokenType.IN: 'IN'>, 'INDEX': <TokenType.INDEX: 'INDEX'>, 'INET': <TokenType.INET: 'INET'>, 'INNER': <TokenType.INNER: 'INNER'>, 'INSERT': <TokenType.INSERT: 'INSERT'>, 'INTERVAL': <TokenType.INTERVAL: 'INTERVAL'>, 'INTERSECT': <TokenType.INTERSECT: 'INTERSECT'>, 'INTO': <TokenType.INTO: 'INTO'>, 'IS': <TokenType.IS: 'IS'>, 'ISNULL': <TokenType.ISNULL: 'ISNULL'>, 'JOIN': <TokenType.JOIN: 'JOIN'>, 'KEEP': <TokenType.KEEP: 'KEEP'>, 'KILL': <TokenType.KILL: 'KILL'>, 'LATERAL': <TokenType.LATERAL: 'LATERAL'>, 'LEFT': <TokenType.LEFT: 'LEFT'>, 'LIKE': <TokenType.LIKE: 'LIKE'>, 'LIMIT': <TokenType.LIMIT: 'LIMIT'>, 'LOAD': <TokenType.LOAD: 'LOAD'>, 'LOCK': <TokenType.LOCK: 'LOCK'>, 'MERGE': <TokenType.MERGE: 'MERGE'>, 'NATURAL': <TokenType.NATURAL: 'NATURAL'>, 'NEXT': <TokenType.NEXT: 'NEXT'>, 'NOT': <TokenType.NOT: 'NOT'>, 'NOTNULL': <TokenType.NOTNULL: 'NOTNULL'>, 'NULL': <TokenType.NULL: 'NULL'>, 'OBJECT': <TokenType.OBJECT: 'OBJECT'>, 'OFFSET': <TokenType.OFFSET: 'OFFSET'>, 'ON': <TokenType.ON: 'ON'>, 'OR': <TokenType.OR: 'OR'>, 'XOR': <TokenType.XOR: 'XOR'>, 'ORDER BY': <TokenType.ORDER_BY: 'ORDER_BY'>, 'ORDINALITY': <TokenType.ORDINALITY: 'ORDINALITY'>, 'OUTER': <TokenType.OUTER: 'OUTER'>, 'OVER': <TokenType.OVER: 'OVER'>, 'OVERLAPS': <TokenType.OVERLAPS: 'OVERLAPS'>, 'OVERWRITE': <TokenType.OVERWRITE: 'OVERWRITE'>, 'PARTITION': <TokenType.PARTITION: 'PARTITION'>, 'PARTITION BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED_BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PERCENT': <TokenType.PERCENT: 'PERCENT'>, 'PIVOT': <TokenType.PIVOT: 'PIVOT'>, 'PRAGMA': <TokenType.PRAGMA: 'PRAGMA'>, 'PRIMARY KEY': <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>, 'PROCEDURE': <TokenType.PROCEDURE: 'PROCEDURE'>, 'QUALIFY': <TokenType.QUALIFY: 'QUALIFY'>, 'RANGE': <TokenType.RANGE: 'RANGE'>, 'RECURSIVE': <TokenType.RECURSIVE: 'RECURSIVE'>, 'REGEXP': <TokenType.RLIKE: 'RLIKE'>, 'REPLACE': <TokenType.REPLACE: 'REPLACE'>, 'RETURNING': <TokenType.RETURNING: 'RETURNING'>, 'REFERENCES': <TokenType.REFERENCES: 'REFERENCES'>, 'RIGHT': <TokenType.RIGHT: 'RIGHT'>, 'RLIKE': <TokenType.RLIKE: 'RLIKE'>, 'ROLLBACK': <TokenType.ROLLBACK: 'ROLLBACK'>, 'ROLLUP': <TokenType.ROLLUP: 'ROLLUP'>, 'ROW': <TokenType.ROW: 'ROW'>, 'ROWS': <TokenType.ROWS: 'ROWS'>, 'SCHEMA': <TokenType.SCHEMA: 'SCHEMA'>, 'SELECT': <TokenType.SELECT: 'SELECT'>, 'SEMI': <TokenType.SEMI: 'SEMI'>, 'SET': <TokenType.SET: 'SET'>, 'SETTINGS': <TokenType.SETTINGS: 'SETTINGS'>, 'SHOW': <TokenType.SHOW: 'SHOW'>, 'SIMILAR TO': <TokenType.SIMILAR_TO: 'SIMILAR_TO'>, 'SOME': <TokenType.SOME: 'SOME'>, 'SORT BY': <TokenType.SORT_BY: 'SORT_BY'>, 'START WITH': <TokenType.START_WITH: 'START_WITH'>, 'TABLE': <TokenType.TABLE: 'TABLE'>, 'TABLESAMPLE': <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>, 'TEMP': <TokenType.TEMPORARY: 'TEMPORARY'>, 'TEMPORARY': <TokenType.TEMPORARY: 'TEMPORARY'>, 'THEN': <TokenType.THEN: 'THEN'>, 'TRUE': <TokenType.TRUE: 'TRUE'>, 'UNION': <TokenType.UNION: 'UNION'>, 'UNKNOWN': <TokenType.UNKNOWN: 'UNKNOWN'>, 'UNNEST': <TokenType.UNNEST: 'UNNEST'>, 'UNPIVOT': <TokenType.UNPIVOT: 'UNPIVOT'>, 'UPDATE': <TokenType.UPDATE: 'UPDATE'>, 'USE': <TokenType.USE: 'USE'>, 'USING': <TokenType.USING: 'USING'>, 'UUID': <TokenType.UUID: 'UUID'>, 'VALUES': <TokenType.VALUES: 'VALUES'>, 'VIEW': <TokenType.VIEW: 'VIEW'>, 'VOLATILE': <TokenType.VOLATILE: 'VOLATILE'>, 'WHEN': <TokenType.WHEN: 'WHEN'>, 'WHERE': <TokenType.WHERE: 'WHERE'>, 'WINDOW': <TokenType.WINDOW: 'WINDOW'>, 'WITH': <TokenType.WITH: 'WITH'>, 'APPLY': <TokenType.APPLY: 'APPLY'>, 'ARRAY': <TokenType.ARRAY: 'ARRAY'>, 'BIT': <TokenType.BIT: 'BIT'>, 'BOOL': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BOOLEAN': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BYTE': <TokenType.TINYINT: 'TINYINT'>, 'MEDIUMINT': <TokenType.MEDIUMINT: 'MEDIUMINT'>, 'TINYINT': <TokenType.TINYINT: 'TINYINT'>, 'SHORT': <TokenType.SMALLINT: 'SMALLINT'>, 'SMALLINT': <TokenType.SMALLINT: 'SMALLINT'>, 'INT128': <TokenType.INT128: 'INT128'>, 'INT2': <TokenType.SMALLINT: 'SMALLINT'>, 'INTEGER': <TokenType.INT: 'INT'>, 'INT': <TokenType.INT: 'INT'>, 'INT4': <TokenType.INT: 'INT'>, 'LONG': <TokenType.BIGINT: 'BIGINT'>, 'BIGINT': <TokenType.BIGINT: 'BIGINT'>, 'INT8': <TokenType.BIGINT: 'BIGINT'>, 'DEC': <TokenType.DECIMAL: 'DECIMAL'>, 'DECIMAL': <TokenType.DECIMAL: 'DECIMAL'>, 'BIGDECIMAL': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'BIGNUMERIC': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'MAP': <TokenType.MAP: 'MAP'>, 'NULLABLE': <TokenType.NULLABLE: 'NULLABLE'>, 'NUMBER': <TokenType.DECIMAL: 'DECIMAL'>, 'NUMERIC': <TokenType.DECIMAL: 'DECIMAL'>, 'FIXED': <TokenType.DECIMAL: 'DECIMAL'>, 'REAL': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT4': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT8': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE PRECISION': <TokenType.DOUBLE: 'DOUBLE'>, 'JSON': <TokenType.JSON: 'JSON'>, 'CHAR': <TokenType.CHAR: 'CHAR'>, 'CHARACTER': <TokenType.CHAR: 'CHAR'>, 'NCHAR': <TokenType.NCHAR: 'NCHAR'>, 'VARCHAR': <TokenType.VARCHAR: 'VARCHAR'>, 'VARCHAR2': <TokenType.VARCHAR: 'VARCHAR'>, 'NVARCHAR': <TokenType.NVARCHAR: 'NVARCHAR'>, 'NVARCHAR2': <TokenType.NVARCHAR: 'NVARCHAR'>, 'STR': <TokenType.TEXT: 'TEXT'>, 'STRING': <TokenType.TEXT: 'TEXT'>, 'TEXT': <TokenType.TEXT: 'TEXT'>, 'LONGTEXT': <TokenType.LONGTEXT: 'LONGTEXT'>, 'MEDIUMTEXT': <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, 'TINYTEXT': <TokenType.TINYTEXT: 'TINYTEXT'>, 'CLOB': <TokenType.TEXT: 'TEXT'>, 'LONGVARCHAR': <TokenType.TEXT: 'TEXT'>, 'BINARY': <TokenType.BINARY: 'BINARY'>, 'BLOB': <TokenType.VARBINARY: 'VARBINARY'>, 'LONGBLOB': <TokenType.LONGBLOB: 'LONGBLOB'>, 'MEDIUMBLOB': <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, 'TINYBLOB': <TokenType.TINYBLOB: 'TINYBLOB'>, 'BYTEA': <TokenType.VARBINARY: 'VARBINARY'>, 'VARBINARY': <TokenType.VARBINARY: 'VARBINARY'>, 'TIME': <TokenType.TIME: 'TIME'>, 'TIMETZ': <TokenType.TIMETZ: 'TIMETZ'>, 'TIMESTAMP': <TokenType.TIMESTAMP: 'TIMESTAMP'>, 'TIMESTAMPTZ': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'TIMESTAMPLTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'DATE': <TokenType.DATE: 'DATE'>, 'DATETIME': <TokenType.DATETIME: 'DATETIME'>, 'INT4RANGE': <TokenType.INT4RANGE: 'INT4RANGE'>, 'INT4MULTIRANGE': <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, 'INT8RANGE': <TokenType.INT8RANGE: 'INT8RANGE'>, 'INT8MULTIRANGE': <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, 'NUMRANGE': <TokenType.NUMRANGE: 'NUMRANGE'>, 'NUMMULTIRANGE': <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, 'TSRANGE': <TokenType.TSRANGE: 'TSRANGE'>, 'TSMULTIRANGE': <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, 'TSTZRANGE': <TokenType.TSTZRANGE: 'TSTZRANGE'>, 'TSTZMULTIRANGE': <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, 'DATERANGE': <TokenType.DATERANGE: 'DATERANGE'>, 'DATEMULTIRANGE': <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, 'UNIQUE': <TokenType.UNIQUE: 'UNIQUE'>, 'STRUCT': <TokenType.STRUCT: 'STRUCT'>, 'VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'ALTER': <TokenType.ALTER: 'ALTER'>, 'ANALYZE': <TokenType.COMMAND: 'COMMAND'>, 'CALL': <TokenType.COMMAND: 'COMMAND'>, 'COMMENT': <TokenType.COMMENT: 'COMMENT'>, 'COPY': <TokenType.COMMAND: 'COMMAND'>, 'EXPLAIN': <TokenType.COMMAND: 'COMMAND'>, 'GRANT': <TokenType.COMMAND: 'COMMAND'>, 'OPTIMIZE': <TokenType.COMMAND: 'COMMAND'>, 'PREPARE': <TokenType.COMMAND: 'COMMAND'>, 'TRUNCATE': <TokenType.COMMAND: 'COMMAND'>, 'VACUUM': <TokenType.COMMAND: 'COMMAND'>, 'USER-DEFINED': <TokenType.USERDEFINED: 'USERDEFINED'>, 'FOR VERSION': <TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>, 'FOR TIMESTAMP': <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>, 'CHARSET': <TokenType.CHARACTER_SET: 'CHARACTER_SET'>, 'ENUM': <TokenType.ENUM: 'ENUM'>, 'FORCE': <TokenType.FORCE: 'FORCE'>, 'IGNORE': <TokenType.IGNORE: 'IGNORE'>, 'LOCK TABLES': <TokenType.COMMAND: 'COMMAND'>, 'MEMBER OF': <TokenType.MEMBER_OF: 'MEMBER_OF'>, 'SEPARATOR': <TokenType.SEPARATOR: 'SEPARATOR'>, 'START': <TokenType.BEGIN: 'BEGIN'>, 'SIGNED': <TokenType.BIGINT: 'BIGINT'>, 'SIGNED INTEGER': <TokenType.BIGINT: 'BIGINT'>, 'UNLOCK TABLES': <TokenType.COMMAND: 'COMMAND'>, 'UNSIGNED': <TokenType.UBIGINT: 'UBIGINT'>, 'UNSIGNED INTEGER': <TokenType.UBIGINT: 'UBIGINT'>, 'YEAR': <TokenType.YEAR: 'YEAR'>, '_ARMSCII8': <TokenType.INTRODUCER: 'INTRODUCER'>, '_ASCII': <TokenType.INTRODUCER: 'INTRODUCER'>, '_BIG5': <TokenType.INTRODUCER: 'INTRODUCER'>, '_BINARY': <TokenType.INTRODUCER: 'INTRODUCER'>, '_CP1250': <TokenType.INTRODUCER: 'INTRODUCER'>, '_CP1251': <TokenType.INTRODUCER: 'INTRODUCER'>, '_CP1256': <TokenType.INTRODUCER: 'INTRODUCER'>, '_CP1257': <TokenType.INTRODUCER: 'INTRODUCER'>, '_CP850': <TokenType.INTRODUCER: 'INTRODUCER'>, '_CP852': <TokenType.INTRODUCER: 'INTRODUCER'>, '_CP866': <TokenType.INTRODUCER: 'INTRODUCER'>, '_CP932': <TokenType.INTRODUCER: 'INTRODUCER'>, '_DEC8': <TokenType.INTRODUCER: 'INTRODUCER'>, '_EUCJPMS': <TokenType.INTRODUCER: 'INTRODUCER'>, '_EUCKR': <TokenType.INTRODUCER: 'INTRODUCER'>, '_GB18030': <TokenType.INTRODUCER: 'INTRODUCER'>, '_GB2312': <TokenType.INTRODUCER: 'INTRODUCER'>, '_GBK': <TokenType.INTRODUCER: 'INTRODUCER'>, '_GEOSTD8': <TokenType.INTRODUCER: 'INTRODUCER'>, '_GREEK': <TokenType.INTRODUCER: 'INTRODUCER'>, '_HEBREW': <TokenType.INTRODUCER: 'INTRODUCER'>, '_HP8': <TokenType.INTRODUCER: 'INTRODUCER'>, '_KEYBCS2': <TokenType.INTRODUCER: 'INTRODUCER'>, '_KOI8R': <TokenType.INTRODUCER: 'INTRODUCER'>, '_KOI8U': <TokenType.INTRODUCER: 'INTRODUCER'>, '_LATIN1': <TokenType.INTRODUCER: 'INTRODUCER'>, '_LATIN2': <TokenType.INTRODUCER: 'INTRODUCER'>, '_LATIN5': <TokenType.INTRODUCER: 'INTRODUCER'>, '_LATIN7': <TokenType.INTRODUCER: 'INTRODUCER'>, '_MACCE': <TokenType.INTRODUCER: 'INTRODUCER'>, '_MACROMAN': <TokenType.INTRODUCER: 'INTRODUCER'>, '_SJIS': <TokenType.INTRODUCER: 'INTRODUCER'>, '_SWE7': <TokenType.INTRODUCER: 'INTRODUCER'>, '_TIS620': <TokenType.INTRODUCER: 'INTRODUCER'>, '_UCS2': <TokenType.INTRODUCER: 'INTRODUCER'>, '_UJIS': <TokenType.INTRODUCER: 'INTRODUCER'>, '_UTF8': <TokenType.INTRODUCER: 'INTRODUCER'>, '_UTF16': <TokenType.INTRODUCER: 'INTRODUCER'>, '_UTF16LE': <TokenType.INTRODUCER: 'INTRODUCER'>, '_UTF32': <TokenType.INTRODUCER: 'INTRODUCER'>, '_UTF8MB3': <TokenType.INTRODUCER: 'INTRODUCER'>, '_UTF8MB4': <TokenType.INTRODUCER: 'INTRODUCER'>, '@@': <TokenType.SESSION_PARAMETER: 'SESSION_PARAMETER'>}
COMMANDS = {<TokenType.EXECUTE: 'EXECUTE'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.FETCH: 'FETCH'>}
IDENTIFIERS_CAN_START_WITH_DIGIT: bool = True

##### Inherited Members

sqlglot.tokens.Tokenizer
  SINGLE_TOKENS
  BYTE_STRINGS
  RAW_STRINGS
  HEREDOC_STRINGS
  IDENTIFIER_ESCAPES
  VAR_SINGLE_TOKENS
  ESCAPE_SEQUENCES
  WHITE_SPACE
  COMMAND_PREFIX_TOKENS
  NUMERIC_LITERALS
  ENCODE
  reset
  tokenize
  peek
  size
  sql
  tokens

class MySQL.Parser(sqlglot.parser.Parser): View Source

    253    class Parser(parser.Parser):
    254        FUNC_TOKENS = {
    255            *parser.Parser.FUNC_TOKENS,
    256            TokenType.DATABASE,
    257            TokenType.SCHEMA,
    258            TokenType.VALUES,
    259        }
    260
    261        CONJUNCTION = {
    262            **parser.Parser.CONJUNCTION,
    263            TokenType.DAMP: exp.And,
    264            TokenType.XOR: exp.Xor,
    265            TokenType.DPIPE: exp.Or,
    266        }
    267
    268        # MySQL uses || as a synonym to the logical OR operator
    269        # https://dev.mysql.com/doc/refman/8.0/en/logical-operators.html#operator_or
    270        BITWISE = parser.Parser.BITWISE.copy()
    271        BITWISE.pop(TokenType.DPIPE)
    272
    273        TABLE_ALIAS_TOKENS = (
    274            parser.Parser.TABLE_ALIAS_TOKENS - parser.Parser.TABLE_INDEX_HINT_TOKENS
    275        )
    276
    277        RANGE_PARSERS = {
    278            **parser.Parser.RANGE_PARSERS,
    279            TokenType.MEMBER_OF: lambda self, this: self.expression(
    280                exp.JSONArrayContains,
    281                this=this,
    282                expression=self._parse_wrapped(self._parse_expression),
    283            ),
    284        }
    285
    286        FUNCTIONS = {
    287            **parser.Parser.FUNCTIONS,
    288            "DATE": lambda args: exp.TsOrDsToDate(this=seq_get(args, 0)),
    289            "DATE_ADD": parse_date_delta_with_interval(exp.DateAdd),
    290            "DATE_FORMAT": format_time_lambda(exp.TimeToStr, "mysql"),
    291            "DATE_SUB": parse_date_delta_with_interval(exp.DateSub),
    292            "INSTR": lambda args: exp.StrPosition(substr=seq_get(args, 1), this=seq_get(args, 0)),
    293            "ISNULL": isnull_to_is_null,
    294            "LOCATE": locate_to_strposition,
    295            "MONTHNAME": lambda args: exp.TimeToStr(
    296                this=exp.TsOrDsToDate(this=seq_get(args, 0)),
    297                format=exp.Literal.string("%B"),
    298            ),
    299            "STR_TO_DATE": _str_to_date,
    300            "TO_DAYS": lambda args: exp.paren(
    301                exp.DateDiff(
    302                    this=exp.TsOrDsToDate(this=seq_get(args, 0)),
    303                    expression=exp.TsOrDsToDate(this=exp.Literal.string("0000-01-01")),
    304                    unit=exp.var("DAY"),
    305                )
    306                + 1
    307            ),
    308            "DAY": lambda args: exp.Day(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    309            "DAYOFMONTH": lambda args: exp.DayOfMonth(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    310            "DAYOFWEEK": lambda args: exp.DayOfWeek(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    311            "DAYOFYEAR": lambda args: exp.DayOfYear(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    312            "MONTH": lambda args: exp.Month(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    313            "WEEK": lambda args: exp.Week(
    314                this=exp.TsOrDsToDate(this=seq_get(args, 0)), mode=seq_get(args, 1)
    315            ),
    316            "WEEKOFYEAR": lambda args: exp.WeekOfYear(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    317            "YEAR": lambda args: exp.Year(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    318        }
    319
    320        FUNCTION_PARSERS = {
    321            **parser.Parser.FUNCTION_PARSERS,
    322            "CHAR": lambda self: self._parse_chr(),
    323            "GROUP_CONCAT": lambda self: self.expression(
    324                exp.GroupConcat,
    325                this=self._parse_lambda(),
    326                separator=self._match(TokenType.SEPARATOR) and self._parse_field(),
    327            ),
    328            # https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_values
    329            "VALUES": lambda self: self.expression(
    330                exp.Anonymous, this="VALUES", expressions=[self._parse_id_var()]
    331            ),
    332        }
    333
    334        STATEMENT_PARSERS = {
    335            **parser.Parser.STATEMENT_PARSERS,
    336            TokenType.SHOW: lambda self: self._parse_show(),
    337        }
    338
    339        SHOW_PARSERS = {
    340            "BINARY LOGS": _show_parser("BINARY LOGS"),
    341            "MASTER LOGS": _show_parser("BINARY LOGS"),
    342            "BINLOG EVENTS": _show_parser("BINLOG EVENTS"),
    343            "CHARACTER SET": _show_parser("CHARACTER SET"),
    344            "CHARSET": _show_parser("CHARACTER SET"),
    345            "COLLATION": _show_parser("COLLATION"),
    346            "FULL COLUMNS": _show_parser("COLUMNS", target="FROM", full=True),
    347            "COLUMNS": _show_parser("COLUMNS", target="FROM"),
    348            "CREATE DATABASE": _show_parser("CREATE DATABASE", target=True),
    349            "CREATE EVENT": _show_parser("CREATE EVENT", target=True),
    350            "CREATE FUNCTION": _show_parser("CREATE FUNCTION", target=True),
    351            "CREATE PROCEDURE": _show_parser("CREATE PROCEDURE", target=True),
    352            "CREATE TABLE": _show_parser("CREATE TABLE", target=True),
    353            "CREATE TRIGGER": _show_parser("CREATE TRIGGER", target=True),
    354            "CREATE VIEW": _show_parser("CREATE VIEW", target=True),
    355            "DATABASES": _show_parser("DATABASES"),
    356            "ENGINE": _show_parser("ENGINE", target=True),
    357            "STORAGE ENGINES": _show_parser("ENGINES"),
    358            "ENGINES": _show_parser("ENGINES"),
    359            "ERRORS": _show_parser("ERRORS"),
    360            "EVENTS": _show_parser("EVENTS"),
    361            "FUNCTION CODE": _show_parser("FUNCTION CODE", target=True),
    362            "FUNCTION STATUS": _show_parser("FUNCTION STATUS"),
    363            "GRANTS": _show_parser("GRANTS", target="FOR"),
    364            "INDEX": _show_parser("INDEX", target="FROM"),
    365            "MASTER STATUS": _show_parser("MASTER STATUS"),
    366            "OPEN TABLES": _show_parser("OPEN TABLES"),
    367            "PLUGINS": _show_parser("PLUGINS"),
    368            "PROCEDURE CODE": _show_parser("PROCEDURE CODE", target=True),
    369            "PROCEDURE STATUS": _show_parser("PROCEDURE STATUS"),
    370            "PRIVILEGES": _show_parser("PRIVILEGES"),
    371            "FULL PROCESSLIST": _show_parser("PROCESSLIST", full=True),
    372            "PROCESSLIST": _show_parser("PROCESSLIST"),
    373            "PROFILE": _show_parser("PROFILE"),
    374            "PROFILES": _show_parser("PROFILES"),
    375            "RELAYLOG EVENTS": _show_parser("RELAYLOG EVENTS"),
    376            "REPLICAS": _show_parser("REPLICAS"),
    377            "SLAVE HOSTS": _show_parser("REPLICAS"),
    378            "REPLICA STATUS": _show_parser("REPLICA STATUS"),
    379            "SLAVE STATUS": _show_parser("REPLICA STATUS"),
    380            "GLOBAL STATUS": _show_parser("STATUS", global_=True),
    381            "SESSION STATUS": _show_parser("STATUS"),
    382            "STATUS": _show_parser("STATUS"),
    383            "TABLE STATUS": _show_parser("TABLE STATUS"),
    384            "FULL TABLES": _show_parser("TABLES", full=True),
    385            "TABLES": _show_parser("TABLES"),
    386            "TRIGGERS": _show_parser("TRIGGERS"),
    387            "GLOBAL VARIABLES": _show_parser("VARIABLES", global_=True),
    388            "SESSION VARIABLES": _show_parser("VARIABLES"),
    389            "VARIABLES": _show_parser("VARIABLES"),
    390            "WARNINGS": _show_parser("WARNINGS"),
    391        }
    392
    393        SET_PARSERS = {
    394            **parser.Parser.SET_PARSERS,
    395            "PERSIST": lambda self: self._parse_set_item_assignment("PERSIST"),
    396            "PERSIST_ONLY": lambda self: self._parse_set_item_assignment("PERSIST_ONLY"),
    397            "CHARACTER SET": lambda self: self._parse_set_item_charset("CHARACTER SET"),
    398            "CHARSET": lambda self: self._parse_set_item_charset("CHARACTER SET"),
    399            "NAMES": lambda self: self._parse_set_item_names(),
    400        }
    401
    402        CONSTRAINT_PARSERS = {
    403            **parser.Parser.CONSTRAINT_PARSERS,
    404            "FULLTEXT": lambda self: self._parse_index_constraint(kind="FULLTEXT"),
    405            "INDEX": lambda self: self._parse_index_constraint(),
    406            "KEY": lambda self: self._parse_index_constraint(),
    407            "SPATIAL": lambda self: self._parse_index_constraint(kind="SPATIAL"),
    408        }
    409
    410        SCHEMA_UNNAMED_CONSTRAINTS = {
    411            *parser.Parser.SCHEMA_UNNAMED_CONSTRAINTS,
    412            "FULLTEXT",
    413            "INDEX",
    414            "KEY",
    415            "SPATIAL",
    416        }
    417
    418        PROFILE_TYPES = {
    419            "ALL",
    420            "BLOCK IO",
    421            "CONTEXT SWITCHES",
    422            "CPU",
    423            "IPC",
    424            "MEMORY",
    425            "PAGE FAULTS",
    426            "SOURCE",
    427            "SWAPS",
    428        }
    429
    430        TYPE_TOKENS = {
    431            *parser.Parser.TYPE_TOKENS,
    432            TokenType.SET,
    433        }
    434
    435        ENUM_TYPE_TOKENS = {
    436            *parser.Parser.ENUM_TYPE_TOKENS,
    437            TokenType.SET,
    438        }
    439
    440        LOG_DEFAULTS_TO_LN = True
    441
    442        def _parse_primary_key_part(self) -> t.Optional[exp.Expression]:
    443            this = self._parse_id_var()
    444            if not self._match(TokenType.L_PAREN):
    445                return this
    446
    447            expression = self._parse_number()
    448            self._match_r_paren()
    449            return self.expression(exp.ColumnPrefix, this=this, expression=expression)
    450
    451        def _parse_index_constraint(
    452            self, kind: t.Optional[str] = None
    453        ) -> exp.IndexColumnConstraint:
    454            if kind:
    455                self._match_texts({"INDEX", "KEY"})
    456
    457            this = self._parse_id_var(any_token=False)
    458            index_type = self._match(TokenType.USING) and self._advance_any() and self._prev.text
    459            schema = self._parse_schema()
    460
    461            options = []
    462            while True:
    463                if self._match_text_seq("KEY_BLOCK_SIZE"):
    464                    self._match(TokenType.EQ)
    465                    opt = exp.IndexConstraintOption(key_block_size=self._parse_number())
    466                elif self._match(TokenType.USING):
    467                    opt = exp.IndexConstraintOption(using=self._advance_any() and self._prev.text)
    468                elif self._match_text_seq("WITH", "PARSER"):
    469                    opt = exp.IndexConstraintOption(parser=self._parse_var(any_token=True))
    470                elif self._match(TokenType.COMMENT):
    471                    opt = exp.IndexConstraintOption(comment=self._parse_string())
    472                elif self._match_text_seq("VISIBLE"):
    473                    opt = exp.IndexConstraintOption(visible=True)
    474                elif self._match_text_seq("INVISIBLE"):
    475                    opt = exp.IndexConstraintOption(visible=False)
    476                elif self._match_text_seq("ENGINE_ATTRIBUTE"):
    477                    self._match(TokenType.EQ)
    478                    opt = exp.IndexConstraintOption(engine_attr=self._parse_string())
    479                elif self._match_text_seq("ENGINE_ATTRIBUTE"):
    480                    self._match(TokenType.EQ)
    481                    opt = exp.IndexConstraintOption(engine_attr=self._parse_string())
    482                elif self._match_text_seq("SECONDARY_ENGINE_ATTRIBUTE"):
    483                    self._match(TokenType.EQ)
    484                    opt = exp.IndexConstraintOption(secondary_engine_attr=self._parse_string())
    485                else:
    486                    opt = None
    487
    488                if not opt:
    489                    break
    490
    491                options.append(opt)
    492
    493            return self.expression(
    494                exp.IndexColumnConstraint,
    495                this=this,
    496                schema=schema,
    497                kind=kind,
    498                index_type=index_type,
    499                options=options,
    500            )
    501
    502        def _parse_show_mysql(
    503            self,
    504            this: str,
    505            target: bool | str = False,
    506            full: t.Optional[bool] = None,
    507            global_: t.Optional[bool] = None,
    508        ) -> exp.Show:
    509            if target:
    510                if isinstance(target, str):
    511                    self._match_text_seq(target)
    512                target_id = self._parse_id_var()
    513            else:
    514                target_id = None
    515
    516            log = self._parse_string() if self._match_text_seq("IN") else None
    517
    518            if this in {"BINLOG EVENTS", "RELAYLOG EVENTS"}:
    519                position = self._parse_number() if self._match_text_seq("FROM") else None
    520                db = None
    521            else:
    522                position = None
    523                db = None
    524
    525                if self._match(TokenType.FROM):
    526                    db = self._parse_id_var()
    527                elif self._match(TokenType.DOT):
    528                    db = target_id
    529                    target_id = self._parse_id_var()
    530
    531            channel = self._parse_id_var() if self._match_text_seq("FOR", "CHANNEL") else None
    532
    533            like = self._parse_string() if self._match_text_seq("LIKE") else None
    534            where = self._parse_where()
    535
    536            if this == "PROFILE":
    537                types = self._parse_csv(lambda: self._parse_var_from_options(self.PROFILE_TYPES))
    538                query = self._parse_number() if self._match_text_seq("FOR", "QUERY") else None
    539                offset = self._parse_number() if self._match_text_seq("OFFSET") else None
    540                limit = self._parse_number() if self._match_text_seq("LIMIT") else None
    541            else:
    542                types, query = None, None
    543                offset, limit = self._parse_oldstyle_limit()
    544
    545            mutex = True if self._match_text_seq("MUTEX") else None
    546            mutex = False if self._match_text_seq("STATUS") else mutex
    547
    548            return self.expression(
    549                exp.Show,
    550                this=this,
    551                target=target_id,
    552                full=full,
    553                log=log,
    554                position=position,
    555                db=db,
    556                channel=channel,
    557                like=like,
    558                where=where,
    559                types=types,
    560                query=query,
    561                offset=offset,
    562                limit=limit,
    563                mutex=mutex,
    564                **{"global": global_},  # type: ignore
    565            )
    566
    567        def _parse_oldstyle_limit(
    568            self,
    569        ) -> t.Tuple[t.Optional[exp.Expression], t.Optional[exp.Expression]]:
    570            limit = None
    571            offset = None
    572            if self._match_text_seq("LIMIT"):
    573                parts = self._parse_csv(self._parse_number)
    574                if len(parts) == 1:
    575                    limit = parts[0]
    576                elif len(parts) == 2:
    577                    limit = parts[1]
    578                    offset = parts[0]
    579
    580            return offset, limit
    581
    582        def _parse_set_item_charset(self, kind: str) -> exp.Expression:
    583            this = self._parse_string() or self._parse_id_var()
    584            return self.expression(exp.SetItem, this=this, kind=kind)
    585
    586        def _parse_set_item_names(self) -> exp.Expression:
    587            charset = self._parse_string() or self._parse_id_var()
    588            if self._match_text_seq("COLLATE"):
    589                collate = self._parse_string() or self._parse_id_var()
    590            else:
    591                collate = None
    592
    593            return self.expression(exp.SetItem, this=charset, collate=collate, kind="NAMES")
    594
    595        def _parse_type(self, parse_interval: bool = True) -> t.Optional[exp.Expression]:
    596            # mysql binary is special and can work anywhere, even in order by operations
    597            # it operates like a no paren func
    598            if self._match(TokenType.BINARY, advance=False):
    599                data_type = self._parse_types(check_func=True, allow_identifiers=False)
    600
    601                if isinstance(data_type, exp.DataType):
    602                    return self.expression(exp.Cast, this=self._parse_column(), to=data_type)
    603
    604            return super()._parse_type(parse_interval=parse_interval)
    605
    606        def _parse_chr(self) -> t.Optional[exp.Expression]:
    607            expressions = self._parse_csv(self._parse_conjunction)
    608            kwargs: t.Dict[str, t.Any] = {"this": seq_get(expressions, 0)}
    609
    610            if len(expressions) > 1:
    611                kwargs["expressions"] = expressions[1:]
    612
    613            if self._match(TokenType.USING):
    614                kwargs["charset"] = self._parse_var()
    615
    616            return self.expression(exp.Chr, **kwargs)

Parser consumes a list of tokens produced by the Tokenizer and produces a parsed syntax tree.

###### Arguments:

- error_level: The desired error level. Default: ErrorLevel.IMMEDIATE
- error_message_context: Determines the amount of context to capture from a query string when displaying the error message (in number of characters). Default: 100
- max_errors: Maximum number of error messages to include in a raised ParseError. This is only relevant if error_level is ErrorLevel.RAISE. Default: 3

FUNC_TOKENS = {<TokenType.GEOMETRY: 'GEOMETRY'>, <TokenType.TINYINT: 'TINYINT'>, <TokenType.UUID: 'UUID'>, <TokenType.XML: 'XML'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.ANY: 'ANY'>, <TokenType.SUPER: 'SUPER'>, <TokenType.USERDEFINED: 'USERDEFINED'>, <TokenType.INTERVAL: 'INTERVAL'>, <TokenType.TIMESTAMP_S: 'TIMESTAMP_S'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.BOOLEAN: 'BOOLEAN'>, <TokenType.HLLSKETCH: 'HLLSKETCH'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.REPLACE: 'REPLACE'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.DATE: 'DATE'>, <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <TokenType.STRUCT: 'STRUCT'>, <TokenType.UINT256: 'UINT256'>, <TokenType.FILTER: 'FILTER'>, <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, <TokenType.SOME: 'SOME'>, <TokenType.INET: 'INET'>, <TokenType.BIT: 'BIT'>, <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.MERGE: 'MERGE'>, <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <TokenType.JSONB: 'JSONB'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.INT4RANGE: 'INT4RANGE'>, <TokenType.DOUBLE: 'DOUBLE'>, <TokenType.TINYTEXT: 'TINYTEXT'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.CHAR: 'CHAR'>, <TokenType.IPADDRESS: 'IPADDRESS'>, <TokenType.ILIKE: 'ILIKE'>, <TokenType.RANGE: 'RANGE'>, <TokenType.TIMETZ: 'TIMETZ'>, <TokenType.TIME: 'TIME'>, <TokenType.OFFSET: 'OFFSET'>, <TokenType.TINYBLOB: 'TINYBLOB'>, <TokenType.LONGTEXT: 'LONGTEXT'>, <TokenType.NULLABLE: 'NULLABLE'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>, <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>, <TokenType.VARBINARY: 'VARBINARY'>, <TokenType.ENUM: 'ENUM'>, <TokenType.FORMAT: 'FORMAT'>, <TokenType.LIKE: 'LIKE'>, <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, <TokenType.FLOAT: 'FLOAT'>, <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, <TokenType.VARCHAR: 'VARCHAR'>, <TokenType.RIGHT: 'RIGHT'>, <TokenType.SMALLINT: 'SMALLINT'>, <TokenType.NESTED: 'NESTED'>, <TokenType.NVARCHAR: 'NVARCHAR'>, <TokenType.LEFT: 'LEFT'>, <TokenType.INT256: 'INT256'>, <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, <TokenType.SMALLSERIAL: 'SMALLSERIAL'>, <TokenType.ALL: 'ALL'>, <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>, <TokenType.JSON: 'JSON'>, <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, <TokenType.XOR: 'XOR'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.DECIMAL: 'DECIMAL'>, <TokenType.TIMESTAMP_MS: 'TIMESTAMP_MS'>, <TokenType.VALUES: 'VALUES'>, <TokenType.VAR: 'VAR'>, <TokenType.NUMRANGE: 'NUMRANGE'>, <TokenType.GLOB: 'GLOB'>, <TokenType.FIXEDSTRING: 'FIXEDSTRING'>, <TokenType.IDENTIFIER: 'IDENTIFIER'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.TEXT: 'TEXT'>, <TokenType.DATERANGE: 'DATERANGE'>, <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, <TokenType.UNKNOWN: 'UNKNOWN'>, <TokenType.YEAR: 'YEAR'>, <TokenType.TABLE: 'TABLE'>, <TokenType.FIRST: 'FIRST'>, <TokenType.ENUM16: 'ENUM16'>, <TokenType.ROW: 'ROW'>, <TokenType.LONGBLOB: 'LONGBLOB'>, <TokenType.INT128: 'INT128'>, <TokenType.RLIKE: 'RLIKE'>, <TokenType.USMALLINT: 'USMALLINT'>, <TokenType.UINT128: 'UINT128'>, <TokenType.BIGINT: 'BIGINT'>, <TokenType.OBJECT: 'OBJECT'>, <TokenType.ENUM8: 'ENUM8'>, <TokenType.UMEDIUMINT: 'UMEDIUMINT'>, <TokenType.INT8RANGE: 'INT8RANGE'>, <TokenType.OBJECT_IDENTIFIER: 'OBJECT_IDENTIFIER'>, <TokenType.NCHAR: 'NCHAR'>, <TokenType.SERIAL: 'SERIAL'>, <TokenType.MEDIUMINT: 'MEDIUMINT'>, <TokenType.MAP: 'MAP'>, <TokenType.NULL: 'NULL'>, <TokenType.BINARY: 'BINARY'>, <TokenType.VARIANT: 'VARIANT'>, <TokenType.INSERT: 'INSERT'>, <TokenType.INDEX: 'INDEX'>, <TokenType.TSRANGE: 'TSRANGE'>, <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, <TokenType.ARRAY: 'ARRAY'>, <TokenType.BIGSERIAL: 'BIGSERIAL'>, <TokenType.MONEY: 'MONEY'>, <TokenType.SMALLMONEY: 'SMALLMONEY'>, <TokenType.UINT: 'UINT'>, <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, <TokenType.UTINYINT: 'UTINYINT'>, <TokenType.INT: 'INT'>, <TokenType.IMAGE: 'IMAGE'>, <TokenType.TIMESTAMP: 'TIMESTAMP'>, <TokenType.DATETIME: 'DATETIME'>, <TokenType.UNNEST: 'UNNEST'>, <TokenType.UBIGINT: 'UBIGINT'>, <TokenType.TSTZRANGE: 'TSTZRANGE'>, <TokenType.DATETIME64: 'DATETIME64'>, <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, <TokenType.WINDOW: 'WINDOW'>, <TokenType.HSTORE: 'HSTORE'>, <TokenType.IPPREFIX: 'IPPREFIX'>, <TokenType.ROWVERSION: 'ROWVERSION'>, <TokenType.UDECIMAL: 'UDECIMAL'>, <TokenType.TIMESTAMP_NS: 'TIMESTAMP_NS'>}
CONJUNCTION = {<TokenType.AND: 'AND'>: <class 'sqlglot.expressions.And'>, <TokenType.OR: 'OR'>: <class 'sqlglot.expressions.Or'>, <TokenType.DAMP: 'DAMP'>: <class 'sqlglot.expressions.And'>, <TokenType.XOR: 'XOR'>: <class 'sqlglot.expressions.Xor'>, <TokenType.DPIPE: 'DPIPE'>: <class 'sqlglot.expressions.Or'>}
BITWISE = {<TokenType.AMP: 'AMP'>: <class 'sqlglot.expressions.BitwiseAnd'>, <TokenType.CARET: 'CARET'>: <class 'sqlglot.expressions.BitwiseXor'>, <TokenType.PIPE: 'PIPE'>: <class 'sqlglot.expressions.BitwiseOr'>}
TABLE_ALIAS_TOKENS = {<TokenType.GEOMETRY: 'GEOMETRY'>, <TokenType.TINYINT: 'TINYINT'>, <TokenType.UUID: 'UUID'>, <TokenType.XML: 'XML'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.KILL: 'KILL'>, <TokenType.ANY: 'ANY'>, <TokenType.SUPER: 'SUPER'>, <TokenType.USERDEFINED: 'USERDEFINED'>, <TokenType.INTERVAL: 'INTERVAL'>, <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, <TokenType.TIMESTAMP_S: 'TIMESTAMP_S'>, <TokenType.BOOLEAN: 'BOOLEAN'>, <TokenType.HLLSKETCH: 'HLLSKETCH'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.DATE: 'DATE'>, <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <TokenType.STRUCT: 'STRUCT'>, <TokenType.UINT256: 'UINT256'>, <TokenType.FILTER: 'FILTER'>, <TokenType.CASE: 'CASE'>, <TokenType.VIEW: 'VIEW'>, <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, <TokenType.ANTI: 'ANTI'>, <TokenType.PERCENT: 'PERCENT'>, <TokenType.SOME: 'SOME'>, <TokenType.INET: 'INET'>, <TokenType.BIT: 'BIT'>, <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, <TokenType.TOP: 'TOP'>, <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.MERGE: 'MERGE'>, <TokenType.UNPIVOT: 'UNPIVOT'>, <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <TokenType.JSONB: 'JSONB'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.INT4RANGE: 'INT4RANGE'>, <TokenType.DOUBLE: 'DOUBLE'>, <TokenType.TINYTEXT: 'TINYTEXT'>, <TokenType.END: 'END'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.MODEL: 'MODEL'>, <TokenType.CHAR: 'CHAR'>, <TokenType.RANGE: 'RANGE'>, <TokenType.UNIQUE: 'UNIQUE'>, <TokenType.IPADDRESS: 'IPADDRESS'>, <TokenType.TIMETZ: 'TIMETZ'>, <TokenType.TIME: 'TIME'>, <TokenType.DICTIONARY: 'DICTIONARY'>, <TokenType.TINYBLOB: 'TINYBLOB'>, <TokenType.VOLATILE: 'VOLATILE'>, <TokenType.LONGTEXT: 'LONGTEXT'>, <TokenType.NULLABLE: 'NULLABLE'>, <TokenType.TEMPORARY: 'TEMPORARY'>, <TokenType.DESCRIBE: 'DESCRIBE'>, <TokenType.DEFAULT: 'DEFAULT'>, <TokenType.REFERENCES: 'REFERENCES'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.PIVOT: 'PIVOT'>, <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>, <TokenType.VARBINARY: 'VARBINARY'>, <TokenType.ENUM: 'ENUM'>, <TokenType.FORMAT: 'FORMAT'>, <TokenType.IS: 'IS'>, <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.FLOAT: 'FLOAT'>, <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, <TokenType.VARCHAR: 'VARCHAR'>, <TokenType.SMALLINT: 'SMALLINT'>, <TokenType.NESTED: 'NESTED'>, <TokenType.NVARCHAR: 'NVARCHAR'>, <TokenType.INT256: 'INT256'>, <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, <TokenType.SMALLSERIAL: 'SMALLSERIAL'>, <TokenType.ALL: 'ALL'>, <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>, <TokenType.COMMENT: 'COMMENT'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.JSON: 'JSON'>, <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, <TokenType.DECIMAL: 'DECIMAL'>, <TokenType.TIMESTAMP_MS: 'TIMESTAMP_MS'>, <TokenType.OVERWRITE: 'OVERWRITE'>, <TokenType.VAR: 'VAR'>, <TokenType.KEEP: 'KEEP'>, <TokenType.ORDINALITY: 'ORDINALITY'>, <TokenType.NUMRANGE: 'NUMRANGE'>, <TokenType.BEGIN: 'BEGIN'>, <TokenType.TRUE: 'TRUE'>, <TokenType.FIXEDSTRING: 'FIXEDSTRING'>, <TokenType.FUNCTION: 'FUNCTION'>, <TokenType.TEXT: 'TEXT'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.DATERANGE: 'DATERANGE'>, <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, <TokenType.UNKNOWN: 'UNKNOWN'>, <TokenType.YEAR: 'YEAR'>, <TokenType.TABLE: 'TABLE'>, <TokenType.FALSE: 'FALSE'>, <TokenType.SHOW: 'SHOW'>, <TokenType.FIRST: 'FIRST'>, <TokenType.ENUM16: 'ENUM16'>, <TokenType.COMMIT: 'COMMIT'>, <TokenType.DIV: 'DIV'>, <TokenType.ROW: 'ROW'>, <TokenType.LONGBLOB: 'LONGBLOB'>, <TokenType.INT128: 'INT128'>, <TokenType.USMALLINT: 'USMALLINT'>, <TokenType.UINT128: 'UINT128'>, <TokenType.BIGINT: 'BIGINT'>, <TokenType.OBJECT: 'OBJECT'>, <TokenType.ESCAPE: 'ESCAPE'>, <TokenType.ENUM8: 'ENUM8'>, <TokenType.UMEDIUMINT: 'UMEDIUMINT'>, <TokenType.INT8RANGE: 'INT8RANGE'>, <TokenType.SETTINGS: 'SETTINGS'>, <TokenType.CONSTRAINT: 'CONSTRAINT'>, <TokenType.COLUMN: 'COLUMN'>, <TokenType.OBJECT_IDENTIFIER: 'OBJECT_IDENTIFIER'>, <TokenType.NCHAR: 'NCHAR'>, <TokenType.SET: 'SET'>, <TokenType.SERIAL: 'SERIAL'>, <TokenType.MEDIUMINT: 'MEDIUMINT'>, <TokenType.MAP: 'MAP'>, <TokenType.OVERLAPS: 'OVERLAPS'>, <TokenType.NULL: 'NULL'>, <TokenType.BINARY: 'BINARY'>, <TokenType.VARIANT: 'VARIANT'>, <TokenType.INDEX: 'INDEX'>, <TokenType.TSRANGE: 'TSRANGE'>, <TokenType.CACHE: 'CACHE'>, <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, <TokenType.ARRAY: 'ARRAY'>, <TokenType.LOAD: 'LOAD'>, <TokenType.BIGSERIAL: 'BIGSERIAL'>, <TokenType.MONEY: 'MONEY'>, <TokenType.SMALLMONEY: 'SMALLMONEY'>, <TokenType.UINT: 'UINT'>, <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, <TokenType.UTINYINT: 'UTINYINT'>, <TokenType.INT: 'INT'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.IMAGE: 'IMAGE'>, <TokenType.TIMESTAMP: 'TIMESTAMP'>, <TokenType.ASC: 'ASC'>, <TokenType.DATETIME: 'DATETIME'>, <TokenType.PRAGMA: 'PRAGMA'>, <TokenType.UBIGINT: 'UBIGINT'>, <TokenType.SEMI: 'SEMI'>, <TokenType.TSTZRANGE: 'TSTZRANGE'>, <TokenType.DELETE: 'DELETE'>, <TokenType.PROCEDURE: 'PROCEDURE'>, <TokenType.DATETIME64: 'DATETIME64'>, <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, <TokenType.HSTORE: 'HSTORE'>, <TokenType.IPPREFIX: 'IPPREFIX'>, <TokenType.ROWS: 'ROWS'>, <TokenType.ROWVERSION: 'ROWVERSION'>, <TokenType.UDECIMAL: 'UDECIMAL'>, <TokenType.DESC: 'DESC'>, <TokenType.NEXT: 'NEXT'>, <TokenType.PARTITION: 'PARTITION'>, <TokenType.TIMESTAMP_NS: 'TIMESTAMP_NS'>}
RANGE_PARSERS = {<TokenType.BETWEEN: 'BETWEEN'>: <function Parser.<lambda>>, <TokenType.GLOB: 'GLOB'>: <function binary_range_parser.<locals>.<lambda>>, <TokenType.ILIKE: 'ILIKE'>: <function binary_range_parser.<locals>.<lambda>>, <TokenType.IN: 'IN'>: <function Parser.<lambda>>, <TokenType.IRLIKE: 'IRLIKE'>: <function binary_range_parser.<locals>.<lambda>>, <TokenType.IS: 'IS'>: <function Parser.<lambda>>, <TokenType.LIKE: 'LIKE'>: <function binary_range_parser.<locals>.<lambda>>, <TokenType.OVERLAPS: 'OVERLAPS'>: <function binary_range_parser.<locals>.<lambda>>, <TokenType.RLIKE: 'RLIKE'>: <function binary_range_parser.<locals>.<lambda>>, <TokenType.SIMILAR_TO: 'SIMILAR_TO'>: <function binary_range_parser.<locals>.<lambda>>, <TokenType.FOR: 'FOR'>: <function Parser.<lambda>>, <TokenType.MEMBER_OF: 'MEMBER_OF'>: <function MySQL.Parser.<lambda>>}
FUNCTIONS = {'ABS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Abs'>>, 'ANY_VALUE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.AnyValue'>>, 'APPROX_DISTINCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxDistinct'>>, 'APPROX_COUNT_DISTINCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxDistinct'>>, 'APPROX_QUANTILE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxQuantile'>>, 'APPROX_TOP_K': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxTopK'>>, 'ARG_MAX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMax'>>, 'ARGMAX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMax'>>, 'MAX_BY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMax'>>, 'ARG_MIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMin'>>, 'ARGMIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMin'>>, 'MIN_BY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMin'>>, 'ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Array'>>, 'ARRAY_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAgg'>>, 'ARRAY_ALL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAll'>>, 'ARRAY_ANY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAny'>>, 'ARRAY_CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayConcat'>>, 'ARRAY_CAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayConcat'>>, 'ARRAY_CONTAINS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayContains'>>, 'FILTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayFilter'>>, 'ARRAY_FILTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayFilter'>>, 'ARRAY_JOIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayJoin'>>, 'ARRAY_SIZE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySize'>>, 'ARRAY_SORT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySort'>>, 'ARRAY_SUM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySum'>>, 'ARRAY_UNION_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayUnionAgg'>>, 'AVG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Avg'>>, 'CASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Case'>>, 'CAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Cast'>>, 'CAST_TO_STR_TYPE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CastToStrType'>>, 'CEIL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ceil'>>, 'CEILING': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ceil'>>, 'CHR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Chr'>>, 'CHAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Chr'>>, 'COALESCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'IFNULL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'NVL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'COLLATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Collate'>>, 'CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Concat'>>, 'CONCAT_WS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ConcatWs'>>, 'COUNT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Count'>>, 'COUNT_IF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CountIf'>>, 'CURRENT_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentDate'>>, 'CURRENT_DATETIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentDatetime'>>, 'CURRENT_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTime'>>, 'CURRENT_TIMESTAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTimestamp'>>, 'CURRENT_USER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>, 'DATE': <function MySQL.Parser.<lambda>>, 'DATE_ADD': <function parse_date_delta_with_interval.<locals>.func>, 'DATEDIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateDiff'>>, 'DATE_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateDiff'>>, 'DATEFROMPARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateFromParts'>>, 'DATE_STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateStrToDate'>>, 'DATE_SUB': <function parse_date_delta_with_interval.<locals>.func>, 'DATE_TO_DATE_STR': <function Parser.<lambda>>, 'DATE_TO_DI': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateToDi'>>, 'DATE_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateTrunc'>>, 'DATETIME_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeAdd'>>, 'DATETIME_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeDiff'>>, 'DATETIME_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeSub'>>, 'DATETIME_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeTrunc'>>, 'DAY': <function MySQL.Parser.<lambda>>, 'DAY_OF_MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfMonth'>>, 'DAYOFMONTH': <function MySQL.Parser.<lambda>>, 'DAY_OF_WEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfWeek'>>, 'DAYOFWEEK': <function MySQL.Parser.<lambda>>, 'DAY_OF_YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfYear'>>, 'DAYOFYEAR': <function MySQL.Parser.<lambda>>, 'DECODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Decode'>>, 'DI_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DiToDate'>>, 'ENCODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Encode'>>, 'EXP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Exp'>>, 'EXPLODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Explode'>>, 'EXPLODE_OUTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ExplodeOuter'>>, 'EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Extract'>>, 'FIRST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.First'>>, 'FLATTEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Flatten'>>, 'FLOOR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Floor'>>, 'FROM_BASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.FromBase'>>, 'FROM_BASE64': <bound method Func.from_arg_list of <class 'sqlglot.expressions.FromBase64'>>, 'GENERATE_SERIES': <bound method Func.from_arg_list of <class 'sqlglot.expressions.GenerateSeries'>>, 'GREATEST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Greatest'>>, 'GROUP_CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.GroupConcat'>>, 'HEX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Hex'>>, 'HLL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Hll'>>, 'IF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.If'>>, 'INITCAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Initcap'>>, 'IS_NAN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.IsNan'>>, 'ISNAN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.IsNan'>>, 'J_S_O_N_ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONArray'>>, 'J_S_O_N_ARRAY_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONArrayAgg'>>, 'JSON_ARRAY_CONTAINS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONArrayContains'>>, 'JSONB_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONBExtract'>>, 'JSONB_EXTRACT_SCALAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONBExtractScalar'>>, 'JSON_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONExtract'>>, 'JSON_EXTRACT_SCALAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONExtractScalar'>>, 'JSON_FORMAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONFormat'>>, 'J_S_O_N_OBJECT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONObject'>>, 'J_S_O_N_TABLE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONTable'>>, 'LAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Last'>>, 'LAST_DATE_OF_MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LastDateOfMonth'>>, 'LEAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Least'>>, 'LEFT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Left'>>, 'LENGTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Length'>>, 'LEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Length'>>, 'LEVENSHTEIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Levenshtein'>>, 'LN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ln'>>, 'LOG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Log'>>, 'LOG10': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Log10'>>, 'LOG2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Log2'>>, 'LOGICAL_AND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'BOOL_AND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'BOOLAND_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'LOGICAL_OR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'BOOL_OR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'BOOLOR_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'LOWER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Lower'>>, 'LCASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Lower'>>, 'MD5': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MD5'>>, 'MD5_DIGEST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MD5Digest'>>, 'MAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Map'>>, 'MAP_FROM_ENTRIES': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MapFromEntries'>>, 'MATCH_AGAINST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MatchAgainst'>>, 'MAX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Max'>>, 'MIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Min'>>, 'MONTH': <function MySQL.Parser.<lambda>>, 'MONTHS_BETWEEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MonthsBetween'>>, 'NEXT_VALUE_FOR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.NextValueFor'>>, 'NUMBER_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.NumberToStr'>>, 'NVL2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Nvl2'>>, 'OPEN_J_S_O_N': <bound method Func.from_arg_list of <class 'sqlglot.expressions.OpenJSON'>>, 'PARAMETERIZED_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ParameterizedAgg'>>, 'PARSE_JSON': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ParseJSON'>>, 'JSON_PARSE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ParseJSON'>>, 'PERCENTILE_CONT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PercentileCont'>>, 'PERCENTILE_DISC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PercentileDisc'>>, 'POSEXPLODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Posexplode'>>, 'POSEXPLODE_OUTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PosexplodeOuter'>>, 'POWER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, 'POW': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, 'PREDICT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Predict'>>, 'QUANTILE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Quantile'>>, 'RANGE_N': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RangeN'>>, 'READ_CSV': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ReadCSV'>>, 'REDUCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Reduce'>>, 'REGEXP_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpExtract'>>, 'REGEXP_I_LIKE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpILike'>>, 'REGEXP_LIKE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpLike'>>, 'REGEXP_REPLACE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpReplace'>>, 'REGEXP_SPLIT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpSplit'>>, 'REPEAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Repeat'>>, 'RIGHT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Right'>>, 'ROUND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Round'>>, 'ROW_NUMBER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RowNumber'>>, 'SHA': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA'>>, 'SHA1': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA'>>, 'SHA2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA2'>>, 'SAFE_CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SafeConcat'>>, 'SAFE_DIVIDE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SafeDivide'>>, 'SET_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SetAgg'>>, 'SORT_ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SortArray'>>, 'SPLIT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Split'>>, 'SQRT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Sqrt'>>, 'STANDARD_HASH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StandardHash'>>, 'STAR_MAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StarMap'>>, 'STARTS_WITH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StartsWith'>>, 'STARTSWITH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StartsWith'>>, 'STDDEV': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Stddev'>>, 'STDDEV_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StddevPop'>>, 'STDDEV_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StddevSamp'>>, 'STR_POSITION': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrPosition'>>, 'STR_TO_DATE': <function _str_to_date>, 'STR_TO_MAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToMap'>>, 'STR_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToTime'>>, 'STR_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToUnix'>>, 'STRUCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Struct'>>, 'STRUCT_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StructExtract'>>, 'STUFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Stuff'>>, 'INSERT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Stuff'>>, 'SUBSTRING': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Substring'>>, 'SUM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Sum'>>, 'TIME_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeAdd'>>, 'TIME_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeDiff'>>, 'TIME_STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToDate'>>, 'TIME_STR_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToTime'>>, 'TIME_STR_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToUnix'>>, 'TIME_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeSub'>>, 'TIME_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeToStr'>>, 'TIME_TO_TIME_STR': <function Parser.<lambda>>, 'TIME_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeToUnix'>>, 'TIME_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeTrunc'>>, 'TIMESTAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Timestamp'>>, 'TIMESTAMP_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampAdd'>>, 'TIMESTAMP_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampDiff'>>, 'TIMESTAMP_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampSub'>>, 'TIMESTAMP_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampTrunc'>>, 'TO_BASE64': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToBase64'>>, 'TO_CHAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToChar'>>, 'TO_DAYS': <function MySQL.Parser.<lambda>>, 'TRANSFORM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Transform'>>, 'TRIM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Trim'>>, 'TRY_CAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TryCast'>>, 'TS_OR_DI_TO_DI': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDiToDi'>>, 'TS_OR_DS_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsAdd'>>, 'TS_OR_DS_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsToDate'>>, 'TS_OR_DS_TO_DATE_STR': <function Parser.<lambda>>, 'UNHEX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Unhex'>>, 'UNIX_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToStr'>>, 'UNIX_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToTime'>>, 'UNIX_TO_TIME_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToTimeStr'>>, 'UPPER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Upper'>>, 'UCASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Upper'>>, 'VAR_MAP': <function parse_var_map>, 'VARIANCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VARIANCE_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VAR_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VARIANCE_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.VariancePop'>>, 'VAR_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.VariancePop'>>, 'WEEK': <function MySQL.Parser.<lambda>>, 'WEEK_OF_YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.WeekOfYear'>>, 'WEEKOFYEAR': <function MySQL.Parser.<lambda>>, 'WHEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.When'>>, 'X_M_L_TABLE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.XMLTable'>>, 'XOR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Xor'>>, 'YEAR': <function MySQL.Parser.<lambda>>, 'GLOB': <function Parser.<lambda>>, 'LIKE': <function parse_like>, 'DATE_FORMAT': <function format_time_lambda.<locals>._format_time>, 'INSTR': <function MySQL.Parser.<lambda>>, 'ISNULL': <function isnull_to_is_null>, 'LOCATE': <function locate_to_strposition>, 'MONTHNAME': <function MySQL.Parser.<lambda>>}
FUNCTION_PARSERS = {'ANY_VALUE': <function Parser.<lambda>>, 'CAST': <function Parser.<lambda>>, 'CONCAT': <function Parser.<lambda>>, 'CONCAT_WS': <function Parser.<lambda>>, 'CONVERT': <function Parser.<lambda>>, 'DECODE': <function Parser.<lambda>>, 'EXTRACT': <function Parser.<lambda>>, 'JSON_OBJECT': <function Parser.<lambda>>, 'JSON_TABLE': <function Parser.<lambda>>, 'LOG': <function Parser.<lambda>>, 'MATCH': <function Parser.<lambda>>, 'OPENJSON': <function Parser.<lambda>>, 'POSITION': <function Parser.<lambda>>, 'PREDICT': <function Parser.<lambda>>, 'SAFE_CAST': <function Parser.<lambda>>, 'STRING_AGG': <function Parser.<lambda>>, 'SUBSTRING': <function Parser.<lambda>>, 'TRIM': <function Parser.<lambda>>, 'TRY_CAST': <function Parser.<lambda>>, 'TRY_CONVERT': <function Parser.<lambda>>, 'CHAR': <function MySQL.Parser.<lambda>>, 'GROUP_CONCAT': <function MySQL.Parser.<lambda>>, 'VALUES': <function MySQL.Parser.<lambda>>}
STATEMENT_PARSERS = {<TokenType.ALTER: 'ALTER'>: <function Parser.<lambda>>, <TokenType.BEGIN: 'BEGIN'>: <function Parser.<lambda>>, <TokenType.CACHE: 'CACHE'>: <function Parser.<lambda>>, <TokenType.COMMIT: 'COMMIT'>: <function Parser.<lambda>>, <TokenType.COMMENT: 'COMMENT'>: <function Parser.<lambda>>, <TokenType.CREATE: 'CREATE'>: <function Parser.<lambda>>, <TokenType.DELETE: 'DELETE'>: <function Parser.<lambda>>, <TokenType.DESC: 'DESC'>: <function Parser.<lambda>>, <TokenType.DESCRIBE: 'DESCRIBE'>: <function Parser.<lambda>>, <TokenType.DROP: 'DROP'>: <function Parser.<lambda>>, <TokenType.INSERT: 'INSERT'>: <function Parser.<lambda>>, <TokenType.KILL: 'KILL'>: <function Parser.<lambda>>, <TokenType.LOAD: 'LOAD'>: <function Parser.<lambda>>, <TokenType.MERGE: 'MERGE'>: <function Parser.<lambda>>, <TokenType.PIVOT: 'PIVOT'>: <function Parser.<lambda>>, <TokenType.PRAGMA: 'PRAGMA'>: <function Parser.<lambda>>, <TokenType.ROLLBACK: 'ROLLBACK'>: <function Parser.<lambda>>, <TokenType.SET: 'SET'>: <function Parser.<lambda>>, <TokenType.UNCACHE: 'UNCACHE'>: <function Parser.<lambda>>, <TokenType.UPDATE: 'UPDATE'>: <function Parser.<lambda>>, <TokenType.USE: 'USE'>: <function Parser.<lambda>>, <TokenType.SHOW: 'SHOW'>: <function MySQL.Parser.<lambda>>}
SHOW_PARSERS = {'BINARY LOGS': <function _show_parser.<locals>._parse>, 'MASTER LOGS': <function _show_parser.<locals>._parse>, 'BINLOG EVENTS': <function _show_parser.<locals>._parse>, 'CHARACTER SET': <function _show_parser.<locals>._parse>, 'CHARSET': <function _show_parser.<locals>._parse>, 'COLLATION': <function _show_parser.<locals>._parse>, 'FULL COLUMNS': <function _show_parser.<locals>._parse>, 'COLUMNS': <function _show_parser.<locals>._parse>, 'CREATE DATABASE': <function _show_parser.<locals>._parse>, 'CREATE EVENT': <function _show_parser.<locals>._parse>, 'CREATE FUNCTION': <function _show_parser.<locals>._parse>, 'CREATE PROCEDURE': <function _show_parser.<locals>._parse>, 'CREATE TABLE': <function _show_parser.<locals>._parse>, 'CREATE TRIGGER': <function _show_parser.<locals>._parse>, 'CREATE VIEW': <function _show_parser.<locals>._parse>, 'DATABASES': <function _show_parser.<locals>._parse>, 'ENGINE': <function _show_parser.<locals>._parse>, 'STORAGE ENGINES': <function _show_parser.<locals>._parse>, 'ENGINES': <function _show_parser.<locals>._parse>, 'ERRORS': <function _show_parser.<locals>._parse>, 'EVENTS': <function _show_parser.<locals>._parse>, 'FUNCTION CODE': <function _show_parser.<locals>._parse>, 'FUNCTION STATUS': <function _show_parser.<locals>._parse>, 'GRANTS': <function _show_parser.<locals>._parse>, 'INDEX': <function _show_parser.<locals>._parse>, 'MASTER STATUS': <function _show_parser.<locals>._parse>, 'OPEN TABLES': <function _show_parser.<locals>._parse>, 'PLUGINS': <function _show_parser.<locals>._parse>, 'PROCEDURE CODE': <function _show_parser.<locals>._parse>, 'PROCEDURE STATUS': <function _show_parser.<locals>._parse>, 'PRIVILEGES': <function _show_parser.<locals>._parse>, 'FULL PROCESSLIST': <function _show_parser.<locals>._parse>, 'PROCESSLIST': <function _show_parser.<locals>._parse>, 'PROFILE': <function _show_parser.<locals>._parse>, 'PROFILES': <function _show_parser.<locals>._parse>, 'RELAYLOG EVENTS': <function _show_parser.<locals>._parse>, 'REPLICAS': <function _show_parser.<locals>._parse>, 'SLAVE HOSTS': <function _show_parser.<locals>._parse>, 'REPLICA STATUS': <function _show_parser.<locals>._parse>, 'SLAVE STATUS': <function _show_parser.<locals>._parse>, 'GLOBAL STATUS': <function _show_parser.<locals>._parse>, 'SESSION STATUS': <function _show_parser.<locals>._parse>, 'STATUS': <function _show_parser.<locals>._parse>, 'TABLE STATUS': <function _show_parser.<locals>._parse>, 'FULL TABLES': <function _show_parser.<locals>._parse>, 'TABLES': <function _show_parser.<locals>._parse>, 'TRIGGERS': <function _show_parser.<locals>._parse>, 'GLOBAL VARIABLES': <function _show_parser.<locals>._parse>, 'SESSION VARIABLES': <function _show_parser.<locals>._parse>, 'VARIABLES': <function _show_parser.<locals>._parse>, 'WARNINGS': <function _show_parser.<locals>._parse>}
SET_PARSERS = {'GLOBAL': <function Parser.<lambda>>, 'LOCAL': <function Parser.<lambda>>, 'SESSION': <function Parser.<lambda>>, 'TRANSACTION': <function Parser.<lambda>>, 'PERSIST': <function MySQL.Parser.<lambda>>, 'PERSIST_ONLY': <function MySQL.Parser.<lambda>>, 'CHARACTER SET': <function MySQL.Parser.<lambda>>, 'CHARSET': <function MySQL.Parser.<lambda>>, 'NAMES': <function MySQL.Parser.<lambda>>}
CONSTRAINT_PARSERS = {'AUTOINCREMENT': <function Parser.<lambda>>, 'AUTO_INCREMENT': <function Parser.<lambda>>, 'CASESPECIFIC': <function Parser.<lambda>>, 'CHARACTER SET': <function Parser.<lambda>>, 'CHECK': <function Parser.<lambda>>, 'COLLATE': <function Parser.<lambda>>, 'COMMENT': <function Parser.<lambda>>, 'COMPRESS': <function Parser.<lambda>>, 'CLUSTERED': <function Parser.<lambda>>, 'NONCLUSTERED': <function Parser.<lambda>>, 'DEFAULT': <function Parser.<lambda>>, 'ENCODE': <function Parser.<lambda>>, 'FOREIGN KEY': <function Parser.<lambda>>, 'FORMAT': <function Parser.<lambda>>, 'GENERATED': <function Parser.<lambda>>, 'IDENTITY': <function Parser.<lambda>>, 'INLINE': <function Parser.<lambda>>, 'LIKE': <function Parser.<lambda>>, 'NOT': <function Parser.<lambda>>, 'NULL': <function Parser.<lambda>>, 'ON': <function Parser.<lambda>>, 'PATH': <function Parser.<lambda>>, 'PRIMARY KEY': <function Parser.<lambda>>, 'REFERENCES': <function Parser.<lambda>>, 'TITLE': <function Parser.<lambda>>, 'TTL': <function Parser.<lambda>>, 'UNIQUE': <function Parser.<lambda>>, 'UPPERCASE': <function Parser.<lambda>>, 'WITH': <function Parser.<lambda>>, 'FULLTEXT': <function MySQL.Parser.<lambda>>, 'INDEX': <function MySQL.Parser.<lambda>>, 'KEY': <function MySQL.Parser.<lambda>>, 'SPATIAL': <function MySQL.Parser.<lambda>>}
SCHEMA_UNNAMED_CONSTRAINTS = {'LIKE', 'KEY', 'INDEX', 'UNIQUE', 'SPATIAL', 'PRIMARY KEY', 'CHECK', 'FULLTEXT', 'FOREIGN KEY'}
PROFILE_TYPES = {'CPU', 'SOURCE', 'IPC', 'MEMORY', 'CONTEXT SWITCHES', 'PAGE FAULTS', 'ALL', 'SWAPS', 'BLOCK IO'}
TYPE_TOKENS = {<TokenType.TEXT: 'TEXT'>, <TokenType.GEOMETRY: 'GEOMETRY'>, <TokenType.TINYINT: 'TINYINT'>, <TokenType.DATERANGE: 'DATERANGE'>, <TokenType.UUID: 'UUID'>, <TokenType.XML: 'XML'>, <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, <TokenType.UNKNOWN: 'UNKNOWN'>, <TokenType.YEAR: 'YEAR'>, <TokenType.SUPER: 'SUPER'>, <TokenType.USERDEFINED: 'USERDEFINED'>, <TokenType.INTERVAL: 'INTERVAL'>, <TokenType.TIMESTAMP_S: 'TIMESTAMP_S'>, <TokenType.BOOLEAN: 'BOOLEAN'>, <TokenType.HLLSKETCH: 'HLLSKETCH'>, <TokenType.DATE: 'DATE'>, <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <TokenType.STRUCT: 'STRUCT'>, <TokenType.UINT256: 'UINT256'>, <TokenType.ENUM16: 'ENUM16'>, <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, <TokenType.LONGBLOB: 'LONGBLOB'>, <TokenType.INET: 'INET'>, <TokenType.INT128: 'INT128'>, <TokenType.BIT: 'BIT'>, <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, <TokenType.USMALLINT: 'USMALLINT'>, <TokenType.UINT128: 'UINT128'>, <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, <TokenType.BIGINT: 'BIGINT'>, <TokenType.OBJECT: 'OBJECT'>, <TokenType.ENUM8: 'ENUM8'>, <TokenType.UMEDIUMINT: 'UMEDIUMINT'>, <TokenType.INT8RANGE: 'INT8RANGE'>, <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <TokenType.JSONB: 'JSONB'>, <TokenType.OBJECT_IDENTIFIER: 'OBJECT_IDENTIFIER'>, <TokenType.NCHAR: 'NCHAR'>, <TokenType.SERIAL: 'SERIAL'>, <TokenType.INT4RANGE: 'INT4RANGE'>, <TokenType.MEDIUMINT: 'MEDIUMINT'>, <TokenType.DOUBLE: 'DOUBLE'>, <TokenType.MAP: 'MAP'>, <TokenType.TINYTEXT: 'TINYTEXT'>, <TokenType.NULL: 'NULL'>, <TokenType.BINARY: 'BINARY'>, <TokenType.SET: 'SET'>, <TokenType.VARIANT: 'VARIANT'>, <TokenType.CHAR: 'CHAR'>, <TokenType.IPADDRESS: 'IPADDRESS'>, <TokenType.TSRANGE: 'TSRANGE'>, <TokenType.TIMETZ: 'TIMETZ'>, <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, <TokenType.TIME: 'TIME'>, <TokenType.ARRAY: 'ARRAY'>, <TokenType.BIGSERIAL: 'BIGSERIAL'>, <TokenType.TINYBLOB: 'TINYBLOB'>, <TokenType.MONEY: 'MONEY'>, <TokenType.SMALLMONEY: 'SMALLMONEY'>, <TokenType.LONGTEXT: 'LONGTEXT'>, <TokenType.UINT: 'UINT'>, <TokenType.NULLABLE: 'NULLABLE'>, <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, <TokenType.UTINYINT: 'UTINYINT'>, <TokenType.INT: 'INT'>, <TokenType.IMAGE: 'IMAGE'>, <TokenType.TIMESTAMP: 'TIMESTAMP'>, <TokenType.DATETIME: 'DATETIME'>, <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>, <TokenType.VARBINARY: 'VARBINARY'>, <TokenType.FIXEDSTRING: 'FIXEDSTRING'>, <TokenType.UBIGINT: 'UBIGINT'>, <TokenType.ENUM: 'ENUM'>, <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, <TokenType.FLOAT: 'FLOAT'>, <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, <TokenType.TSTZRANGE: 'TSTZRANGE'>, <TokenType.VARCHAR: 'VARCHAR'>, <TokenType.SMALLINT: 'SMALLINT'>, <TokenType.NESTED: 'NESTED'>, <TokenType.NVARCHAR: 'NVARCHAR'>, <TokenType.INT256: 'INT256'>, <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, <TokenType.SMALLSERIAL: 'SMALLSERIAL'>, <TokenType.DATETIME64: 'DATETIME64'>, <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>, <TokenType.HSTORE: 'HSTORE'>, <TokenType.IPPREFIX: 'IPPREFIX'>, <TokenType.JSON: 'JSON'>, <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, <TokenType.DECIMAL: 'DECIMAL'>, <TokenType.ROWVERSION: 'ROWVERSION'>, <TokenType.TIMESTAMP_MS: 'TIMESTAMP_MS'>, <TokenType.UDECIMAL: 'UDECIMAL'>, <TokenType.NUMRANGE: 'NUMRANGE'>, <TokenType.TIMESTAMP_NS: 'TIMESTAMP_NS'>}
ENUM_TYPE_TOKENS = {<TokenType.ENUM16: 'ENUM16'>, <TokenType.ENUM: 'ENUM'>, <TokenType.SET: 'SET'>, <TokenType.ENUM8: 'ENUM8'>}
LOG_DEFAULTS_TO_LN = True
TOKENIZER_CLASS: Type[sqlglot.tokens.Tokenizer] = <class 'MySQL.Tokenizer'>
SUPPORTS_USER_DEFINED_TYPES = False
SHOW_TRIE: Dict = {'BINARY': {'LOGS': {0: True}}, 'MASTER': {'LOGS': {0: True}, 'STATUS': {0: True}}, 'BINLOG': {'EVENTS': {0: True}}, 'CHARACTER': {'SET': {0: True}}, 'CHARSET': {0: True}, 'COLLATION': {0: True}, 'FULL': {'COLUMNS': {0: True}, 'PROCESSLIST': {0: True}, 'TABLES': {0: True}}, 'COLUMNS': {0: True}, 'CREATE': {'DATABASE': {0: True}, 'EVENT': {0: True}, 'FUNCTION': {0: True}, 'PROCEDURE': {0: True}, 'TABLE': {0: True}, 'TRIGGER': {0: True}, 'VIEW': {0: True}}, 'DATABASES': {0: True}, 'ENGINE': {0: True}, 'STORAGE': {'ENGINES': {0: True}}, 'ENGINES': {0: True}, 'ERRORS': {0: True}, 'EVENTS': {0: True}, 'FUNCTION': {'CODE': {0: True}, 'STATUS': {0: True}}, 'GRANTS': {0: True}, 'INDEX': {0: True}, 'OPEN': {'TABLES': {0: True}}, 'PLUGINS': {0: True}, 'PROCEDURE': {'CODE': {0: True}, 'STATUS': {0: True}}, 'PRIVILEGES': {0: True}, 'PROCESSLIST': {0: True}, 'PROFILE': {0: True}, 'PROFILES': {0: True}, 'RELAYLOG': {'EVENTS': {0: True}}, 'REPLICAS': {0: True}, 'SLAVE': {'HOSTS': {0: True}, 'STATUS': {0: True}}, 'REPLICA': {'STATUS': {0: True}}, 'GLOBAL': {'STATUS': {0: True}, 'VARIABLES': {0: True}}, 'SESSION': {'STATUS': {0: True}, 'VARIABLES': {0: True}}, 'STATUS': {0: True}, 'TABLE': {'STATUS': {0: True}}, 'TABLES': {0: True}, 'TRIGGERS': {0: True}, 'VARIABLES': {0: True}, 'WARNINGS': {0: True}}
SET_TRIE: Dict = {'GLOBAL': {0: True}, 'LOCAL': {0: True}, 'SESSION': {0: True}, 'TRANSACTION': {0: True}, 'PERSIST': {0: True}, 'PERSIST_ONLY': {0: True}, 'CHARACTER': {'SET': {0: True}}, 'CHARSET': {0: True}, 'NAMES': {0: True}}
FORMAT_TRIE: Dict = {'%': {'M': {0: True}, 'c': {0: True}, 'e': {0: True}, 'h': {0: True}, 'i': {0: True}, 's': {0: True}, 'u': {0: True}, 'k': {0: True}, 'l': {0: True}, 'T': {0: True}, 'W': {0: True}}}
TIME_MAPPING: Dict[str, str] = {'%M': '%B', '%c': '%-m', '%e': '%-d', '%h': '%I', '%i': '%M', '%s': '%S', '%u': '%W', '%k': '%-H', '%l': '%-I', '%T': '%H:%M:%S', '%W': '%a'}
TIME_TRIE: Dict = {'%': {'M': {0: True}, 'c': {0: True}, 'e': {0: True}, 'h': {0: True}, 'i': {0: True}, 's': {0: True}, 'u': {0: True}, 'k': {0: True}, 'l': {0: True}, 'T': {0: True}, 'W': {0: True}}}

##### Inherited Members

sqlglot.parser.Parser
  Parser
  NO_PAREN_FUNCTIONS
  STRUCT_TYPE_TOKENS
  NESTED_TYPE_TOKENS
  SIGNED_TO_UNSIGNED_TYPE_TOKEN
  SUBQUERY_PREDICATES
  RESERVED_KEYWORDS
  DB_CREATABLES
  CREATABLES
  ID_VAR_TOKENS
  INTERVAL_VARS
  COMMENT_TABLE_ALIAS_TOKENS
  UPDATE_ALIAS_TOKENS
  TRIM_TYPES
  EQUALITY
  COMPARISON
  TERM
  FACTOR
  TIMES
  TIMESTAMPS
  SET_OPERATIONS
  JOIN_METHODS
  JOIN_SIDES
  JOIN_KINDS
  JOIN_HINTS
  LAMBDAS
  COLUMN_OPERATORS
  EXPRESSION_PARSERS
  UNARY_PARSERS
  PRIMARY_PARSERS
  PLACEHOLDER_PARSERS
  PROPERTY_PARSERS
  ALTER_PARSERS
  NO_PAREN_FUNCTION_PARSERS
  INVALID_FUNC_NAME_TOKENS
  FUNCTIONS_WITH_ALIASED_ARGS
  QUERY_MODIFIER_PARSERS
  TYPE_LITERAL_PARSERS
  MODIFIABLES
  DDL_SELECT_TOKENS
  PRE_VOLATILE_TOKENS
  TRANSACTION_KIND
  TRANSACTION_CHARACTERISTICS
  INSERT_ALTERNATIVES
  CLONE_KEYWORDS
  CLONE_KINDS
  OPCLASS_FOLLOW_KEYWORDS
  TABLE_INDEX_HINT_TOKENS
  WINDOW_ALIAS_TOKENS
  WINDOW_BEFORE_PAREN_TOKENS
  WINDOW_SIDES
  FETCH_TOKENS
  ADD_CONSTRAINT_TOKENS
  DISTINCT_TOKENS
  NULL_TOKENS
  UNNEST_OFFSET_ALIAS_TOKENS
  STRICT_CAST
  CONCAT_NULL_OUTPUTS_STRING
  PREFIXED_PIVOT_COLUMNS
  IDENTIFY_PIVOT_STRINGS
  LOG_BASE_FIRST
  ALTER_TABLE_ADD_COLUMN_KEYWORD
  TABLESAMPLE_CSV
  SET_REQUIRES_ASSIGNMENT_DELIMITER
  TRIM_PATTERN_FIRST
  INDEX_OFFSET
  UNNEST_COLUMN_ONLY
  ALIAS_POST_TABLESAMPLE
  STRICT_STRING_CONCAT
  NORMALIZE_FUNCTIONS
  NULL_ORDERING
  FORMAT_MAPPING
  error_level
  error_message_context
  max_errors
  reset
  parse
  parse_into
  check_errors
  raise_error
  expression
  validate_expression
  errors
  sql

class MySQL.Generator(sqlglot.generator.Generator): View Source

    618    class Generator(generator.Generator):
    619        LOCKING_READS_SUPPORTED = True
    620        NULL_ORDERING_SUPPORTED = False
    621        JOIN_HINTS = False
    622        TABLE_HINTS = True
    623        DUPLICATE_KEY_UPDATE_WITH_SET = False
    624        QUERY_HINT_SEP = " "
    625        VALUES_AS_TABLE = False
    626        NVL2_SUPPORTED = False
    627
    628        TRANSFORMS = {
    629            **generator.Generator.TRANSFORMS,
    630            exp.CurrentDate: no_paren_current_date_sql,
    631            exp.DateDiff: _remove_ts_or_ds_to_date(
    632                lambda self, e: self.func("DATEDIFF", e.this, e.expression), ("this", "expression")
    633            ),
    634            exp.DateAdd: _remove_ts_or_ds_to_date(_date_add_sql("ADD")),
    635            exp.DateStrToDate: datestrtodate_sql,
    636            exp.DateSub: _remove_ts_or_ds_to_date(_date_add_sql("SUB")),
    637            exp.DateTrunc: _date_trunc_sql,
    638            exp.Day: _remove_ts_or_ds_to_date(),
    639            exp.DayOfMonth: _remove_ts_or_ds_to_date(rename_func("DAYOFMONTH")),
    640            exp.DayOfWeek: _remove_ts_or_ds_to_date(rename_func("DAYOFWEEK")),
    641            exp.DayOfYear: _remove_ts_or_ds_to_date(rename_func("DAYOFYEAR")),
    642            exp.GroupConcat: lambda self, e: f"""GROUP_CONCAT({self.sql(e, "this")} SEPARATOR {self.sql(e, "separator") or "','"})""",
    643            exp.ILike: no_ilike_sql,
    644            exp.JSONExtractScalar: arrow_json_extract_scalar_sql,
    645            exp.JSONKeyValue: json_keyvalue_comma_sql,
    646            exp.Max: max_or_greatest,
    647            exp.Min: min_or_least,
    648            exp.Month: _remove_ts_or_ds_to_date(),
    649            exp.NullSafeEQ: lambda self, e: self.binary(e, "<=>"),
    650            exp.NullSafeNEQ: lambda self, e: self.not_sql(self.binary(e, "<=>")),
    651            exp.Pivot: no_pivot_sql,
    652            exp.Select: transforms.preprocess(
    653                [
    654                    transforms.eliminate_distinct_on,
    655                    transforms.eliminate_semi_and_anti_joins,
    656                    transforms.eliminate_qualify,
    657                    transforms.eliminate_full_outer_join,
    658                ]
    659            ),
    660            exp.StrPosition: strposition_to_locate_sql,
    661            exp.StrToDate: _str_to_date_sql,
    662            exp.StrToTime: _str_to_date_sql,
    663            exp.Stuff: rename_func("INSERT"),
    664            exp.TableSample: no_tablesample_sql,
    665            exp.TimestampAdd: date_add_interval_sql("DATE", "ADD"),
    666            exp.TimestampSub: date_add_interval_sql("DATE", "SUB"),
    667            exp.TimeStrToUnix: rename_func("UNIX_TIMESTAMP"),
    668            exp.TimeStrToTime: lambda self, e: self.sql(exp.cast(e.this, "datetime", copy=True)),
    669            exp.TimeToStr: _remove_ts_or_ds_to_date(
    670                lambda self, e: self.func("DATE_FORMAT", e.this, self.format_time(e))
    671            ),
    672            exp.Trim: _trim_sql,
    673            exp.TryCast: no_trycast_sql,
    674            exp.TsOrDsAdd: _date_add_sql("ADD"),
    675            exp.TsOrDsToDate: _ts_or_ds_to_date_sql,
    676            exp.Week: _remove_ts_or_ds_to_date(),
    677            exp.WeekOfYear: _remove_ts_or_ds_to_date(rename_func("WEEKOFYEAR")),
    678            exp.Year: _remove_ts_or_ds_to_date(),
    679        }
    680
    681        UNSIGNED_TYPE_MAPPING = {
    682            exp.DataType.Type.UBIGINT: "BIGINT",
    683            exp.DataType.Type.UINT: "INT",
    684            exp.DataType.Type.UMEDIUMINT: "MEDIUMINT",
    685            exp.DataType.Type.USMALLINT: "SMALLINT",
    686            exp.DataType.Type.UTINYINT: "TINYINT",
    687            exp.DataType.Type.UDECIMAL: "DECIMAL",
    688        }
    689
    690        TIMESTAMP_TYPE_MAPPING = {
    691            exp.DataType.Type.TIMESTAMP: "DATETIME",
    692            exp.DataType.Type.TIMESTAMPTZ: "TIMESTAMP",
    693            exp.DataType.Type.TIMESTAMPLTZ: "TIMESTAMP",
    694        }
    695
    696        TYPE_MAPPING = {
    697            **generator.Generator.TYPE_MAPPING,
    698            **UNSIGNED_TYPE_MAPPING,
    699            **TIMESTAMP_TYPE_MAPPING,
    700        }
    701
    702        TYPE_MAPPING.pop(exp.DataType.Type.MEDIUMTEXT)
    703        TYPE_MAPPING.pop(exp.DataType.Type.LONGTEXT)
    704        TYPE_MAPPING.pop(exp.DataType.Type.TINYTEXT)
    705        TYPE_MAPPING.pop(exp.DataType.Type.MEDIUMBLOB)
    706        TYPE_MAPPING.pop(exp.DataType.Type.LONGBLOB)
    707        TYPE_MAPPING.pop(exp.DataType.Type.TINYBLOB)
    708
    709        PROPERTIES_LOCATION = {
    710            **generator.Generator.PROPERTIES_LOCATION,
    711            exp.TransientProperty: exp.Properties.Location.UNSUPPORTED,
    712            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    713        }
    714
    715        LIMIT_FETCH = "LIMIT"
    716
    717        LIMIT_ONLY_LITERALS = True
    718
    719        # MySQL doesn't support many datatypes in cast.
    720        # https://dev.mysql.com/doc/refman/8.0/en/cast-functions.html#function_cast
    721        CAST_MAPPING = {
    722            exp.DataType.Type.BIGINT: "SIGNED",
    723            exp.DataType.Type.BOOLEAN: "SIGNED",
    724            exp.DataType.Type.INT: "SIGNED",
    725            exp.DataType.Type.TEXT: "CHAR",
    726            exp.DataType.Type.UBIGINT: "UNSIGNED",
    727            exp.DataType.Type.VARCHAR: "CHAR",
    728        }
    729
    730        TIMESTAMP_FUNC_TYPES = {
    731            exp.DataType.Type.TIMESTAMPTZ,
    732            exp.DataType.Type.TIMESTAMPLTZ,
    733        }
    734
    735        def datatype_sql(self, expression: exp.DataType) -> str:
    736            # https://dev.mysql.com/doc/refman/8.0/en/numeric-type-syntax.html
    737            result = super().datatype_sql(expression)
    738            if expression.this in self.UNSIGNED_TYPE_MAPPING:
    739                result = f"{result} UNSIGNED"
    740            return result
    741
    742        def xor_sql(self, expression: exp.Xor) -> str:
    743            if expression.expressions:
    744                return self.expressions(expression, sep=" XOR ")
    745            return super().xor_sql(expression)
    746
    747        def jsonarraycontains_sql(self, expression: exp.JSONArrayContains) -> str:
    748            return f"{self.sql(expression, 'this')} MEMBER OF({self.sql(expression, 'expression')})"
    749
    750        def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    751            if expression.to.this in self.TIMESTAMP_FUNC_TYPES:
    752                return self.func("TIMESTAMP", expression.this)
    753
    754            to = self.CAST_MAPPING.get(expression.to.this)
    755
    756            if to:
    757                expression.to.set("this", to)
    758            return super().cast_sql(expression)
    759
    760        def show_sql(self, expression: exp.Show) -> str:
    761            this = f" {expression.name}"
    762            full = " FULL" if expression.args.get("full") else ""
    763            global_ = " GLOBAL" if expression.args.get("global") else ""
    764
    765            target = self.sql(expression, "target")
    766            target = f" {target}" if target else ""
    767            if expression.name in {"COLUMNS", "INDEX"}:
    768                target = f" FROM{target}"
    769            elif expression.name == "GRANTS":
    770                target = f" FOR{target}"
    771
    772            db = self._prefixed_sql("FROM", expression, "db")
    773
    774            like = self._prefixed_sql("LIKE", expression, "like")
    775            where = self.sql(expression, "where")
    776
    777            types = self.expressions(expression, key="types")
    778            types = f" {types}" if types else types
    779            query = self._prefixed_sql("FOR QUERY", expression, "query")
    780
    781            if expression.name == "PROFILE":
    782                offset = self._prefixed_sql("OFFSET", expression, "offset")
    783                limit = self._prefixed_sql("LIMIT", expression, "limit")
    784            else:
    785                offset = ""
    786                limit = self._oldstyle_limit_sql(expression)
    787
    788            log = self._prefixed_sql("IN", expression, "log")
    789            position = self._prefixed_sql("FROM", expression, "position")
    790
    791            channel = self._prefixed_sql("FOR CHANNEL", expression, "channel")
    792
    793            if expression.name == "ENGINE":
    794                mutex_or_status = " MUTEX" if expression.args.get("mutex") else " STATUS"
    795            else:
    796                mutex_or_status = ""
    797
    798            return f"SHOW{full}{global_}{this}{target}{types}{db}{query}{log}{position}{channel}{mutex_or_status}{like}{where}{offset}{limit}"
    799
    800        def _prefixed_sql(self, prefix: str, expression: exp.Expression, arg: str) -> str:
    801            sql = self.sql(expression, arg)
    802            return f" {prefix} {sql}" if sql else ""
    803
    804        def _oldstyle_limit_sql(self, expression: exp.Show) -> str:
    805            limit = self.sql(expression, "limit")
    806            offset = self.sql(expression, "offset")
    807            if limit:
    808                limit_offset = f"{offset}, {limit}" if offset else limit
    809                return f" LIMIT {limit_offset}"
    810            return ""
    811
    812        def chr_sql(self, expression: exp.Chr) -> str:
    813            this = self.expressions(sqls=[expression.this] + expression.expressions)
    814            charset = expression.args.get("charset")
    815            using = f" USING {self.sql(charset)}" if charset else ""
    816            return f"CHAR({this}{using})"

Generator converts a given syntax tree to the corresponding SQL string.

###### Arguments:

- pretty: Whether or not 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 or 'always': Always quote. 'safe': Only quote identifiers that are case insensitive.
- normalize: Whether or not to normalize identifiers to lowercase. Default: False.
- pad: Determines the pad size in a formatted string. Default: 2.
- indent: Determines the indentation size in a formatted string. Default: 2.
- normalize_functions: Whether or not to normalize all 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: Determines whether or not 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 or not to preserve comments in the output SQL code. Default: True

LOCKING_READS_SUPPORTED = True
NULL_ORDERING_SUPPORTED = False
JOIN_HINTS = False
TABLE_HINTS = True
DUPLICATE_KEY_UPDATE_WITH_SET = False
QUERY_HINT_SEP = ' '
VALUES_AS_TABLE = False
NVL2_SUPPORTED = False
TRANSFORMS = {<class 'sqlglot.expressions.DateAdd'>: <function _remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.TsOrDsAdd'>: <function _date_add_sql.<locals>.func>, <class 'sqlglot.expressions.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CheckColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CurrentDate'>: <function no_paren_current_date_sql>, <class 'sqlglot.expressions.DateDiff'>: <function _remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.DateStrToDate'>: <function datestrtodate_sql>, <class 'sqlglot.expressions.DateSub'>: <function _remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.DateTrunc'>: <function _date_trunc_sql>, <class 'sqlglot.expressions.Day'>: <function _remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.DayOfMonth'>: <function _remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.DayOfWeek'>: <function _remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.DayOfYear'>: <function _remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.GroupConcat'>: <function MySQL.Generator.<lambda>>, <class 'sqlglot.expressions.ILike'>: <function no_ilike_sql>, <class 'sqlglot.expressions.JSONExtractScalar'>: <function arrow_json_extract_scalar_sql>, <class 'sqlglot.expressions.JSONKeyValue'>: <function json_keyvalue_comma_sql>, <class 'sqlglot.expressions.Max'>: <function max_or_greatest>, <class 'sqlglot.expressions.Min'>: <function min_or_least>, <class 'sqlglot.expressions.Month'>: <function _remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.NullSafeEQ'>: <function MySQL.Generator.<lambda>>, <class 'sqlglot.expressions.NullSafeNEQ'>: <function MySQL.Generator.<lambda>>, <class 'sqlglot.expressions.Pivot'>: <function no_pivot_sql>, <class 'sqlglot.expressions.Select'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.StrPosition'>: <function strposition_to_locate_sql>, <class 'sqlglot.expressions.StrToDate'>: <function _str_to_date_sql>, <class 'sqlglot.expressions.StrToTime'>: <function _str_to_date_sql>, <class 'sqlglot.expressions.Stuff'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.TableSample'>: <function no_tablesample_sql>, <class 'sqlglot.expressions.TimestampAdd'>: <function date_add_interval_sql.<locals>.func>, <class 'sqlglot.expressions.TimestampSub'>: <function date_add_interval_sql.<locals>.func>, <class 'sqlglot.expressions.TimeStrToUnix'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.TimeStrToTime'>: <function MySQL.Generator.<lambda>>, <class 'sqlglot.expressions.TimeToStr'>: <function _remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.Trim'>: <function _trim_sql>, <class 'sqlglot.expressions.TryCast'>: <function no_trycast_sql>, <class 'sqlglot.expressions.TsOrDsToDate'>: <function _ts_or_ds_to_date_sql>, <class 'sqlglot.expressions.Week'>: <function _remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.WeekOfYear'>: <function _remove_ts_or_ds_to_date.<locals>.func>, <class 'sqlglot.expressions.Year'>: <function _remove_ts_or_ds_to_date.<locals>.func>}
UNSIGNED_TYPE_MAPPING = {<Type.UBIGINT: 'UBIGINT'>: 'BIGINT', <Type.UINT: 'UINT'>: 'INT', <Type.UMEDIUMINT: 'UMEDIUMINT'>: 'MEDIUMINT', <Type.USMALLINT: 'USMALLINT'>: 'SMALLINT', <Type.UTINYINT: 'UTINYINT'>: 'TINYINT', <Type.UDECIMAL: 'UDECIMAL'>: 'DECIMAL'}
TIMESTAMP_TYPE_MAPPING = {<Type.TIMESTAMP: 'TIMESTAMP'>: 'DATETIME', <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>: 'TIMESTAMP', <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>: 'TIMESTAMP'}
TYPE_MAPPING = {<Type.NCHAR: 'NCHAR'>: 'CHAR', <Type.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <Type.INET: 'INET'>: 'INET', <Type.UBIGINT: 'UBIGINT'>: 'BIGINT', <Type.UINT: 'UINT'>: 'INT', <Type.UMEDIUMINT: 'UMEDIUMINT'>: 'MEDIUMINT', <Type.USMALLINT: 'USMALLINT'>: 'SMALLINT', <Type.UTINYINT: 'UTINYINT'>: 'TINYINT', <Type.UDECIMAL: 'UDECIMAL'>: 'DECIMAL', <Type.TIMESTAMP: 'TIMESTAMP'>: 'DATETIME', <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>: 'TIMESTAMP', <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>: 'TIMESTAMP'}
PROPERTIES_LOCATION = {<class 'sqlglot.expressions.AlgorithmProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.AutoIncrementProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BlockCompressionProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CharacterSetProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ChecksumProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CollateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Cluster'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ClusteredByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DataBlocksizeProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.DefinerProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DictRange'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistStyleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EngineProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExternalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.FallbackProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.FileFormatProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.FreespaceProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.HeapProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.InputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IsolatedLoadingProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.JournalProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.LanguageProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LikeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LocationProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockingProperty'>: <Location.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.LogProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.MaterializedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeBlockRatioProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.OnProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OnCommitProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.Order'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OutputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PartitionedByProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.PartitionedOfProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ReturnsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatDelimitedProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatSerdeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SampleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SchemaCommentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SerdeProperties'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Set'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SettingsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SetProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SortKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StabilityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TemporaryProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ToTableProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TransientProperty'>: <Location.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.TransformModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.MergeTreeTTL'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>}
LIMIT_FETCH = 'LIMIT'
LIMIT_ONLY_LITERALS = True
CAST_MAPPING = {<Type.BIGINT: 'BIGINT'>: 'SIGNED', <Type.BOOLEAN: 'BOOLEAN'>: 'SIGNED', <Type.INT: 'INT'>: 'SIGNED', <Type.TEXT: 'TEXT'>: 'CHAR', <Type.UBIGINT: 'UBIGINT'>: 'UNSIGNED', <Type.VARCHAR: 'VARCHAR'>: 'CHAR'}
TIMESTAMP_FUNC_TYPES = {<Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>}
def datatype_sql(self, expression: sqlglot.expressions.DataType) -> str: View Source

    735        def datatype_sql(self, expression: exp.DataType) -> str:
    736            # https://dev.mysql.com/doc/refman/8.0/en/numeric-type-syntax.html
    737            result = super().datatype_sql(expression)
    738            if expression.this in self.UNSIGNED_TYPE_MAPPING:
    739                result = f"{result} UNSIGNED"
    740            return result

def xor_sql(self, expression: sqlglot.expressions.Xor) -> str: View Source

    742        def xor_sql(self, expression: exp.Xor) -> str:
    743            if expression.expressions:
    744                return self.expressions(expression, sep=" XOR ")
    745            return super().xor_sql(expression)

def jsonarraycontains_sql(self, expression: sqlglot.expressions.JSONArrayContains) -> str: View Source

    747        def jsonarraycontains_sql(self, expression: exp.JSONArrayContains) -> str:
    748            return f"{self.sql(expression, 'this')} MEMBER OF({self.sql(expression, 'expression')})"

def cast_sql( self, expression: sqlglot.expressions.Cast, safe_prefix: Optional[str] = None) -> str: View Source

    750        def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    751            if expression.to.this in self.TIMESTAMP_FUNC_TYPES:
    752                return self.func("TIMESTAMP", expression.this)
    753
    754            to = self.CAST_MAPPING.get(expression.to.this)
    755
    756            if to:
    757                expression.to.set("this", to)
    758            return super().cast_sql(expression)

def show_sql(self, expression: sqlglot.expressions.Show) -> str: View Source

    760        def show_sql(self, expression: exp.Show) -> str:
    761            this = f" {expression.name}"
    762            full = " FULL" if expression.args.get("full") else ""
    763            global_ = " GLOBAL" if expression.args.get("global") else ""
    764
    765            target = self.sql(expression, "target")
    766            target = f" {target}" if target else ""
    767            if expression.name in {"COLUMNS", "INDEX"}:
    768                target = f" FROM{target}"
    769            elif expression.name == "GRANTS":
    770                target = f" FOR{target}"
    771
    772            db = self._prefixed_sql("FROM", expression, "db")
    773
    774            like = self._prefixed_sql("LIKE", expression, "like")
    775            where = self.sql(expression, "where")
    776
    777            types = self.expressions(expression, key="types")
    778            types = f" {types}" if types else types
    779            query = self._prefixed_sql("FOR QUERY", expression, "query")
    780
    781            if expression.name == "PROFILE":
    782                offset = self._prefixed_sql("OFFSET", expression, "offset")
    783                limit = self._prefixed_sql("LIMIT", expression, "limit")
    784            else:
    785                offset = ""
    786                limit = self._oldstyle_limit_sql(expression)
    787
    788            log = self._prefixed_sql("IN", expression, "log")
    789            position = self._prefixed_sql("FROM", expression, "position")
    790
    791            channel = self._prefixed_sql("FOR CHANNEL", expression, "channel")
    792
    793            if expression.name == "ENGINE":
    794                mutex_or_status = " MUTEX" if expression.args.get("mutex") else " STATUS"
    795            else:
    796                mutex_or_status = ""
    797
    798            return f"SHOW{full}{global_}{this}{target}{types}{db}{query}{log}{position}{channel}{mutex_or_status}{like}{where}{offset}{limit}"

def chr_sql(self, expression: sqlglot.expressions.Chr) -> str: View Source

    812        def chr_sql(self, expression: exp.Chr) -> str:
    813            this = self.expressions(sqls=[expression.this] + expression.expressions)
    814            charset = expression.args.get("charset")
    815            using = f" USING {self.sql(charset)}" if charset else ""
    816            return f"CHAR({this}{using})"

SELECT_KINDS: Tuple[str, ...] = ()
INVERSE_TIME_MAPPING: Dict[str, str] = {'%B': '%M', '%-m': '%c', '%-d': '%e', '%I': '%h', '%M': '%i', '%S': '%s', '%W': '%u', '%-H': '%k', '%-I': '%l', '%H:%M:%S': '%T', '%a': '%W'}
INVERSE_TIME_TRIE: Dict = {'%': {'B': {0: True}, '-': {'m': {0: True}, 'd': {0: True}, 'H': {0: True}, 'I': {0: True}}, 'I': {0: True}, 'M': {0: True}, 'S': {0: True}, 'W': {0: True}, 'H': {':': {'%': {'M': {':': {'%': {'S': {0: True}}}}}}}, 'a': {0: True}}}
INVERSE_ESCAPE_SEQUENCES: Dict[str, str] = {}
IDENTIFIERS_CAN_START_WITH_DIGIT = True
@classmethod
def can_identify(text: str, identify: str | bool = 'safe') -> bool: View Source

    279    @classmethod
    280    def can_identify(cls, text: str, identify: str | bool = "safe") -> bool:
    281        """Checks if text can be identified given an identify option.
    282
    283        Args:
    284            text: The text to check.
    285            identify:
    286                "always" or `True`: Always returns true.
    287                "safe": True if the identifier is case-insensitive.
    288
    289        Returns:
    290            Whether or not the given text can be identified.
    291        """
    292        if identify is True or identify == "always":
    293            return True
    294
    295        if identify == "safe":
    296            return not cls.case_sensitive(text)
    297
    298        return False

Checks if text can be identified given an identify option.

###### Arguments:

- text: The text to check.
- identify: "always" or `True`: Always returns true. "safe": True if the identifier is case-insensitive.

###### Returns:

> Whether or not the given text can be identified.

QUOTE_START = "'"
QUOTE_END = "'"
IDENTIFIER_START = '`'
IDENTIFIER_END = '`'
TOKENIZER_CLASS = <class 'MySQL.Tokenizer'>
BIT_START: Optional[str] = "b'"
BIT_END: Optional[str] = "'"
HEX_START: Optional[str] = "x'"
HEX_END: Optional[str] = "'"
BYTE_START: Optional[str] = None
BYTE_END: Optional[str] = None

##### Inherited Members

sqlglot.generator.Generator
  Generator
  LOG_BASE_FIRST
  EXPLICIT_UNION
  WRAP_DERIVED_VALUES
  CREATE_FUNCTION_RETURN_AS
  MATCHED_BY_SOURCE
  SINGLE_STRING_INTERVAL
  INTERVAL_ALLOWS_PLURAL_FORM
  TABLESAMPLE_WITH_METHOD
  TABLESAMPLE_SIZE_IS_PERCENT
  RENAME_TABLE_WITH_DB
  GROUPINGS_SEP
  INDEX_ON
  QUERY_HINTS
  IS_BOOL_ALLOWED
  LIMIT_IS_TOP
  RETURNING_END
  COLUMN_JOIN_MARKS_SUPPORTED
  EXTRACT_ALLOWS_QUOTES
  TZ_TO_WITH_TIME_ZONE
  ALTER_TABLE_ADD_COLUMN_KEYWORD
  UNNEST_WITH_ORDINALITY
  AGGREGATE_FILTER_SUPPORTED
  SEMI_ANTI_JOIN_WITH_SIDE
  SUPPORTS_PARAMETERS
  COMPUTED_COLUMN_WITH_TYPE
  SUPPORTS_TABLE_COPY
  TABLESAMPLE_REQUIRES_PARENS
  COLLATE_IS_FUNC
  DATA_TYPE_SPECIFIERS_ALLOWED
  SUPPORTS_NESTED_CTES
  CTE_RECURSIVE_KEYWORD_REQUIRED
  STAR_MAPPING
  TIME_PART_SINGULARS
  TOKEN_MAPPING
  STRUCT_DELIMITER
  PARAMETER_TOKEN
  RESERVED_KEYWORDS
  WITH_SEPARATED_COMMENTS
  EXCLUDE_COMMENTS
  UNWRAPPED_INTERVAL_VALUES
  SENTINEL_LINE_BREAK
  INDEX_OFFSET
  UNNEST_COLUMN_ONLY
  ALIAS_POST_TABLESAMPLE
  STRICT_STRING_CONCAT
  NORMALIZE_FUNCTIONS
  NULL_ORDERING
  pretty
  identify
  normalize
  pad
  unsupported_level
  max_unsupported
  leading_comma
  max_text_width
  comments
  normalize_functions
  unsupported_messages
  generate
  unsupported
  sep
  seg
  pad_comment
  maybe_comment
  wrap
  no_identify
  normalize_func
  indent
  sql
  uncache_sql
  cache_sql
  characterset_sql
  column_sql
  columnposition_sql
  columndef_sql
  columnconstraint_sql
  computedcolumnconstraint_sql
  autoincrementcolumnconstraint_sql
  compresscolumnconstraint_sql
  generatedasidentitycolumnconstraint_sql
  notnullcolumnconstraint_sql
  primarykeycolumnconstraint_sql
  uniquecolumnconstraint_sql
  createable_sql
  create_sql
  clone_sql
  describe_sql
  prepend_ctes
  with_sql
  cte_sql
  tablealias_sql
  bitstring_sql
  hexstring_sql
  bytestring_sql
  rawstring_sql
  datatypeparam_sql
  directory_sql
  delete_sql
  drop_sql
  except_sql
  except_op
  fetch_sql
  filter_sql
  hint_sql
  index_sql
  identifier_sql
  inputoutputformat_sql
  national_sql
  partition_sql
  properties_sql
  root_properties
  properties
  with_properties
  locate_properties
  property_name
  property_sql
  likeproperty_sql
  fallbackproperty_sql
  journalproperty_sql
  freespaceproperty_sql
  checksumproperty_sql
  mergeblockratioproperty_sql
  datablocksizeproperty_sql
  blockcompressionproperty_sql
  isolatedloadingproperty_sql
  partitionboundspec_sql
  partitionedofproperty_sql
  lockingproperty_sql
  withdataproperty_sql
  insert_sql
  intersect_sql
  intersect_op
  introducer_sql
  kill_sql
  pseudotype_sql
  objectidentifier_sql
  onconflict_sql
  returning_sql
  rowformatdelimitedproperty_sql
  withtablehint_sql
  indextablehint_sql
  table_sql
  tablesample_sql
  pivot_sql
  version_sql
  tuple_sql
  update_sql
  values_sql
  var_sql
  into_sql
  from_sql
  group_sql
  having_sql
  connect_sql
  prior_sql
  join_sql
  lambda_sql
  lateral_sql
  limit_sql
  offset_sql
  setitem_sql
  set_sql
  pragma_sql
  lock_sql
  literal_sql
  escape_str
  loaddata_sql
  null_sql
  boolean_sql
  order_sql
  cluster_sql
  distribute_sql
  sort_sql
  ordered_sql
  matchrecognize_sql
  query_modifiers
  offset_limit_modifiers
  after_having_modifiers
  after_limit_modifiers
  select_sql
  schema_sql
  schema_columns_sql
  star_sql
  parameter_sql
  sessionparameter_sql
  placeholder_sql
  subquery_sql
  qualify_sql
  union_sql
  union_op
  unnest_sql
  where_sql
  window_sql
  partition_by_sql
  windowspec_sql
  withingroup_sql
  between_sql
  bracket_sql
  safebracket_sql
  all_sql
  any_sql
  exists_sql
  case_sql
  constraint_sql
  nextvaluefor_sql
  extract_sql
  trim_sql
  safeconcat_sql
  check_sql
  foreignkey_sql
  primarykey_sql
  if_sql
  matchagainst_sql
  jsonkeyvalue_sql
  formatjson_sql
  jsonobject_sql
  jsonarray_sql
  jsonarrayagg_sql
  jsoncolumndef_sql
  jsonschema_sql
  jsontable_sql
  openjsoncolumndef_sql
  openjson_sql
  in_sql
  in_unnest_op
  interval_sql
  return_sql
  reference_sql
  anonymous_sql
  paren_sql
  neg_sql
  not_sql
  alias_sql
  aliases_sql
  attimezone_sql
  add_sql
  and_sql
  connector_sql
  bitwiseand_sql
  bitwiseleftshift_sql
  bitwisenot_sql
  bitwiseor_sql
  bitwiserightshift_sql
  bitwisexor_sql
  currentdate_sql
  collate_sql
  command_sql
  comment_sql
  mergetreettlaction_sql
  mergetreettl_sql
  transaction_sql
  commit_sql
  rollback_sql
  altercolumn_sql
  renametable_sql
  altertable_sql
  droppartition_sql
  addconstraint_sql
  distinct_sql
  ignorenulls_sql
  respectnulls_sql
  intdiv_sql
  dpipe_sql
  safedpipe_sql
  div_sql
  overlaps_sql
  distance_sql
  dot_sql
  eq_sql
  escape_sql
  glob_sql
  gt_sql
  gte_sql
  ilike_sql
  ilikeany_sql
  is_sql
  like_sql
  likeany_sql
  similarto_sql
  lt_sql
  lte_sql
  mod_sql
  mul_sql
  neq_sql
  nullsafeeq_sql
  nullsafeneq_sql
  or_sql
  slice_sql
  sub_sql
  trycast_sql
  log_sql
  use_sql
  binary
  function_fallback_sql
  func
  format_args
  text_width
  format_time
  expressions
  op_expressions
  naked_property
  set_operation
  tag_sql
  token_sql
  userdefinedfunction_sql
  joinhint_sql
  kwarg_sql
  when_sql
  merge_sql
  tochar_sql
  dictproperty_sql
  dictrange_sql
  dictsubproperty_sql
  oncluster_sql
  clusteredbyproperty_sql
  anyvalue_sql
  querytransform_sql
  indexconstraintoption_sql
  indexcolumnconstraint_sql
  nvl2_sql
  comprehension_sql
  columnprefix_sql
  opclass_sql
  predict_sql