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

class MySQL(sqlglot.dialects.dialect.Dialect): View Source

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

    151    class Tokenizer(tokens.Tokenizer):
    152        QUOTES = ["'", '"']
    153        COMMENTS = ["--", "#", ("/*", "*/")]
    154        IDENTIFIERS = ["`"]
    155        STRING_ESCAPES = ["'", '"', "\\"]
    156        BIT_STRINGS = [("b'", "'"), ("B'", "'"), ("0b", "")]
    157        HEX_STRINGS = [("x'", "'"), ("X'", "'"), ("0x", "")]
    158
    159        KEYWORDS = {
    160            **tokens.Tokenizer.KEYWORDS,
    161            "CHARSET": TokenType.CHARACTER_SET,
    162            "ENUM": TokenType.ENUM,
    163            "FORCE": TokenType.FORCE,
    164            "IGNORE": TokenType.IGNORE,
    165            "LOCK TABLES": TokenType.COMMAND,
    166            "LONGBLOB": TokenType.LONGBLOB,
    167            "LONGTEXT": TokenType.LONGTEXT,
    168            "MEDIUMBLOB": TokenType.MEDIUMBLOB,
    169            "TINYBLOB": TokenType.TINYBLOB,
    170            "TINYTEXT": TokenType.TINYTEXT,
    171            "MEDIUMTEXT": TokenType.MEDIUMTEXT,
    172            "MEDIUMINT": TokenType.MEDIUMINT,
    173            "MEMBER OF": TokenType.MEMBER_OF,
    174            "SEPARATOR": TokenType.SEPARATOR,
    175            "START": TokenType.BEGIN,
    176            "SIGNED": TokenType.BIGINT,
    177            "SIGNED INTEGER": TokenType.BIGINT,
    178            "UNLOCK TABLES": TokenType.COMMAND,
    179            "UNSIGNED": TokenType.UBIGINT,
    180            "UNSIGNED INTEGER": TokenType.UBIGINT,
    181            "YEAR": TokenType.YEAR,
    182            "_ARMSCII8": TokenType.INTRODUCER,
    183            "_ASCII": TokenType.INTRODUCER,
    184            "_BIG5": TokenType.INTRODUCER,
    185            "_BINARY": TokenType.INTRODUCER,
    186            "_CP1250": TokenType.INTRODUCER,
    187            "_CP1251": TokenType.INTRODUCER,
    188            "_CP1256": TokenType.INTRODUCER,
    189            "_CP1257": TokenType.INTRODUCER,
    190            "_CP850": TokenType.INTRODUCER,
    191            "_CP852": TokenType.INTRODUCER,
    192            "_CP866": TokenType.INTRODUCER,
    193            "_CP932": TokenType.INTRODUCER,
    194            "_DEC8": TokenType.INTRODUCER,
    195            "_EUCJPMS": TokenType.INTRODUCER,
    196            "_EUCKR": TokenType.INTRODUCER,
    197            "_GB18030": TokenType.INTRODUCER,
    198            "_GB2312": TokenType.INTRODUCER,
    199            "_GBK": TokenType.INTRODUCER,
    200            "_GEOSTD8": TokenType.INTRODUCER,
    201            "_GREEK": TokenType.INTRODUCER,
    202            "_HEBREW": TokenType.INTRODUCER,
    203            "_HP8": TokenType.INTRODUCER,
    204            "_KEYBCS2": TokenType.INTRODUCER,
    205            "_KOI8R": TokenType.INTRODUCER,
    206            "_KOI8U": TokenType.INTRODUCER,
    207            "_LATIN1": TokenType.INTRODUCER,
    208            "_LATIN2": TokenType.INTRODUCER,
    209            "_LATIN5": TokenType.INTRODUCER,
    210            "_LATIN7": TokenType.INTRODUCER,
    211            "_MACCE": TokenType.INTRODUCER,
    212            "_MACROMAN": TokenType.INTRODUCER,
    213            "_SJIS": TokenType.INTRODUCER,
    214            "_SWE7": TokenType.INTRODUCER,
    215            "_TIS620": TokenType.INTRODUCER,
    216            "_UCS2": TokenType.INTRODUCER,
    217            "_UJIS": TokenType.INTRODUCER,
    218            # https://dev.mysql.com/doc/refman/8.0/en/string-literals.html
    219            "_UTF8": TokenType.INTRODUCER,
    220            "_UTF16": TokenType.INTRODUCER,
    221            "_UTF16LE": TokenType.INTRODUCER,
    222            "_UTF32": TokenType.INTRODUCER,
    223            "_UTF8MB3": TokenType.INTRODUCER,
    224            "_UTF8MB4": TokenType.INTRODUCER,
    225            "@@": TokenType.SESSION_PARAMETER,
    226        }
    227
    228        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

    230    class Parser(parser.Parser):
    231        FUNC_TOKENS = {
    232            *parser.Parser.FUNC_TOKENS,
    233            TokenType.DATABASE,
    234            TokenType.SCHEMA,
    235            TokenType.VALUES,
    236        }
    237
    238        CONJUNCTION = {
    239            **parser.Parser.CONJUNCTION,
    240            TokenType.DAMP: exp.And,
    241            TokenType.XOR: exp.Xor,
    242            TokenType.DPIPE: exp.Or,
    243        }
    244
    245        # MySQL uses || as a synonym to the logical OR operator
    246        # https://dev.mysql.com/doc/refman/8.0/en/logical-operators.html#operator_or
    247        BITWISE = parser.Parser.BITWISE.copy()
    248        BITWISE.pop(TokenType.DPIPE)
    249
    250        TABLE_ALIAS_TOKENS = (
    251            parser.Parser.TABLE_ALIAS_TOKENS - parser.Parser.TABLE_INDEX_HINT_TOKENS
    252        )
    253
    254        RANGE_PARSERS = {
    255            **parser.Parser.RANGE_PARSERS,
    256            TokenType.MEMBER_OF: lambda self, this: self.expression(
    257                exp.JSONArrayContains,
    258                this=this,
    259                expression=self._parse_wrapped(self._parse_expression),
    260            ),
    261        }
    262
    263        FUNCTIONS = {
    264            **parser.Parser.FUNCTIONS,
    265            "DATE": lambda args: exp.TsOrDsToDate(this=seq_get(args, 0)),
    266            "DATE_ADD": parse_date_delta_with_interval(exp.DateAdd),
    267            "DATE_FORMAT": format_time_lambda(exp.TimeToStr, "mysql"),
    268            "DATE_SUB": parse_date_delta_with_interval(exp.DateSub),
    269            "INSTR": lambda args: exp.StrPosition(substr=seq_get(args, 1), this=seq_get(args, 0)),
    270            "ISNULL": isnull_to_is_null,
    271            "LOCATE": locate_to_strposition,
    272            "MONTHNAME": lambda args: exp.TimeToStr(
    273                this=exp.TsOrDsToDate(this=seq_get(args, 0)),
    274                format=exp.Literal.string("%B"),
    275            ),
    276            "STR_TO_DATE": _str_to_date,
    277            "TO_DAYS": lambda args: exp.paren(
    278                exp.DateDiff(
    279                    this=exp.TsOrDsToDate(this=seq_get(args, 0)),
    280                    expression=exp.TsOrDsToDate(this=exp.Literal.string("0000-01-01")),
    281                    unit=exp.var("DAY"),
    282                )
    283                + 1
    284            ),
    285            "DAY": lambda args: exp.Day(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    286            "DAYOFMONTH": lambda args: exp.DayOfMonth(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    287            "DAYOFWEEK": lambda args: exp.DayOfWeek(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    288            "DAYOFYEAR": lambda args: exp.DayOfYear(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    289            "MONTH": lambda args: exp.Month(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    290            "WEEK": lambda args: exp.Week(
    291                this=exp.TsOrDsToDate(this=seq_get(args, 0)), mode=seq_get(args, 1)
    292            ),
    293            "WEEKOFYEAR": lambda args: exp.WeekOfYear(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    294            "YEAR": lambda args: exp.Year(this=exp.TsOrDsToDate(this=seq_get(args, 0))),
    295        }
    296
    297        FUNCTION_PARSERS = {
    298            **parser.Parser.FUNCTION_PARSERS,
    299            "CHAR": lambda self: self._parse_chr(),
    300            "GROUP_CONCAT": lambda self: self.expression(
    301                exp.GroupConcat,
    302                this=self._parse_lambda(),
    303                separator=self._match(TokenType.SEPARATOR) and self._parse_field(),
    304            ),
    305            # https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_values
    306            "VALUES": lambda self: self.expression(
    307                exp.Anonymous, this="VALUES", expressions=[self._parse_id_var()]
    308            ),
    309        }
    310
    311        STATEMENT_PARSERS = {
    312            **parser.Parser.STATEMENT_PARSERS,
    313            TokenType.SHOW: lambda self: self._parse_show(),
    314        }
    315
    316        SHOW_PARSERS = {
    317            "BINARY LOGS": _show_parser("BINARY LOGS"),
    318            "MASTER LOGS": _show_parser("BINARY LOGS"),
    319            "BINLOG EVENTS": _show_parser("BINLOG EVENTS"),
    320            "CHARACTER SET": _show_parser("CHARACTER SET"),
    321            "CHARSET": _show_parser("CHARACTER SET"),
    322            "COLLATION": _show_parser("COLLATION"),
    323            "FULL COLUMNS": _show_parser("COLUMNS", target="FROM", full=True),
    324            "COLUMNS": _show_parser("COLUMNS", target="FROM"),
    325            "CREATE DATABASE": _show_parser("CREATE DATABASE", target=True),
    326            "CREATE EVENT": _show_parser("CREATE EVENT", target=True),
    327            "CREATE FUNCTION": _show_parser("CREATE FUNCTION", target=True),
    328            "CREATE PROCEDURE": _show_parser("CREATE PROCEDURE", target=True),
    329            "CREATE TABLE": _show_parser("CREATE TABLE", target=True),
    330            "CREATE TRIGGER": _show_parser("CREATE TRIGGER", target=True),
    331            "CREATE VIEW": _show_parser("CREATE VIEW", target=True),
    332            "DATABASES": _show_parser("DATABASES"),
    333            "ENGINE": _show_parser("ENGINE", target=True),
    334            "STORAGE ENGINES": _show_parser("ENGINES"),
    335            "ENGINES": _show_parser("ENGINES"),
    336            "ERRORS": _show_parser("ERRORS"),
    337            "EVENTS": _show_parser("EVENTS"),
    338            "FUNCTION CODE": _show_parser("FUNCTION CODE", target=True),
    339            "FUNCTION STATUS": _show_parser("FUNCTION STATUS"),
    340            "GRANTS": _show_parser("GRANTS", target="FOR"),
    341            "INDEX": _show_parser("INDEX", target="FROM"),
    342            "MASTER STATUS": _show_parser("MASTER STATUS"),
    343            "OPEN TABLES": _show_parser("OPEN TABLES"),
    344            "PLUGINS": _show_parser("PLUGINS"),
    345            "PROCEDURE CODE": _show_parser("PROCEDURE CODE", target=True),
    346            "PROCEDURE STATUS": _show_parser("PROCEDURE STATUS"),
    347            "PRIVILEGES": _show_parser("PRIVILEGES"),
    348            "FULL PROCESSLIST": _show_parser("PROCESSLIST", full=True),
    349            "PROCESSLIST": _show_parser("PROCESSLIST"),
    350            "PROFILE": _show_parser("PROFILE"),
    351            "PROFILES": _show_parser("PROFILES"),
    352            "RELAYLOG EVENTS": _show_parser("RELAYLOG EVENTS"),
    353            "REPLICAS": _show_parser("REPLICAS"),
    354            "SLAVE HOSTS": _show_parser("REPLICAS"),
    355            "REPLICA STATUS": _show_parser("REPLICA STATUS"),
    356            "SLAVE STATUS": _show_parser("REPLICA STATUS"),
    357            "GLOBAL STATUS": _show_parser("STATUS", global_=True),
    358            "SESSION STATUS": _show_parser("STATUS"),
    359            "STATUS": _show_parser("STATUS"),
    360            "TABLE STATUS": _show_parser("TABLE STATUS"),
    361            "FULL TABLES": _show_parser("TABLES", full=True),
    362            "TABLES": _show_parser("TABLES"),
    363            "TRIGGERS": _show_parser("TRIGGERS"),
    364            "GLOBAL VARIABLES": _show_parser("VARIABLES", global_=True),
    365            "SESSION VARIABLES": _show_parser("VARIABLES"),
    366            "VARIABLES": _show_parser("VARIABLES"),
    367            "WARNINGS": _show_parser("WARNINGS"),
    368        }
    369
    370        SET_PARSERS = {
    371            **parser.Parser.SET_PARSERS,
    372            "PERSIST": lambda self: self._parse_set_item_assignment("PERSIST"),
    373            "PERSIST_ONLY": lambda self: self._parse_set_item_assignment("PERSIST_ONLY"),
    374            "CHARACTER SET": lambda self: self._parse_set_item_charset("CHARACTER SET"),
    375            "CHARSET": lambda self: self._parse_set_item_charset("CHARACTER SET"),
    376            "NAMES": lambda self: self._parse_set_item_names(),
    377        }
    378
    379        CONSTRAINT_PARSERS = {
    380            **parser.Parser.CONSTRAINT_PARSERS,
    381            "FULLTEXT": lambda self: self._parse_index_constraint(kind="FULLTEXT"),
    382            "INDEX": lambda self: self._parse_index_constraint(),
    383            "KEY": lambda self: self._parse_index_constraint(),
    384            "SPATIAL": lambda self: self._parse_index_constraint(kind="SPATIAL"),
    385        }
    386
    387        SCHEMA_UNNAMED_CONSTRAINTS = {
    388            *parser.Parser.SCHEMA_UNNAMED_CONSTRAINTS,
    389            "FULLTEXT",
    390            "INDEX",
    391            "KEY",
    392            "SPATIAL",
    393        }
    394
    395        PROFILE_TYPES = {
    396            "ALL",
    397            "BLOCK IO",
    398            "CONTEXT SWITCHES",
    399            "CPU",
    400            "IPC",
    401            "MEMORY",
    402            "PAGE FAULTS",
    403            "SOURCE",
    404            "SWAPS",
    405        }
    406
    407        TYPE_TOKENS = {
    408            *parser.Parser.TYPE_TOKENS,
    409            TokenType.SET,
    410        }
    411
    412        ENUM_TYPE_TOKENS = {
    413            *parser.Parser.ENUM_TYPE_TOKENS,
    414            TokenType.SET,
    415        }
    416
    417        LOG_DEFAULTS_TO_LN = True
    418
    419        def _parse_primary_key_part(self) -> t.Optional[exp.Expression]:
    420            this = self._parse_id_var()
    421            if not self._match(TokenType.L_PAREN):
    422                return this
    423
    424            expression = self._parse_number()
    425            self._match_r_paren()
    426            return self.expression(exp.ColumnPrefix, this=this, expression=expression)
    427
    428        def _parse_index_constraint(
    429            self, kind: t.Optional[str] = None
    430        ) -> exp.IndexColumnConstraint:
    431            if kind:
    432                self._match_texts({"INDEX", "KEY"})
    433
    434            this = self._parse_id_var(any_token=False)
    435            index_type = self._match(TokenType.USING) and self._advance_any() and self._prev.text
    436            schema = self._parse_schema()
    437
    438            options = []
    439            while True:
    440                if self._match_text_seq("KEY_BLOCK_SIZE"):
    441                    self._match(TokenType.EQ)
    442                    opt = exp.IndexConstraintOption(key_block_size=self._parse_number())
    443                elif self._match(TokenType.USING):
    444                    opt = exp.IndexConstraintOption(using=self._advance_any() and self._prev.text)
    445                elif self._match_text_seq("WITH", "PARSER"):
    446                    opt = exp.IndexConstraintOption(parser=self._parse_var(any_token=True))
    447                elif self._match(TokenType.COMMENT):
    448                    opt = exp.IndexConstraintOption(comment=self._parse_string())
    449                elif self._match_text_seq("VISIBLE"):
    450                    opt = exp.IndexConstraintOption(visible=True)
    451                elif self._match_text_seq("INVISIBLE"):
    452                    opt = exp.IndexConstraintOption(visible=False)
    453                elif self._match_text_seq("ENGINE_ATTRIBUTE"):
    454                    self._match(TokenType.EQ)
    455                    opt = exp.IndexConstraintOption(engine_attr=self._parse_string())
    456                elif self._match_text_seq("ENGINE_ATTRIBUTE"):
    457                    self._match(TokenType.EQ)
    458                    opt = exp.IndexConstraintOption(engine_attr=self._parse_string())
    459                elif self._match_text_seq("SECONDARY_ENGINE_ATTRIBUTE"):
    460                    self._match(TokenType.EQ)
    461                    opt = exp.IndexConstraintOption(secondary_engine_attr=self._parse_string())
    462                else:
    463                    opt = None
    464
    465                if not opt:
    466                    break
    467
    468                options.append(opt)
    469
    470            return self.expression(
    471                exp.IndexColumnConstraint,
    472                this=this,
    473                schema=schema,
    474                kind=kind,
    475                index_type=index_type,
    476                options=options,
    477            )
    478
    479        def _parse_show_mysql(
    480            self,
    481            this: str,
    482            target: bool | str = False,
    483            full: t.Optional[bool] = None,
    484            global_: t.Optional[bool] = None,
    485        ) -> exp.Show:
    486            if target:
    487                if isinstance(target, str):
    488                    self._match_text_seq(target)
    489                target_id = self._parse_id_var()
    490            else:
    491                target_id = None
    492
    493            log = self._parse_string() if self._match_text_seq("IN") else None
    494
    495            if this in {"BINLOG EVENTS", "RELAYLOG EVENTS"}:
    496                position = self._parse_number() if self._match_text_seq("FROM") else None
    497                db = None
    498            else:
    499                position = None
    500                db = None
    501
    502                if self._match(TokenType.FROM):
    503                    db = self._parse_id_var()
    504                elif self._match(TokenType.DOT):
    505                    db = target_id
    506                    target_id = self._parse_id_var()
    507
    508            channel = self._parse_id_var() if self._match_text_seq("FOR", "CHANNEL") else None
    509
    510            like = self._parse_string() if self._match_text_seq("LIKE") else None
    511            where = self._parse_where()
    512
    513            if this == "PROFILE":
    514                types = self._parse_csv(lambda: self._parse_var_from_options(self.PROFILE_TYPES))
    515                query = self._parse_number() if self._match_text_seq("FOR", "QUERY") else None
    516                offset = self._parse_number() if self._match_text_seq("OFFSET") else None
    517                limit = self._parse_number() if self._match_text_seq("LIMIT") else None
    518            else:
    519                types, query = None, None
    520                offset, limit = self._parse_oldstyle_limit()
    521
    522            mutex = True if self._match_text_seq("MUTEX") else None
    523            mutex = False if self._match_text_seq("STATUS") else mutex
    524
    525            return self.expression(
    526                exp.Show,
    527                this=this,
    528                target=target_id,
    529                full=full,
    530                log=log,
    531                position=position,
    532                db=db,
    533                channel=channel,
    534                like=like,
    535                where=where,
    536                types=types,
    537                query=query,
    538                offset=offset,
    539                limit=limit,
    540                mutex=mutex,
    541                **{"global": global_},  # type: ignore
    542            )
    543
    544        def _parse_oldstyle_limit(
    545            self,
    546        ) -> t.Tuple[t.Optional[exp.Expression], t.Optional[exp.Expression]]:
    547            limit = None
    548            offset = None
    549            if self._match_text_seq("LIMIT"):
    550                parts = self._parse_csv(self._parse_number)
    551                if len(parts) == 1:
    552                    limit = parts[0]
    553                elif len(parts) == 2:
    554                    limit = parts[1]
    555                    offset = parts[0]
    556
    557            return offset, limit
    558
    559        def _parse_set_item_charset(self, kind: str) -> exp.Expression:
    560            this = self._parse_string() or self._parse_id_var()
    561            return self.expression(exp.SetItem, this=this, kind=kind)
    562
    563        def _parse_set_item_names(self) -> exp.Expression:
    564            charset = self._parse_string() or self._parse_id_var()
    565            if self._match_text_seq("COLLATE"):
    566                collate = self._parse_string() or self._parse_id_var()
    567            else:
    568                collate = None
    569
    570            return self.expression(exp.SetItem, this=charset, collate=collate, kind="NAMES")
    571
    572        def _parse_type(self, parse_interval: bool = True) -> t.Optional[exp.Expression]:
    573            # mysql binary is special and can work anywhere, even in order by operations
    574            # it operates like a no paren func
    575            if self._match(TokenType.BINARY, advance=False):
    576                data_type = self._parse_types(check_func=True, allow_identifiers=False)
    577
    578                if isinstance(data_type, exp.DataType):
    579                    return self.expression(exp.Cast, this=self._parse_column(), to=data_type)
    580
    581            return super()._parse_type(parse_interval=parse_interval)
    582
    583        def _parse_chr(self) -> t.Optional[exp.Expression]:
    584            expressions = self._parse_csv(self._parse_conjunction)
    585            kwargs: t.Dict[str, t.Any] = {"this": seq_get(expressions, 0)}
    586
    587            if len(expressions) > 1:
    588                kwargs["expressions"] = expressions[1:]
    589
    590            if self._match(TokenType.USING):
    591                kwargs["charset"] = self._parse_var()
    592
    593            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.JSON: 'JSON'>, <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.NULLABLE: 'NULLABLE'>, <TokenType.NESTED: 'NESTED'>, <TokenType.UNNEST: 'UNNEST'>, <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, <TokenType.VALUES: 'VALUES'>, <TokenType.UTINYINT: 'UTINYINT'>, <TokenType.NULL: 'NULL'>, <TokenType.TEXT: 'TEXT'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.OBJECT_IDENTIFIER: 'OBJECT_IDENTIFIER'>, <TokenType.TIME: 'TIME'>, <TokenType.REPLACE: 'REPLACE'>, <TokenType.USMALLINT: 'USMALLINT'>, <TokenType.HSTORE: 'HSTORE'>, <TokenType.FORMAT: 'FORMAT'>, <TokenType.INDEX: 'INDEX'>, <TokenType.MONEY: 'MONEY'>, <TokenType.HLLSKETCH: 'HLLSKETCH'>, <TokenType.RIGHT: 'RIGHT'>, <TokenType.MERGE: 'MERGE'>, <TokenType.TINYTEXT: 'TINYTEXT'>, <TokenType.DATERANGE: 'DATERANGE'>, <TokenType.RANGE: 'RANGE'>, <TokenType.TIMETZ: 'TIMETZ'>, <TokenType.JSONB: 'JSONB'>, <TokenType.BIGINT: 'BIGINT'>, <TokenType.INSERT: 'INSERT'>, <TokenType.UINT256: 'UINT256'>, <TokenType.NUMRANGE: 'NUMRANGE'>, <TokenType.BIT: 'BIT'>, <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, <TokenType.VARIANT: 'VARIANT'>, <TokenType.GEOMETRY: 'GEOMETRY'>, <TokenType.DATE: 'DATE'>, <TokenType.SERIAL: 'SERIAL'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.BINARY: 'BINARY'>, <TokenType.NCHAR: 'NCHAR'>, <TokenType.ILIKE: 'ILIKE'>, <TokenType.INT256: 'INT256'>, <TokenType.UUID: 'UUID'>, <TokenType.TSRANGE: 'TSRANGE'>, <TokenType.FIXEDSTRING: 'FIXEDSTRING'>, <TokenType.SMALLMONEY: 'SMALLMONEY'>, <TokenType.TIMESTAMP: 'TIMESTAMP'>, <TokenType.UDECIMAL: 'UDECIMAL'>, <TokenType.YEAR: 'YEAR'>, <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, <TokenType.IPPREFIX: 'IPPREFIX'>, <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>, <TokenType.RLIKE: 'RLIKE'>, <TokenType.VARCHAR: 'VARCHAR'>, <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <TokenType.BOOLEAN: 'BOOLEAN'>, <TokenType.UBIGINT: 'UBIGINT'>, <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, <TokenType.ANY: 'ANY'>, <TokenType.FILTER: 'FILTER'>, <TokenType.TINYBLOB: 'TINYBLOB'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, <TokenType.GLOB: 'GLOB'>, <TokenType.FLOAT: 'FLOAT'>, <TokenType.IPADDRESS: 'IPADDRESS'>, <TokenType.TINYINT: 'TINYINT'>, <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, <TokenType.SMALLINT: 'SMALLINT'>, <TokenType.BIGSERIAL: 'BIGSERIAL'>, <TokenType.MEDIUMINT: 'MEDIUMINT'>, <TokenType.IMAGE: 'IMAGE'>, <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, <TokenType.XOR: 'XOR'>, <TokenType.INET: 'INET'>, <TokenType.LEFT: 'LEFT'>, <TokenType.SMALLSERIAL: 'SMALLSERIAL'>, <TokenType.CHAR: 'CHAR'>, <TokenType.SUPER: 'SUPER'>, <TokenType.MAP: 'MAP'>, <TokenType.INT128: 'INT128'>, <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>, <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, <TokenType.USERDEFINED: 'USERDEFINED'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.INT: 'INT'>, <TokenType.UMEDIUMINT: 'UMEDIUMINT'>, <TokenType.INT4RANGE: 'INT4RANGE'>, <TokenType.ENUM16: 'ENUM16'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.FIRST: 'FIRST'>, <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <TokenType.INTERVAL: 'INTERVAL'>, <TokenType.LONGBLOB: 'LONGBLOB'>, <TokenType.WINDOW: 'WINDOW'>, <TokenType.NVARCHAR: 'NVARCHAR'>, <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.TSTZRANGE: 'TSTZRANGE'>, <TokenType.DATETIME64: 'DATETIME64'>, <TokenType.DATETIME: 'DATETIME'>, <TokenType.UINT: 'UINT'>, <TokenType.VAR: 'VAR'>, <TokenType.IDENTIFIER: 'IDENTIFIER'>, <TokenType.XML: 'XML'>, <TokenType.ENUM8: 'ENUM8'>, <TokenType.ENUM: 'ENUM'>, <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.OFFSET: 'OFFSET'>, <TokenType.DOUBLE: 'DOUBLE'>, <TokenType.SOME: 'SOME'>, <TokenType.VARBINARY: 'VARBINARY'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.TABLE: 'TABLE'>, <TokenType.OBJECT: 'OBJECT'>, <TokenType.LIKE: 'LIKE'>, <TokenType.ROWVERSION: 'ROWVERSION'>, <TokenType.INT8RANGE: 'INT8RANGE'>, <TokenType.ROW: 'ROW'>, <TokenType.LONGTEXT: 'LONGTEXT'>, <TokenType.DECIMAL: 'DECIMAL'>, <TokenType.ARRAY: 'ARRAY'>, <TokenType.UINT128: 'UINT128'>, <TokenType.STRUCT: 'STRUCT'>, <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.UNKNOWN: 'UNKNOWN'>, <TokenType.ALL: 'ALL'>}
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.LOAD: 'LOAD'>, <TokenType.FUNCTION: 'FUNCTION'>, <TokenType.JSON: 'JSON'>, <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.TEMPORARY: 'TEMPORARY'>, <TokenType.BEGIN: 'BEGIN'>, <TokenType.NULLABLE: 'NULLABLE'>, <TokenType.NESTED: 'NESTED'>, <TokenType.VIEW: 'VIEW'>, <TokenType.IS: 'IS'>, <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, <TokenType.REFERENCES: 'REFERENCES'>, <TokenType.UTINYINT: 'UTINYINT'>, <TokenType.NULL: 'NULL'>, <TokenType.PARTITION: 'PARTITION'>, <TokenType.TEXT: 'TEXT'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.OBJECT_IDENTIFIER: 'OBJECT_IDENTIFIER'>, <TokenType.TIME: 'TIME'>, <TokenType.COMMENT: 'COMMENT'>, <TokenType.ANTI: 'ANTI'>, <TokenType.CONSTRAINT: 'CONSTRAINT'>, <TokenType.USMALLINT: 'USMALLINT'>, <TokenType.HSTORE: 'HSTORE'>, <TokenType.FORMAT: 'FORMAT'>, <TokenType.INDEX: 'INDEX'>, <TokenType.MONEY: 'MONEY'>, <TokenType.HLLSKETCH: 'HLLSKETCH'>, <TokenType.COMMIT: 'COMMIT'>, <TokenType.MERGE: 'MERGE'>, <TokenType.TINYTEXT: 'TINYTEXT'>, <TokenType.DATERANGE: 'DATERANGE'>, <TokenType.ROWS: 'ROWS'>, <TokenType.RANGE: 'RANGE'>, <TokenType.TIMETZ: 'TIMETZ'>, <TokenType.OVERLAPS: 'OVERLAPS'>, <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, <TokenType.JSONB: 'JSONB'>, <TokenType.BIGINT: 'BIGINT'>, <TokenType.DESC: 'DESC'>, <TokenType.UINT256: 'UINT256'>, <TokenType.NUMRANGE: 'NUMRANGE'>, <TokenType.BIT: 'BIT'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, <TokenType.VARIANT: 'VARIANT'>, <TokenType.GEOMETRY: 'GEOMETRY'>, <TokenType.SERIAL: 'SERIAL'>, <TokenType.DATE: 'DATE'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.BINARY: 'BINARY'>, <TokenType.NCHAR: 'NCHAR'>, <TokenType.PIVOT: 'PIVOT'>, <TokenType.SHOW: 'SHOW'>, <TokenType.KEEP: 'KEEP'>, <TokenType.INT256: 'INT256'>, <TokenType.UUID: 'UUID'>, <TokenType.TSRANGE: 'TSRANGE'>, <TokenType.FIXEDSTRING: 'FIXEDSTRING'>, <TokenType.SMALLMONEY: 'SMALLMONEY'>, <TokenType.TIMESTAMP: 'TIMESTAMP'>, <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, <TokenType.UDECIMAL: 'UDECIMAL'>, <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, <TokenType.IPPREFIX: 'IPPREFIX'>, <TokenType.VARCHAR: 'VARCHAR'>, <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <TokenType.BOOLEAN: 'BOOLEAN'>, <TokenType.UBIGINT: 'UBIGINT'>, <TokenType.TRUE: 'TRUE'>, <TokenType.DEFAULT: 'DEFAULT'>, <TokenType.COLUMN: 'COLUMN'>, <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, <TokenType.ANY: 'ANY'>, <TokenType.FILTER: 'FILTER'>, <TokenType.FALSE: 'FALSE'>, <TokenType.VOLATILE: 'VOLATILE'>, <TokenType.TINYBLOB: 'TINYBLOB'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, <TokenType.PRAGMA: 'PRAGMA'>, <TokenType.FLOAT: 'FLOAT'>, <TokenType.NEXT: 'NEXT'>, <TokenType.IPADDRESS: 'IPADDRESS'>, <TokenType.PROCEDURE: 'PROCEDURE'>, <TokenType.TINYINT: 'TINYINT'>, <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, <TokenType.SMALLINT: 'SMALLINT'>, <TokenType.BIGSERIAL: 'BIGSERIAL'>, <TokenType.MEDIUMINT: 'MEDIUMINT'>, <TokenType.IMAGE: 'IMAGE'>, <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, <TokenType.SETTINGS: 'SETTINGS'>, <TokenType.INET: 'INET'>, <TokenType.SET: 'SET'>, <TokenType.SMALLSERIAL: 'SMALLSERIAL'>, <TokenType.CHAR: 'CHAR'>, <TokenType.SUPER: 'SUPER'>, <TokenType.MAP: 'MAP'>, <TokenType.UNIQUE: 'UNIQUE'>, <TokenType.INT128: 'INT128'>, <TokenType.OVERWRITE: 'OVERWRITE'>, <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>, <TokenType.CASE: 'CASE'>, <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, <TokenType.PERCENT: 'PERCENT'>, <TokenType.USERDEFINED: 'USERDEFINED'>, <TokenType.ESCAPE: 'ESCAPE'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.UNPIVOT: 'UNPIVOT'>, <TokenType.INT: 'INT'>, <TokenType.UMEDIUMINT: 'UMEDIUMINT'>, <TokenType.INT4RANGE: 'INT4RANGE'>, <TokenType.ENUM16: 'ENUM16'>, <TokenType.END: 'END'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.FIRST: 'FIRST'>, <TokenType.DELETE: 'DELETE'>, <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <TokenType.INTERVAL: 'INTERVAL'>, <TokenType.LONGBLOB: 'LONGBLOB'>, <TokenType.NVARCHAR: 'NVARCHAR'>, <TokenType.KILL: 'KILL'>, <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.TSTZRANGE: 'TSTZRANGE'>, <TokenType.DATETIME64: 'DATETIME64'>, <TokenType.DATETIME: 'DATETIME'>, <TokenType.UINT: 'UINT'>, <TokenType.VAR: 'VAR'>, <TokenType.SEMI: 'SEMI'>, <TokenType.XML: 'XML'>, <TokenType.ENUM8: 'ENUM8'>, <TokenType.ENUM: 'ENUM'>, <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.TOP: 'TOP'>, <TokenType.DOUBLE: 'DOUBLE'>, <TokenType.SOME: 'SOME'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.VARBINARY: 'VARBINARY'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.TABLE: 'TABLE'>, <TokenType.OBJECT: 'OBJECT'>, <TokenType.CACHE: 'CACHE'>, <TokenType.ORDINALITY: 'ORDINALITY'>, <TokenType.DICTIONARY: 'DICTIONARY'>, <TokenType.ASC: 'ASC'>, <TokenType.ROWVERSION: 'ROWVERSION'>, <TokenType.INT8RANGE: 'INT8RANGE'>, <TokenType.DIV: 'DIV'>, <TokenType.ROW: 'ROW'>, <TokenType.LONGTEXT: 'LONGTEXT'>, <TokenType.DECIMAL: 'DECIMAL'>, <TokenType.ARRAY: 'ARRAY'>, <TokenType.UINT128: 'UINT128'>, <TokenType.STRUCT: 'STRUCT'>, <TokenType.YEAR: 'YEAR'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.UNKNOWN: 'UNKNOWN'>, <TokenType.DESCRIBE: 'DESCRIBE'>, <TokenType.ALL: 'ALL'>}
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'>>, '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'>>, 'EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Extract'>>, 'FIRST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.First'>>, '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'>>, 'POWER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, 'POW': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, '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>>, 'LOG': <function Parser.<lambda>>, 'MATCH': <function Parser.<lambda>>, 'OPENJSON': <function Parser.<lambda>>, 'POSITION': <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 = {'UNIQUE', 'SPATIAL', 'PRIMARY KEY', 'LIKE', 'CHECK', 'INDEX', 'FOREIGN KEY', 'KEY', 'FULLTEXT'}
PROFILE_TYPES = {'IPC', 'SOURCE', 'CPU', 'BLOCK IO', 'SWAPS', 'CONTEXT SWITCHES', 'PAGE FAULTS', 'MEMORY', 'ALL'}
TYPE_TOKENS = {<TokenType.JSON: 'JSON'>, <TokenType.FLOAT: 'FLOAT'>, <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, <TokenType.NULLABLE: 'NULLABLE'>, <TokenType.IPADDRESS: 'IPADDRESS'>, <TokenType.NESTED: 'NESTED'>, <TokenType.TINYINT: 'TINYINT'>, <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, <TokenType.SMALLINT: 'SMALLINT'>, <TokenType.UTINYINT: 'UTINYINT'>, <TokenType.NULL: 'NULL'>, <TokenType.BIGSERIAL: 'BIGSERIAL'>, <TokenType.MEDIUMINT: 'MEDIUMINT'>, <TokenType.IMAGE: 'IMAGE'>, <TokenType.TEXT: 'TEXT'>, <TokenType.OBJECT_IDENTIFIER: 'OBJECT_IDENTIFIER'>, <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, <TokenType.TIME: 'TIME'>, <TokenType.INET: 'INET'>, <TokenType.SET: 'SET'>, <TokenType.USMALLINT: 'USMALLINT'>, <TokenType.HSTORE: 'HSTORE'>, <TokenType.SMALLSERIAL: 'SMALLSERIAL'>, <TokenType.MONEY: 'MONEY'>, <TokenType.CHAR: 'CHAR'>, <TokenType.SUPER: 'SUPER'>, <TokenType.HLLSKETCH: 'HLLSKETCH'>, <TokenType.MAP: 'MAP'>, <TokenType.TINYTEXT: 'TINYTEXT'>, <TokenType.INT128: 'INT128'>, <TokenType.DATERANGE: 'DATERANGE'>, <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>, <TokenType.TIMETZ: 'TIMETZ'>, <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, <TokenType.USERDEFINED: 'USERDEFINED'>, <TokenType.JSONB: 'JSONB'>, <TokenType.BIGINT: 'BIGINT'>, <TokenType.UINT256: 'UINT256'>, <TokenType.NUMRANGE: 'NUMRANGE'>, <TokenType.BIT: 'BIT'>, <TokenType.INT: 'INT'>, <TokenType.UMEDIUMINT: 'UMEDIUMINT'>, <TokenType.INT4RANGE: 'INT4RANGE'>, <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, <TokenType.VARIANT: 'VARIANT'>, <TokenType.ENUM16: 'ENUM16'>, <TokenType.GEOMETRY: 'GEOMETRY'>, <TokenType.SERIAL: 'SERIAL'>, <TokenType.DATE: 'DATE'>, <TokenType.BINARY: 'BINARY'>, <TokenType.NCHAR: 'NCHAR'>, <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <TokenType.INTERVAL: 'INTERVAL'>, <TokenType.LONGBLOB: 'LONGBLOB'>, <TokenType.NVARCHAR: 'NVARCHAR'>, <TokenType.INT256: 'INT256'>, <TokenType.UUID: 'UUID'>, <TokenType.TSRANGE: 'TSRANGE'>, <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, <TokenType.TSTZRANGE: 'TSTZRANGE'>, <TokenType.DATETIME64: 'DATETIME64'>, <TokenType.FIXEDSTRING: 'FIXEDSTRING'>, <TokenType.DATETIME: 'DATETIME'>, <TokenType.SMALLMONEY: 'SMALLMONEY'>, <TokenType.UINT: 'UINT'>, <TokenType.TIMESTAMP: 'TIMESTAMP'>, <TokenType.UDECIMAL: 'UDECIMAL'>, <TokenType.XML: 'XML'>, <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, <TokenType.YEAR: 'YEAR'>, <TokenType.ENUM8: 'ENUM8'>, <TokenType.IPPREFIX: 'IPPREFIX'>, <TokenType.ENUM: 'ENUM'>, <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>, <TokenType.DOUBLE: 'DOUBLE'>, <TokenType.VARBINARY: 'VARBINARY'>, <TokenType.OBJECT: 'OBJECT'>, <TokenType.VARCHAR: 'VARCHAR'>, <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <TokenType.BOOLEAN: 'BOOLEAN'>, <TokenType.UBIGINT: 'UBIGINT'>, <TokenType.ROWVERSION: 'ROWVERSION'>, <TokenType.INT8RANGE: 'INT8RANGE'>, <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, <TokenType.LONGTEXT: 'LONGTEXT'>, <TokenType.DECIMAL: 'DECIMAL'>, <TokenType.TINYBLOB: 'TINYBLOB'>, <TokenType.ARRAY: 'ARRAY'>, <TokenType.UINT128: 'UINT128'>, <TokenType.STRUCT: 'STRUCT'>, <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, <TokenType.UNKNOWN: 'UNKNOWN'>}
ENUM_TYPE_TOKENS = {<TokenType.ENUM16: 'ENUM16'>, <TokenType.ENUM8: 'ENUM8'>, <TokenType.ENUM: 'ENUM'>, <TokenType.SET: 'SET'>}
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

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

    709        def datatype_sql(self, expression: exp.DataType) -> str:
    710            # https://dev.mysql.com/doc/refman/8.0/en/numeric-type-syntax.html
    711            result = super().datatype_sql(expression)
    712            if expression.this in self.UNSIGNED_TYPE_MAPPING:
    713                result = f"{result} UNSIGNED"
    714            return result

def limit_sql(self, expression: sqlglot.expressions.Limit, top: bool = False) -> str: View Source

    716        def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    717            # MySQL requires simple literal values for its LIMIT clause.
    718            expression = simplify_literal(expression.copy())
    719            return super().limit_sql(expression, top=top)

def offset_sql(self, expression: sqlglot.expressions.Offset) -> str: View Source

    721        def offset_sql(self, expression: exp.Offset) -> str:
    722            # MySQL requires simple literal values for its OFFSET clause.
    723            expression = simplify_literal(expression.copy())
    724            return super().offset_sql(expression)

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

    726        def xor_sql(self, expression: exp.Xor) -> str:
    727            if expression.expressions:
    728                return self.expressions(expression, sep=" XOR ")
    729            return super().xor_sql(expression)

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

    731        def jsonarraycontains_sql(self, expression: exp.JSONArrayContains) -> str:
    732            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

    734        def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    735            if expression.to.this in self.TIMESTAMP_FUNC_TYPES:
    736                return self.func("TIMESTAMP", expression.this)
    737
    738            to = self.CAST_MAPPING.get(expression.to.this)
    739
    740            if to:
    741                expression = expression.copy()
    742                expression.to.set("this", to)
    743            return super().cast_sql(expression)

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

    745        def show_sql(self, expression: exp.Show) -> str:
    746            this = f" {expression.name}"
    747            full = " FULL" if expression.args.get("full") else ""
    748            global_ = " GLOBAL" if expression.args.get("global") else ""
    749
    750            target = self.sql(expression, "target")
    751            target = f" {target}" if target else ""
    752            if expression.name in {"COLUMNS", "INDEX"}:
    753                target = f" FROM{target}"
    754            elif expression.name == "GRANTS":
    755                target = f" FOR{target}"
    756
    757            db = self._prefixed_sql("FROM", expression, "db")
    758
    759            like = self._prefixed_sql("LIKE", expression, "like")
    760            where = self.sql(expression, "where")
    761
    762            types = self.expressions(expression, key="types")
    763            types = f" {types}" if types else types
    764            query = self._prefixed_sql("FOR QUERY", expression, "query")
    765
    766            if expression.name == "PROFILE":
    767                offset = self._prefixed_sql("OFFSET", expression, "offset")
    768                limit = self._prefixed_sql("LIMIT", expression, "limit")
    769            else:
    770                offset = ""
    771                limit = self._oldstyle_limit_sql(expression)
    772
    773            log = self._prefixed_sql("IN", expression, "log")
    774            position = self._prefixed_sql("FROM", expression, "position")
    775
    776            channel = self._prefixed_sql("FOR CHANNEL", expression, "channel")
    777
    778            if expression.name == "ENGINE":
    779                mutex_or_status = " MUTEX" if expression.args.get("mutex") else " STATUS"
    780            else:
    781                mutex_or_status = ""
    782
    783            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

    797        def chr_sql(self, expression: exp.Chr) -> str:
    798            this = self.expressions(sqls=[expression.this] + expression.expressions)
    799            charset = expression.args.get("charset")
    800            using = f" USING {self.sql(charset)}" if charset else ""
    801            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
  STAR_MAPPING
  TIME_PART_SINGULARS
  TOKEN_MAPPING
  STRUCT_DELIMITER
  PARAMETER_TOKEN
  RESERVED_KEYWORDS
  WITH_SEPARATED_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
  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
  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
  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