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

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

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

IDENTIFIERS_CAN_START_WITH_DIGIT = True
TIME_FORMAT = "'%Y-%m-%d %T'"
DPIPE_IS_STRING_CONCAT = False
SUPPORTS_USER_DEFINED_TYPES = 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}}}
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
  NULL_ORDERING
  DATE_FORMAT
  DATEINT_FORMAT
  FORMAT_MAPPING
  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

    120    class Tokenizer(tokens.Tokenizer):
    121        QUOTES = ["'", '"']
    122        COMMENTS = ["--", "#", ("/*", "*/")]
    123        IDENTIFIERS = ["`"]
    124        STRING_ESCAPES = ["'", '"', "\\"]
    125        BIT_STRINGS = [("b'", "'"), ("B'", "'"), ("0b", "")]
    126        HEX_STRINGS = [("x'", "'"), ("X'", "'"), ("0x", "")]
    127
    128        KEYWORDS = {
    129            **tokens.Tokenizer.KEYWORDS,
    130            "CHARSET": TokenType.CHARACTER_SET,
    131            "ENUM": TokenType.ENUM,
    132            "FORCE": TokenType.FORCE,
    133            "IGNORE": TokenType.IGNORE,
    134            "LOCK TABLES": TokenType.COMMAND,
    135            "LONGBLOB": TokenType.LONGBLOB,
    136            "LONGTEXT": TokenType.LONGTEXT,
    137            "MEDIUMBLOB": TokenType.MEDIUMBLOB,
    138            "TINYBLOB": TokenType.TINYBLOB,
    139            "TINYTEXT": TokenType.TINYTEXT,
    140            "MEDIUMTEXT": TokenType.MEDIUMTEXT,
    141            "MEDIUMINT": TokenType.MEDIUMINT,
    142            "MEMBER OF": TokenType.MEMBER_OF,
    143            "SEPARATOR": TokenType.SEPARATOR,
    144            "START": TokenType.BEGIN,
    145            "SIGNED": TokenType.BIGINT,
    146            "SIGNED INTEGER": TokenType.BIGINT,
    147            "UNLOCK TABLES": TokenType.COMMAND,
    148            "UNSIGNED": TokenType.UBIGINT,
    149            "UNSIGNED INTEGER": TokenType.UBIGINT,
    150            "YEAR": TokenType.YEAR,
    151            "_ARMSCII8": TokenType.INTRODUCER,
    152            "_ASCII": TokenType.INTRODUCER,
    153            "_BIG5": TokenType.INTRODUCER,
    154            "_BINARY": TokenType.INTRODUCER,
    155            "_CP1250": TokenType.INTRODUCER,
    156            "_CP1251": TokenType.INTRODUCER,
    157            "_CP1256": TokenType.INTRODUCER,
    158            "_CP1257": TokenType.INTRODUCER,
    159            "_CP850": TokenType.INTRODUCER,
    160            "_CP852": TokenType.INTRODUCER,
    161            "_CP866": TokenType.INTRODUCER,
    162            "_CP932": TokenType.INTRODUCER,
    163            "_DEC8": TokenType.INTRODUCER,
    164            "_EUCJPMS": TokenType.INTRODUCER,
    165            "_EUCKR": TokenType.INTRODUCER,
    166            "_GB18030": TokenType.INTRODUCER,
    167            "_GB2312": TokenType.INTRODUCER,
    168            "_GBK": TokenType.INTRODUCER,
    169            "_GEOSTD8": TokenType.INTRODUCER,
    170            "_GREEK": TokenType.INTRODUCER,
    171            "_HEBREW": TokenType.INTRODUCER,
    172            "_HP8": TokenType.INTRODUCER,
    173            "_KEYBCS2": TokenType.INTRODUCER,
    174            "_KOI8R": TokenType.INTRODUCER,
    175            "_KOI8U": TokenType.INTRODUCER,
    176            "_LATIN1": TokenType.INTRODUCER,
    177            "_LATIN2": TokenType.INTRODUCER,
    178            "_LATIN5": TokenType.INTRODUCER,
    179            "_LATIN7": TokenType.INTRODUCER,
    180            "_MACCE": TokenType.INTRODUCER,
    181            "_MACROMAN": TokenType.INTRODUCER,
    182            "_SJIS": TokenType.INTRODUCER,
    183            "_SWE7": TokenType.INTRODUCER,
    184            "_TIS620": TokenType.INTRODUCER,
    185            "_UCS2": TokenType.INTRODUCER,
    186            "_UJIS": TokenType.INTRODUCER,
    187            # https://dev.mysql.com/doc/refman/8.0/en/string-literals.html
    188            "_UTF8": TokenType.INTRODUCER,
    189            "_UTF16": TokenType.INTRODUCER,
    190            "_UTF16LE": TokenType.INTRODUCER,
    191            "_UTF32": TokenType.INTRODUCER,
    192            "_UTF8MB3": TokenType.INTRODUCER,
    193            "_UTF8MB4": TokenType.INTRODUCER,
    194            "@@": TokenType.SESSION_PARAMETER,
    195        }
    196
    197        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'>, '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.COMMAND: 'COMMAND'>, <TokenType.FETCH: 'FETCH'>, <TokenType.EXECUTE: 'EXECUTE'>}
IDENTIFIERS_CAN_START_WITH_DIGIT: bool = True

##### Inherited Members

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

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

    199    class Parser(parser.Parser):
    200        FUNC_TOKENS = {
    201            *parser.Parser.FUNC_TOKENS,
    202            TokenType.DATABASE,
    203            TokenType.SCHEMA,
    204            TokenType.VALUES,
    205        }
    206
    207        CONJUNCTION = {
    208            **parser.Parser.CONJUNCTION,
    209            TokenType.DAMP: exp.And,
    210            TokenType.XOR: exp.Xor,
    211            TokenType.DPIPE: exp.Or,
    212        }
    213
    214        # MySQL uses || as a synonym to the logical OR operator
    215        # https://dev.mysql.com/doc/refman/8.0/en/logical-operators.html#operator_or
    216        BITWISE = parser.Parser.BITWISE.copy()
    217        BITWISE.pop(TokenType.DPIPE)
    218
    219        TABLE_ALIAS_TOKENS = (
    220            parser.Parser.TABLE_ALIAS_TOKENS - parser.Parser.TABLE_INDEX_HINT_TOKENS
    221        )
    222
    223        RANGE_PARSERS = {
    224            **parser.Parser.RANGE_PARSERS,
    225            TokenType.MEMBER_OF: lambda self, this: self.expression(
    226                exp.JSONArrayContains,
    227                this=this,
    228                expression=self._parse_wrapped(self._parse_expression),
    229            ),
    230        }
    231
    232        FUNCTIONS = {
    233            **parser.Parser.FUNCTIONS,
    234            "DATE_ADD": parse_date_delta_with_interval(exp.DateAdd),
    235            "DATE_FORMAT": format_time_lambda(exp.TimeToStr, "mysql"),
    236            "DATE_SUB": parse_date_delta_with_interval(exp.DateSub),
    237            "INSTR": lambda args: exp.StrPosition(substr=seq_get(args, 1), this=seq_get(args, 0)),
    238            "LOCATE": locate_to_strposition,
    239            "STR_TO_DATE": _str_to_date,
    240        }
    241
    242        FUNCTION_PARSERS = {
    243            **parser.Parser.FUNCTION_PARSERS,
    244            "GROUP_CONCAT": lambda self: self.expression(
    245                exp.GroupConcat,
    246                this=self._parse_lambda(),
    247                separator=self._match(TokenType.SEPARATOR) and self._parse_field(),
    248            ),
    249            # https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_values
    250            "VALUES": lambda self: self.expression(
    251                exp.Anonymous, this="VALUES", expressions=[self._parse_id_var()]
    252            ),
    253        }
    254
    255        STATEMENT_PARSERS = {
    256            **parser.Parser.STATEMENT_PARSERS,
    257            TokenType.SHOW: lambda self: self._parse_show(),
    258        }
    259
    260        SHOW_PARSERS = {
    261            "BINARY LOGS": _show_parser("BINARY LOGS"),
    262            "MASTER LOGS": _show_parser("BINARY LOGS"),
    263            "BINLOG EVENTS": _show_parser("BINLOG EVENTS"),
    264            "CHARACTER SET": _show_parser("CHARACTER SET"),
    265            "CHARSET": _show_parser("CHARACTER SET"),
    266            "COLLATION": _show_parser("COLLATION"),
    267            "FULL COLUMNS": _show_parser("COLUMNS", target="FROM", full=True),
    268            "COLUMNS": _show_parser("COLUMNS", target="FROM"),
    269            "CREATE DATABASE": _show_parser("CREATE DATABASE", target=True),
    270            "CREATE EVENT": _show_parser("CREATE EVENT", target=True),
    271            "CREATE FUNCTION": _show_parser("CREATE FUNCTION", target=True),
    272            "CREATE PROCEDURE": _show_parser("CREATE PROCEDURE", target=True),
    273            "CREATE TABLE": _show_parser("CREATE TABLE", target=True),
    274            "CREATE TRIGGER": _show_parser("CREATE TRIGGER", target=True),
    275            "CREATE VIEW": _show_parser("CREATE VIEW", target=True),
    276            "DATABASES": _show_parser("DATABASES"),
    277            "ENGINE": _show_parser("ENGINE", target=True),
    278            "STORAGE ENGINES": _show_parser("ENGINES"),
    279            "ENGINES": _show_parser("ENGINES"),
    280            "ERRORS": _show_parser("ERRORS"),
    281            "EVENTS": _show_parser("EVENTS"),
    282            "FUNCTION CODE": _show_parser("FUNCTION CODE", target=True),
    283            "FUNCTION STATUS": _show_parser("FUNCTION STATUS"),
    284            "GRANTS": _show_parser("GRANTS", target="FOR"),
    285            "INDEX": _show_parser("INDEX", target="FROM"),
    286            "MASTER STATUS": _show_parser("MASTER STATUS"),
    287            "OPEN TABLES": _show_parser("OPEN TABLES"),
    288            "PLUGINS": _show_parser("PLUGINS"),
    289            "PROCEDURE CODE": _show_parser("PROCEDURE CODE", target=True),
    290            "PROCEDURE STATUS": _show_parser("PROCEDURE STATUS"),
    291            "PRIVILEGES": _show_parser("PRIVILEGES"),
    292            "FULL PROCESSLIST": _show_parser("PROCESSLIST", full=True),
    293            "PROCESSLIST": _show_parser("PROCESSLIST"),
    294            "PROFILE": _show_parser("PROFILE"),
    295            "PROFILES": _show_parser("PROFILES"),
    296            "RELAYLOG EVENTS": _show_parser("RELAYLOG EVENTS"),
    297            "REPLICAS": _show_parser("REPLICAS"),
    298            "SLAVE HOSTS": _show_parser("REPLICAS"),
    299            "REPLICA STATUS": _show_parser("REPLICA STATUS"),
    300            "SLAVE STATUS": _show_parser("REPLICA STATUS"),
    301            "GLOBAL STATUS": _show_parser("STATUS", global_=True),
    302            "SESSION STATUS": _show_parser("STATUS"),
    303            "STATUS": _show_parser("STATUS"),
    304            "TABLE STATUS": _show_parser("TABLE STATUS"),
    305            "FULL TABLES": _show_parser("TABLES", full=True),
    306            "TABLES": _show_parser("TABLES"),
    307            "TRIGGERS": _show_parser("TRIGGERS"),
    308            "GLOBAL VARIABLES": _show_parser("VARIABLES", global_=True),
    309            "SESSION VARIABLES": _show_parser("VARIABLES"),
    310            "VARIABLES": _show_parser("VARIABLES"),
    311            "WARNINGS": _show_parser("WARNINGS"),
    312        }
    313
    314        SET_PARSERS = {
    315            **parser.Parser.SET_PARSERS,
    316            "PERSIST": lambda self: self._parse_set_item_assignment("PERSIST"),
    317            "PERSIST_ONLY": lambda self: self._parse_set_item_assignment("PERSIST_ONLY"),
    318            "CHARACTER SET": lambda self: self._parse_set_item_charset("CHARACTER SET"),
    319            "CHARSET": lambda self: self._parse_set_item_charset("CHARACTER SET"),
    320            "NAMES": lambda self: self._parse_set_item_names(),
    321        }
    322
    323        CONSTRAINT_PARSERS = {
    324            **parser.Parser.CONSTRAINT_PARSERS,
    325            "FULLTEXT": lambda self: self._parse_index_constraint(kind="FULLTEXT"),
    326            "INDEX": lambda self: self._parse_index_constraint(),
    327            "KEY": lambda self: self._parse_index_constraint(),
    328            "SPATIAL": lambda self: self._parse_index_constraint(kind="SPATIAL"),
    329        }
    330
    331        SCHEMA_UNNAMED_CONSTRAINTS = {
    332            *parser.Parser.SCHEMA_UNNAMED_CONSTRAINTS,
    333            "FULLTEXT",
    334            "INDEX",
    335            "KEY",
    336            "SPATIAL",
    337        }
    338
    339        PROFILE_TYPES = {
    340            "ALL",
    341            "BLOCK IO",
    342            "CONTEXT SWITCHES",
    343            "CPU",
    344            "IPC",
    345            "MEMORY",
    346            "PAGE FAULTS",
    347            "SOURCE",
    348            "SWAPS",
    349        }
    350
    351        TYPE_TOKENS = {
    352            *parser.Parser.TYPE_TOKENS,
    353            TokenType.SET,
    354        }
    355
    356        ENUM_TYPE_TOKENS = {
    357            *parser.Parser.ENUM_TYPE_TOKENS,
    358            TokenType.SET,
    359        }
    360
    361        LOG_DEFAULTS_TO_LN = True
    362
    363        def _parse_primary_key_part(self) -> t.Optional[exp.Expression]:
    364            this = self._parse_id_var()
    365            if not self._match(TokenType.L_PAREN):
    366                return this
    367
    368            expression = self._parse_number()
    369            self._match_r_paren()
    370            return self.expression(exp.ColumnPrefix, this=this, expression=expression)
    371
    372        def _parse_index_constraint(
    373            self, kind: t.Optional[str] = None
    374        ) -> exp.IndexColumnConstraint:
    375            if kind:
    376                self._match_texts({"INDEX", "KEY"})
    377
    378            this = self._parse_id_var(any_token=False)
    379            index_type = self._match(TokenType.USING) and self._advance_any() and self._prev.text
    380            schema = self._parse_schema()
    381
    382            options = []
    383            while True:
    384                if self._match_text_seq("KEY_BLOCK_SIZE"):
    385                    self._match(TokenType.EQ)
    386                    opt = exp.IndexConstraintOption(key_block_size=self._parse_number())
    387                elif self._match(TokenType.USING):
    388                    opt = exp.IndexConstraintOption(using=self._advance_any() and self._prev.text)
    389                elif self._match_text_seq("WITH", "PARSER"):
    390                    opt = exp.IndexConstraintOption(parser=self._parse_var(any_token=True))
    391                elif self._match(TokenType.COMMENT):
    392                    opt = exp.IndexConstraintOption(comment=self._parse_string())
    393                elif self._match_text_seq("VISIBLE"):
    394                    opt = exp.IndexConstraintOption(visible=True)
    395                elif self._match_text_seq("INVISIBLE"):
    396                    opt = exp.IndexConstraintOption(visible=False)
    397                elif self._match_text_seq("ENGINE_ATTRIBUTE"):
    398                    self._match(TokenType.EQ)
    399                    opt = exp.IndexConstraintOption(engine_attr=self._parse_string())
    400                elif self._match_text_seq("ENGINE_ATTRIBUTE"):
    401                    self._match(TokenType.EQ)
    402                    opt = exp.IndexConstraintOption(engine_attr=self._parse_string())
    403                elif self._match_text_seq("SECONDARY_ENGINE_ATTRIBUTE"):
    404                    self._match(TokenType.EQ)
    405                    opt = exp.IndexConstraintOption(secondary_engine_attr=self._parse_string())
    406                else:
    407                    opt = None
    408
    409                if not opt:
    410                    break
    411
    412                options.append(opt)
    413
    414            return self.expression(
    415                exp.IndexColumnConstraint,
    416                this=this,
    417                schema=schema,
    418                kind=kind,
    419                index_type=index_type,
    420                options=options,
    421            )
    422
    423        def _parse_show_mysql(
    424            self,
    425            this: str,
    426            target: bool | str = False,
    427            full: t.Optional[bool] = None,
    428            global_: t.Optional[bool] = None,
    429        ) -> exp.Show:
    430            if target:
    431                if isinstance(target, str):
    432                    self._match_text_seq(target)
    433                target_id = self._parse_id_var()
    434            else:
    435                target_id = None
    436
    437            log = self._parse_string() if self._match_text_seq("IN") else None
    438
    439            if this in {"BINLOG EVENTS", "RELAYLOG EVENTS"}:
    440                position = self._parse_number() if self._match_text_seq("FROM") else None
    441                db = None
    442            else:
    443                position = None
    444                db = None
    445
    446                if self._match(TokenType.FROM):
    447                    db = self._parse_id_var()
    448                elif self._match(TokenType.DOT):
    449                    db = target_id
    450                    target_id = self._parse_id_var()
    451
    452            channel = self._parse_id_var() if self._match_text_seq("FOR", "CHANNEL") else None
    453
    454            like = self._parse_string() if self._match_text_seq("LIKE") else None
    455            where = self._parse_where()
    456
    457            if this == "PROFILE":
    458                types = self._parse_csv(lambda: self._parse_var_from_options(self.PROFILE_TYPES))
    459                query = self._parse_number() if self._match_text_seq("FOR", "QUERY") else None
    460                offset = self._parse_number() if self._match_text_seq("OFFSET") else None
    461                limit = self._parse_number() if self._match_text_seq("LIMIT") else None
    462            else:
    463                types, query = None, None
    464                offset, limit = self._parse_oldstyle_limit()
    465
    466            mutex = True if self._match_text_seq("MUTEX") else None
    467            mutex = False if self._match_text_seq("STATUS") else mutex
    468
    469            return self.expression(
    470                exp.Show,
    471                this=this,
    472                target=target_id,
    473                full=full,
    474                log=log,
    475                position=position,
    476                db=db,
    477                channel=channel,
    478                like=like,
    479                where=where,
    480                types=types,
    481                query=query,
    482                offset=offset,
    483                limit=limit,
    484                mutex=mutex,
    485                **{"global": global_},  # type: ignore
    486            )
    487
    488        def _parse_oldstyle_limit(
    489            self,
    490        ) -> t.Tuple[t.Optional[exp.Expression], t.Optional[exp.Expression]]:
    491            limit = None
    492            offset = None
    493            if self._match_text_seq("LIMIT"):
    494                parts = self._parse_csv(self._parse_number)
    495                if len(parts) == 1:
    496                    limit = parts[0]
    497                elif len(parts) == 2:
    498                    limit = parts[1]
    499                    offset = parts[0]
    500
    501            return offset, limit
    502
    503        def _parse_set_item_charset(self, kind: str) -> exp.Expression:
    504            this = self._parse_string() or self._parse_id_var()
    505            return self.expression(exp.SetItem, this=this, kind=kind)
    506
    507        def _parse_set_item_names(self) -> exp.Expression:
    508            charset = self._parse_string() or self._parse_id_var()
    509            if self._match_text_seq("COLLATE"):
    510                collate = self._parse_string() or self._parse_id_var()
    511            else:
    512                collate = None
    513
    514            return self.expression(exp.SetItem, this=charset, collate=collate, kind="NAMES")
    515
    516        def _parse_type(self) -> t.Optional[exp.Expression]:
    517            # mysql binary is special and can work anywhere, even in order by operations
    518            # it operates like a no paren func
    519            if self._match(TokenType.BINARY, advance=False):
    520                data_type = self._parse_types(check_func=True, allow_identifiers=False)
    521
    522                if isinstance(data_type, exp.DataType):
    523                    return self.expression(exp.Cast, this=self._parse_column(), to=data_type)
    524
    525            return super()._parse_type()

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.MAP: 'MAP'>, <TokenType.TEXT: 'TEXT'>, <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, <TokenType.VARCHAR: 'VARCHAR'>, <TokenType.TINYTEXT: 'TINYTEXT'>, <TokenType.TIMESTAMP: 'TIMESTAMP'>, <TokenType.IMAGE: 'IMAGE'>, <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, <TokenType.SMALLINT: 'SMALLINT'>, <TokenType.YEAR: 'YEAR'>, <TokenType.RANGE: 'RANGE'>, <TokenType.DOUBLE: 'DOUBLE'>, <TokenType.UUID: 'UUID'>, <TokenType.ILIKE: 'ILIKE'>, <TokenType.INT4RANGE: 'INT4RANGE'>, <TokenType.ALL: 'ALL'>, <TokenType.VARIANT: 'VARIANT'>, <TokenType.FIRST: 'FIRST'>, <TokenType.LIKE: 'LIKE'>, <TokenType.STRUCT: 'STRUCT'>, <TokenType.ANY: 'ANY'>, <TokenType.SUPER: 'SUPER'>, <TokenType.INT256: 'INT256'>, <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <TokenType.JSONB: 'JSONB'>, <TokenType.ENUM8: 'ENUM8'>, <TokenType.FIXEDSTRING: 'FIXEDSTRING'>, <TokenType.WINDOW: 'WINDOW'>, <TokenType.XML: 'XML'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, <TokenType.FORMAT: 'FORMAT'>, <TokenType.INT8RANGE: 'INT8RANGE'>, <TokenType.REPLACE: 'REPLACE'>, <TokenType.MONEY: 'MONEY'>, <TokenType.USMALLINT: 'USMALLINT'>, <TokenType.VAR: 'VAR'>, <TokenType.GLOB: 'GLOB'>, <TokenType.VALUES: 'VALUES'>, <TokenType.FILTER: 'FILTER'>, <TokenType.MERGE: 'MERGE'>, <TokenType.ENUM: 'ENUM'>, <TokenType.OBJECT_IDENTIFIER: 'OBJECT_IDENTIFIER'>, <TokenType.UINT256: 'UINT256'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, <TokenType.FLOAT: 'FLOAT'>, <TokenType.OBJECT: 'OBJECT'>, <TokenType.UNNEST: 'UNNEST'>, <TokenType.RLIKE: 'RLIKE'>, <TokenType.INTERVAL: 'INTERVAL'>, <TokenType.NVARCHAR: 'NVARCHAR'>, <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, <TokenType.VARBINARY: 'VARBINARY'>, <TokenType.ROW: 'ROW'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.INET: 'INET'>, <TokenType.IDENTIFIER: 'IDENTIFIER'>, <TokenType.IPPREFIX: 'IPPREFIX'>, <TokenType.NUMRANGE: 'NUMRANGE'>, <TokenType.UINT128: 'UINT128'>, <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, <TokenType.DATERANGE: 'DATERANGE'>, <TokenType.LONGTEXT: 'LONGTEXT'>, <TokenType.JSON: 'JSON'>, <TokenType.TIMETZ: 'TIMETZ'>, <TokenType.SMALLSERIAL: 'SMALLSERIAL'>, <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>, <TokenType.RIGHT: 'RIGHT'>, <TokenType.NULLABLE: 'NULLABLE'>, <TokenType.INT128: 'INT128'>, <TokenType.BIT: 'BIT'>, <TokenType.INT: 'INT'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.BIGINT: 'BIGINT'>, <TokenType.UTINYINT: 'UTINYINT'>, <TokenType.HSTORE: 'HSTORE'>, <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>, <TokenType.TABLE: 'TABLE'>, <TokenType.NULL: 'NULL'>, <TokenType.SMALLMONEY: 'SMALLMONEY'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.TSRANGE: 'TSRANGE'>, <TokenType.NCHAR: 'NCHAR'>, <TokenType.DATETIME64: 'DATETIME64'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, <TokenType.TIME: 'TIME'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.ROWVERSION: 'ROWVERSION'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, <TokenType.TINYBLOB: 'TINYBLOB'>, <TokenType.XOR: 'XOR'>, <TokenType.ENUM16: 'ENUM16'>, <TokenType.SOME: 'SOME'>, <TokenType.OFFSET: 'OFFSET'>, <TokenType.BOOLEAN: 'BOOLEAN'>, <TokenType.BINARY: 'BINARY'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.HLLSKETCH: 'HLLSKETCH'>, <TokenType.UINT: 'UINT'>, <TokenType.UNKNOWN: 'UNKNOWN'>, <TokenType.UMEDIUMINT: 'UMEDIUMINT'>, <TokenType.INSERT: 'INSERT'>, <TokenType.DECIMAL: 'DECIMAL'>, <TokenType.GEOMETRY: 'GEOMETRY'>, <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, <TokenType.LEFT: 'LEFT'>, <TokenType.ARRAY: 'ARRAY'>, <TokenType.SERIAL: 'SERIAL'>, <TokenType.DATE: 'DATE'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.TINYINT: 'TINYINT'>, <TokenType.INDEX: 'INDEX'>, <TokenType.CHAR: 'CHAR'>, <TokenType.USERDEFINED: 'USERDEFINED'>, <TokenType.UBIGINT: 'UBIGINT'>, <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>, <TokenType.TSTZRANGE: 'TSTZRANGE'>, <TokenType.DATETIME: 'DATETIME'>, <TokenType.NESTED: 'NESTED'>, <TokenType.LONGBLOB: 'LONGBLOB'>, <TokenType.MEDIUMINT: 'MEDIUMINT'>, <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <TokenType.IPADDRESS: 'IPADDRESS'>, <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, <TokenType.BIGSERIAL: 'BIGSERIAL'>}
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.TEXT: 'TEXT'>, <TokenType.TINYTEXT: 'TINYTEXT'>, <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, <TokenType.SMALLINT: 'SMALLINT'>, <TokenType.DEFAULT: 'DEFAULT'>, <TokenType.PROCEDURE: 'PROCEDURE'>, <TokenType.ROWS: 'ROWS'>, <TokenType.UUID: 'UUID'>, <TokenType.ALL: 'ALL'>, <TokenType.INT4RANGE: 'INT4RANGE'>, <TokenType.FIRST: 'FIRST'>, <TokenType.SETTINGS: 'SETTINGS'>, <TokenType.ANY: 'ANY'>, <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <TokenType.BEGIN: 'BEGIN'>, <TokenType.DESC: 'DESC'>, <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.INT8RANGE: 'INT8RANGE'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.VAR: 'VAR'>, <TokenType.VIEW: 'VIEW'>, <TokenType.FALSE: 'FALSE'>, <TokenType.ENUM: 'ENUM'>, <TokenType.PRAGMA: 'PRAGMA'>, <TokenType.KEEP: 'KEEP'>, <TokenType.UINT256: 'UINT256'>, <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, <TokenType.SEMI: 'SEMI'>, <TokenType.IS: 'IS'>, <TokenType.OBJECT: 'OBJECT'>, <TokenType.ASC: 'ASC'>, <TokenType.INTERVAL: 'INTERVAL'>, <TokenType.DELETE: 'DELETE'>, <TokenType.VARBINARY: 'VARBINARY'>, <TokenType.NEXT: 'NEXT'>, <TokenType.IPPREFIX: 'IPPREFIX'>, <TokenType.FUNCTION: 'FUNCTION'>, <TokenType.DATERANGE: 'DATERANGE'>, <TokenType.LONGTEXT: 'LONGTEXT'>, <TokenType.JSON: 'JSON'>, <TokenType.COLUMN: 'COLUMN'>, <TokenType.INT: 'INT'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.BIGINT: 'BIGINT'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>, <TokenType.NULL: 'NULL'>, <TokenType.DATETIME64: 'DATETIME64'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, <TokenType.ANTI: 'ANTI'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, <TokenType.COMMENT: 'COMMENT'>, <TokenType.UNKNOWN: 'UNKNOWN'>, <TokenType.UMEDIUMINT: 'UMEDIUMINT'>, <TokenType.SET: 'SET'>, <TokenType.GEOMETRY: 'GEOMETRY'>, <TokenType.ARRAY: 'ARRAY'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.TINYINT: 'TINYINT'>, <TokenType.CHAR: 'CHAR'>, <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>, <TokenType.DATETIME: 'DATETIME'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.UNIQUE: 'UNIQUE'>, <TokenType.ESCAPE: 'ESCAPE'>, <TokenType.MEDIUMINT: 'MEDIUMINT'>, <TokenType.TEMPORARY: 'TEMPORARY'>, <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, <TokenType.PIVOT: 'PIVOT'>, <TokenType.MAP: 'MAP'>, <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.VARCHAR: 'VARCHAR'>, <TokenType.IMAGE: 'IMAGE'>, <TokenType.TIMESTAMP: 'TIMESTAMP'>, <TokenType.COMMIT: 'COMMIT'>, <TokenType.YEAR: 'YEAR'>, <TokenType.RANGE: 'RANGE'>, <TokenType.DOUBLE: 'DOUBLE'>, <TokenType.VARIANT: 'VARIANT'>, <TokenType.DICTIONARY: 'DICTIONARY'>, <TokenType.STRUCT: 'STRUCT'>, <TokenType.SUPER: 'SUPER'>, <TokenType.INT256: 'INT256'>, <TokenType.JSONB: 'JSONB'>, <TokenType.ENUM8: 'ENUM8'>, <TokenType.FIXEDSTRING: 'FIXEDSTRING'>, <TokenType.XML: 'XML'>, <TokenType.FORMAT: 'FORMAT'>, <TokenType.MONEY: 'MONEY'>, <TokenType.REFERENCES: 'REFERENCES'>, <TokenType.PERCENT: 'PERCENT'>, <TokenType.USMALLINT: 'USMALLINT'>, <TokenType.CACHE: 'CACHE'>, <TokenType.FILTER: 'FILTER'>, <TokenType.MERGE: 'MERGE'>, <TokenType.VOLATILE: 'VOLATILE'>, <TokenType.TOP: 'TOP'>, <TokenType.OBJECT_IDENTIFIER: 'OBJECT_IDENTIFIER'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, <TokenType.FLOAT: 'FLOAT'>, <TokenType.OVERWRITE: 'OVERWRITE'>, <TokenType.NVARCHAR: 'NVARCHAR'>, <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, <TokenType.ROW: 'ROW'>, <TokenType.PARTITION: 'PARTITION'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.LOAD: 'LOAD'>, <TokenType.INET: 'INET'>, <TokenType.NUMRANGE: 'NUMRANGE'>, <TokenType.UINT128: 'UINT128'>, <TokenType.TRUE: 'TRUE'>, <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, <TokenType.TIMETZ: 'TIMETZ'>, <TokenType.DESCRIBE: 'DESCRIBE'>, <TokenType.SMALLSERIAL: 'SMALLSERIAL'>, <TokenType.NULLABLE: 'NULLABLE'>, <TokenType.INT128: 'INT128'>, <TokenType.BIT: 'BIT'>, <TokenType.UTINYINT: 'UTINYINT'>, <TokenType.HSTORE: 'HSTORE'>, <TokenType.TABLE: 'TABLE'>, <TokenType.SMALLMONEY: 'SMALLMONEY'>, <TokenType.TSRANGE: 'TSRANGE'>, <TokenType.NCHAR: 'NCHAR'>, <TokenType.UNPIVOT: 'UNPIVOT'>, <TokenType.TIME: 'TIME'>, <TokenType.DIV: 'DIV'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.ROWVERSION: 'ROWVERSION'>, <TokenType.TINYBLOB: 'TINYBLOB'>, <TokenType.ENUM16: 'ENUM16'>, <TokenType.ORDINALITY: 'ORDINALITY'>, <TokenType.SHOW: 'SHOW'>, <TokenType.END: 'END'>, <TokenType.SOME: 'SOME'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.BOOLEAN: 'BOOLEAN'>, <TokenType.BINARY: 'BINARY'>, <TokenType.HLLSKETCH: 'HLLSKETCH'>, <TokenType.UINT: 'UINT'>, <TokenType.DECIMAL: 'DECIMAL'>, <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, <TokenType.SERIAL: 'SERIAL'>, <TokenType.DATE: 'DATE'>, <TokenType.INDEX: 'INDEX'>, <TokenType.USERDEFINED: 'USERDEFINED'>, <TokenType.UBIGINT: 'UBIGINT'>, <TokenType.TSTZRANGE: 'TSTZRANGE'>, <TokenType.NESTED: 'NESTED'>, <TokenType.CASE: 'CASE'>, <TokenType.LONGBLOB: 'LONGBLOB'>, <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <TokenType.IPADDRESS: 'IPADDRESS'>, <TokenType.CONSTRAINT: 'CONSTRAINT'>, <TokenType.BIGSERIAL: 'BIGSERIAL'>}
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'>>, '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'>>, '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': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Date'>>, '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': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Day'>>, 'DAY_OF_MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfMonth'>>, 'DAYOFMONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfMonth'>>, 'DAY_OF_WEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfWeek'>>, 'DAYOFWEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfWeek'>>, 'DAY_OF_YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfYear'>>, 'DAYOFYEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfYear'>>, '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': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Month'>>, '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'>>, '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_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'>>, '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': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Week'>>, 'WEEK_OF_YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.WeekOfYear'>>, 'WEEKOFYEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.WeekOfYear'>>, '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': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Year'>>, 'GLOB': <function Parser.<lambda>>, 'LIKE': <function parse_like>, 'DATE_FORMAT': <function format_time_lambda.<locals>._format_time>, 'INSTR': <function MySQL.Parser.<lambda>>, 'LOCATE': <function locate_to_strposition>}
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>>, '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.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 = {'CHECK', 'FOREIGN KEY', 'SPATIAL', 'INDEX', 'KEY', 'LIKE', 'FULLTEXT', 'UNIQUE', 'PRIMARY KEY'}
PROFILE_TYPES = {'BLOCK IO', 'ALL', 'MEMORY', 'SOURCE', 'CPU', 'PAGE FAULTS', 'IPC', 'CONTEXT SWITCHES', 'SWAPS'}
TYPE_TOKENS = {<TokenType.MAP: 'MAP'>, <TokenType.TEXT: 'TEXT'>, <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, <TokenType.VARCHAR: 'VARCHAR'>, <TokenType.TINYTEXT: 'TINYTEXT'>, <TokenType.IMAGE: 'IMAGE'>, <TokenType.TIMESTAMP: 'TIMESTAMP'>, <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, <TokenType.SMALLINT: 'SMALLINT'>, <TokenType.YEAR: 'YEAR'>, <TokenType.DOUBLE: 'DOUBLE'>, <TokenType.UUID: 'UUID'>, <TokenType.INT4RANGE: 'INT4RANGE'>, <TokenType.VARIANT: 'VARIANT'>, <TokenType.STRUCT: 'STRUCT'>, <TokenType.SUPER: 'SUPER'>, <TokenType.INT256: 'INT256'>, <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <TokenType.JSONB: 'JSONB'>, <TokenType.ENUM8: 'ENUM8'>, <TokenType.FIXEDSTRING: 'FIXEDSTRING'>, <TokenType.XML: 'XML'>, <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, <TokenType.INT8RANGE: 'INT8RANGE'>, <TokenType.MONEY: 'MONEY'>, <TokenType.USMALLINT: 'USMALLINT'>, <TokenType.ENUM: 'ENUM'>, <TokenType.OBJECT_IDENTIFIER: 'OBJECT_IDENTIFIER'>, <TokenType.UINT256: 'UINT256'>, <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, <TokenType.FLOAT: 'FLOAT'>, <TokenType.OBJECT: 'OBJECT'>, <TokenType.NVARCHAR: 'NVARCHAR'>, <TokenType.INTERVAL: 'INTERVAL'>, <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, <TokenType.VARBINARY: 'VARBINARY'>, <TokenType.INET: 'INET'>, <TokenType.IPPREFIX: 'IPPREFIX'>, <TokenType.NUMRANGE: 'NUMRANGE'>, <TokenType.UINT128: 'UINT128'>, <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, <TokenType.DATERANGE: 'DATERANGE'>, <TokenType.LONGTEXT: 'LONGTEXT'>, <TokenType.JSON: 'JSON'>, <TokenType.TIMETZ: 'TIMETZ'>, <TokenType.SMALLSERIAL: 'SMALLSERIAL'>, <TokenType.NULLABLE: 'NULLABLE'>, <TokenType.INT128: 'INT128'>, <TokenType.BIT: 'BIT'>, <TokenType.INT: 'INT'>, <TokenType.UTINYINT: 'UTINYINT'>, <TokenType.BIGINT: 'BIGINT'>, <TokenType.HSTORE: 'HSTORE'>, <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>, <TokenType.NULL: 'NULL'>, <TokenType.SMALLMONEY: 'SMALLMONEY'>, <TokenType.TSRANGE: 'TSRANGE'>, <TokenType.NCHAR: 'NCHAR'>, <TokenType.DATETIME64: 'DATETIME64'>, <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, <TokenType.TIME: 'TIME'>, <TokenType.ROWVERSION: 'ROWVERSION'>, <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, <TokenType.TINYBLOB: 'TINYBLOB'>, <TokenType.ENUM16: 'ENUM16'>, <TokenType.BOOLEAN: 'BOOLEAN'>, <TokenType.BINARY: 'BINARY'>, <TokenType.HLLSKETCH: 'HLLSKETCH'>, <TokenType.UINT: 'UINT'>, <TokenType.UNKNOWN: 'UNKNOWN'>, <TokenType.UMEDIUMINT: 'UMEDIUMINT'>, <TokenType.SET: 'SET'>, <TokenType.DECIMAL: 'DECIMAL'>, <TokenType.GEOMETRY: 'GEOMETRY'>, <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, <TokenType.ARRAY: 'ARRAY'>, <TokenType.SERIAL: 'SERIAL'>, <TokenType.DATE: 'DATE'>, <TokenType.TINYINT: 'TINYINT'>, <TokenType.CHAR: 'CHAR'>, <TokenType.USERDEFINED: 'USERDEFINED'>, <TokenType.UBIGINT: 'UBIGINT'>, <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>, <TokenType.TSTZRANGE: 'TSTZRANGE'>, <TokenType.DATETIME: 'DATETIME'>, <TokenType.NESTED: 'NESTED'>, <TokenType.LONGBLOB: 'LONGBLOB'>, <TokenType.MEDIUMINT: 'MEDIUMINT'>, <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <TokenType.IPADDRESS: 'IPADDRESS'>, <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, <TokenType.BIGSERIAL: 'BIGSERIAL'>}
ENUM_TYPE_TOKENS = {<TokenType.ENUM16: 'ENUM16'>, <TokenType.ENUM: 'ENUM'>, <TokenType.ENUM8: 'ENUM8'>, <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_KINDS
  TABLE_INDEX_HINT_TOKENS
  WINDOW_ALIAS_TOKENS
  WINDOW_BEFORE_PAREN_TOKENS
  WINDOW_SIDES
  FETCH_TOKENS
  ADD_CONSTRAINT_TOKENS
  DISTINCT_TOKENS
  STRICT_CAST
  CONCAT_NULL_OUTPUTS_STRING
  PREFIXED_PIVOT_COLUMNS
  IDENTIFY_PIVOT_STRINGS
  LOG_BASE_FIRST
  ALTER_TABLE_ADD_COLUMN_KEYWORD
  TABLESAMPLE_CSV
  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

    527    class Generator(generator.Generator):
    528        LOCKING_READS_SUPPORTED = True
    529        NULL_ORDERING_SUPPORTED = False
    530        JOIN_HINTS = False
    531        TABLE_HINTS = True
    532        DUPLICATE_KEY_UPDATE_WITH_SET = False
    533        QUERY_HINT_SEP = " "
    534        VALUES_AS_TABLE = False
    535        NVL2_SUPPORTED = False
    536
    537        TRANSFORMS = {
    538            **generator.Generator.TRANSFORMS,
    539            exp.CurrentDate: no_paren_current_date_sql,
    540            exp.DateDiff: lambda self, e: self.func("DATEDIFF", e.this, e.expression),
    541            exp.DateAdd: _date_add_sql("ADD"),
    542            exp.DateStrToDate: datestrtodate_sql,
    543            exp.DateSub: _date_add_sql("SUB"),
    544            exp.DateTrunc: _date_trunc_sql,
    545            exp.DayOfMonth: rename_func("DAYOFMONTH"),
    546            exp.DayOfWeek: rename_func("DAYOFWEEK"),
    547            exp.DayOfYear: rename_func("DAYOFYEAR"),
    548            exp.GroupConcat: lambda self, e: f"""GROUP_CONCAT({self.sql(e, "this")} SEPARATOR {self.sql(e, "separator") or "','"})""",
    549            exp.ILike: no_ilike_sql,
    550            exp.JSONExtractScalar: arrow_json_extract_scalar_sql,
    551            exp.JSONKeyValue: json_keyvalue_comma_sql,
    552            exp.Max: max_or_greatest,
    553            exp.Min: min_or_least,
    554            exp.NullSafeEQ: lambda self, e: self.binary(e, "<=>"),
    555            exp.NullSafeNEQ: lambda self, e: self.not_sql(self.binary(e, "<=>")),
    556            exp.Pivot: no_pivot_sql,
    557            exp.Select: transforms.preprocess([transforms.eliminate_distinct_on]),
    558            exp.StrPosition: strposition_to_locate_sql,
    559            exp.StrToDate: _str_to_date_sql,
    560            exp.StrToTime: _str_to_date_sql,
    561            exp.Stuff: rename_func("INSERT"),
    562            exp.TableSample: no_tablesample_sql,
    563            exp.TimeStrToUnix: rename_func("UNIX_TIMESTAMP"),
    564            exp.TimeStrToTime: lambda self, e: self.sql(exp.cast(e.this, "datetime", copy=True)),
    565            exp.TimeToStr: lambda self, e: self.func("DATE_FORMAT", e.this, self.format_time(e)),
    566            exp.Trim: _trim_sql,
    567            exp.TryCast: no_trycast_sql,
    568            exp.WeekOfYear: rename_func("WEEKOFYEAR"),
    569        }
    570
    571        UNSIGNED_TYPE_MAPPING = {
    572            exp.DataType.Type.UBIGINT: "BIGINT",
    573            exp.DataType.Type.UINT: "INT",
    574            exp.DataType.Type.UMEDIUMINT: "MEDIUMINT",
    575            exp.DataType.Type.USMALLINT: "SMALLINT",
    576            exp.DataType.Type.UTINYINT: "TINYINT",
    577        }
    578
    579        TIMESTAMP_TYPE_MAPPING = {
    580            exp.DataType.Type.TIMESTAMP: "DATETIME",
    581            exp.DataType.Type.TIMESTAMPTZ: "TIMESTAMP",
    582            exp.DataType.Type.TIMESTAMPLTZ: "TIMESTAMP",
    583        }
    584
    585        TYPE_MAPPING = {
    586            **generator.Generator.TYPE_MAPPING,
    587            **UNSIGNED_TYPE_MAPPING,
    588            **TIMESTAMP_TYPE_MAPPING,
    589        }
    590
    591        TYPE_MAPPING.pop(exp.DataType.Type.MEDIUMTEXT)
    592        TYPE_MAPPING.pop(exp.DataType.Type.LONGTEXT)
    593        TYPE_MAPPING.pop(exp.DataType.Type.TINYTEXT)
    594        TYPE_MAPPING.pop(exp.DataType.Type.MEDIUMBLOB)
    595        TYPE_MAPPING.pop(exp.DataType.Type.LONGBLOB)
    596        TYPE_MAPPING.pop(exp.DataType.Type.TINYBLOB)
    597
    598        PROPERTIES_LOCATION = {
    599            **generator.Generator.PROPERTIES_LOCATION,
    600            exp.TransientProperty: exp.Properties.Location.UNSUPPORTED,
    601            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    602        }
    603
    604        LIMIT_FETCH = "LIMIT"
    605
    606        # MySQL doesn't support many datatypes in cast.
    607        # https://dev.mysql.com/doc/refman/8.0/en/cast-functions.html#function_cast
    608        CAST_MAPPING = {
    609            exp.DataType.Type.BIGINT: "SIGNED",
    610            exp.DataType.Type.BOOLEAN: "SIGNED",
    611            exp.DataType.Type.INT: "SIGNED",
    612            exp.DataType.Type.TEXT: "CHAR",
    613            exp.DataType.Type.UBIGINT: "UNSIGNED",
    614            exp.DataType.Type.VARCHAR: "CHAR",
    615        }
    616
    617        TIMESTAMP_FUNC_TYPES = {
    618            exp.DataType.Type.TIMESTAMPTZ,
    619            exp.DataType.Type.TIMESTAMPLTZ,
    620        }
    621
    622        def datatype_sql(self, expression: exp.DataType) -> str:
    623            # https://dev.mysql.com/doc/refman/8.0/en/numeric-type-syntax.html
    624            result = super().datatype_sql(expression)
    625            if expression.this in self.UNSIGNED_TYPE_MAPPING:
    626                result = f"{result} UNSIGNED"
    627            return result
    628
    629        def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    630            # MySQL requires simple literal values for its LIMIT clause.
    631            expression = simplify_literal(expression.copy())
    632            return super().limit_sql(expression, top=top)
    633
    634        def offset_sql(self, expression: exp.Offset) -> str:
    635            # MySQL requires simple literal values for its OFFSET clause.
    636            expression = simplify_literal(expression.copy())
    637            return super().offset_sql(expression)
    638
    639        def xor_sql(self, expression: exp.Xor) -> str:
    640            if expression.expressions:
    641                return self.expressions(expression, sep=" XOR ")
    642            return super().xor_sql(expression)
    643
    644        def jsonarraycontains_sql(self, expression: exp.JSONArrayContains) -> str:
    645            return f"{self.sql(expression, 'this')} MEMBER OF({self.sql(expression, 'expression')})"
    646
    647        def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    648            if expression.to.this in self.TIMESTAMP_FUNC_TYPES:
    649                return self.func("TIMESTAMP", expression.this)
    650
    651            to = self.CAST_MAPPING.get(expression.to.this)
    652
    653            if to:
    654                expression = expression.copy()
    655                expression.to.set("this", to)
    656            return super().cast_sql(expression)
    657
    658        def show_sql(self, expression: exp.Show) -> str:
    659            this = f" {expression.name}"
    660            full = " FULL" if expression.args.get("full") else ""
    661            global_ = " GLOBAL" if expression.args.get("global") else ""
    662
    663            target = self.sql(expression, "target")
    664            target = f" {target}" if target else ""
    665            if expression.name in {"COLUMNS", "INDEX"}:
    666                target = f" FROM{target}"
    667            elif expression.name == "GRANTS":
    668                target = f" FOR{target}"
    669
    670            db = self._prefixed_sql("FROM", expression, "db")
    671
    672            like = self._prefixed_sql("LIKE", expression, "like")
    673            where = self.sql(expression, "where")
    674
    675            types = self.expressions(expression, key="types")
    676            types = f" {types}" if types else types
    677            query = self._prefixed_sql("FOR QUERY", expression, "query")
    678
    679            if expression.name == "PROFILE":
    680                offset = self._prefixed_sql("OFFSET", expression, "offset")
    681                limit = self._prefixed_sql("LIMIT", expression, "limit")
    682            else:
    683                offset = ""
    684                limit = self._oldstyle_limit_sql(expression)
    685
    686            log = self._prefixed_sql("IN", expression, "log")
    687            position = self._prefixed_sql("FROM", expression, "position")
    688
    689            channel = self._prefixed_sql("FOR CHANNEL", expression, "channel")
    690
    691            if expression.name == "ENGINE":
    692                mutex_or_status = " MUTEX" if expression.args.get("mutex") else " STATUS"
    693            else:
    694                mutex_or_status = ""
    695
    696            return f"SHOW{full}{global_}{this}{target}{types}{db}{query}{log}{position}{channel}{mutex_or_status}{like}{where}{offset}{limit}"
    697
    698        def _prefixed_sql(self, prefix: str, expression: exp.Expression, arg: str) -> str:
    699            sql = self.sql(expression, arg)
    700            return f" {prefix} {sql}" if sql else ""
    701
    702        def _oldstyle_limit_sql(self, expression: exp.Show) -> str:
    703            limit = self.sql(expression, "limit")
    704            offset = self.sql(expression, "offset")
    705            if limit:
    706                limit_offset = f"{offset}, {limit}" if offset else limit
    707                return f" LIMIT {limit_offset}"
    708            return ""

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 _date_add_sql.<locals>.func>, <class 'sqlglot.expressions.TsOrDsAdd'>: <function Generator.<lambda>>, <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.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 MySQL.Generator.<lambda>>, <class 'sqlglot.expressions.DateStrToDate'>: <function datestrtodate_sql>, <class 'sqlglot.expressions.DateSub'>: <function _date_add_sql.<locals>.func>, <class 'sqlglot.expressions.DateTrunc'>: <function _date_trunc_sql>, <class 'sqlglot.expressions.DayOfMonth'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.DayOfWeek'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.DayOfYear'>: <function rename_func.<locals>.<lambda>>, <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.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.TimeStrToUnix'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.TimeStrToTime'>: <function MySQL.Generator.<lambda>>, <class 'sqlglot.expressions.TimeToStr'>: <function MySQL.Generator.<lambda>>, <class 'sqlglot.expressions.Trim'>: <function _trim_sql>, <class 'sqlglot.expressions.TryCast'>: <function no_trycast_sql>, <class 'sqlglot.expressions.WeekOfYear'>: <function rename_func.<locals>.<lambda>>}
UNSIGNED_TYPE_MAPPING = {<Type.UBIGINT: 'UBIGINT'>: 'BIGINT', <Type.UINT: 'UINT'>: 'INT', <Type.UMEDIUMINT: 'UMEDIUMINT'>: 'MEDIUMINT', <Type.USMALLINT: 'USMALLINT'>: 'SMALLINT', <Type.UTINYINT: 'UTINYINT'>: 'TINYINT'}
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.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.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.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>}
def datatype_sql(self, expression: sqlglot.expressions.DataType) -> str: View Source

    622        def datatype_sql(self, expression: exp.DataType) -> str:
    623            # https://dev.mysql.com/doc/refman/8.0/en/numeric-type-syntax.html
    624            result = super().datatype_sql(expression)
    625            if expression.this in self.UNSIGNED_TYPE_MAPPING:
    626                result = f"{result} UNSIGNED"
    627            return result

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

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

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

    634        def offset_sql(self, expression: exp.Offset) -> str:
    635            # MySQL requires simple literal values for its OFFSET clause.
    636            expression = simplify_literal(expression.copy())
    637            return super().offset_sql(expression)

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

    639        def xor_sql(self, expression: exp.Xor) -> str:
    640            if expression.expressions:
    641                return self.expressions(expression, sep=" XOR ")
    642            return super().xor_sql(expression)

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

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

    647        def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    648            if expression.to.this in self.TIMESTAMP_FUNC_TYPES:
    649                return self.func("TIMESTAMP", expression.this)
    650
    651            to = self.CAST_MAPPING.get(expression.to.this)
    652
    653            if to:
    654                expression = expression.copy()
    655                expression.to.set("this", to)
    656            return super().cast_sql(expression)

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

    658        def show_sql(self, expression: exp.Show) -> str:
    659            this = f" {expression.name}"
    660            full = " FULL" if expression.args.get("full") else ""
    661            global_ = " GLOBAL" if expression.args.get("global") else ""
    662
    663            target = self.sql(expression, "target")
    664            target = f" {target}" if target else ""
    665            if expression.name in {"COLUMNS", "INDEX"}:
    666                target = f" FROM{target}"
    667            elif expression.name == "GRANTS":
    668                target = f" FOR{target}"
    669
    670            db = self._prefixed_sql("FROM", expression, "db")
    671
    672            like = self._prefixed_sql("LIKE", expression, "like")
    673            where = self.sql(expression, "where")
    674
    675            types = self.expressions(expression, key="types")
    676            types = f" {types}" if types else types
    677            query = self._prefixed_sql("FOR QUERY", expression, "query")
    678
    679            if expression.name == "PROFILE":
    680                offset = self._prefixed_sql("OFFSET", expression, "offset")
    681                limit = self._prefixed_sql("LIMIT", expression, "limit")
    682            else:
    683                offset = ""
    684                limit = self._oldstyle_limit_sql(expression)
    685
    686            log = self._prefixed_sql("IN", expression, "log")
    687            position = self._prefixed_sql("FROM", expression, "position")
    688
    689            channel = self._prefixed_sql("FOR CHANNEL", expression, "channel")
    690
    691            if expression.name == "ENGINE":
    692                mutex_or_status = " MUTEX" if expression.args.get("mutex") else " STATUS"
    693            else:
    694                mutex_or_status = ""
    695
    696            return f"SHOW{full}{global_}{this}{target}{types}{db}{query}{log}{position}{channel}{mutex_or_status}{like}{where}{offset}{limit}"

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}}}
IDENTIFIERS_CAN_START_WITH_DIGIT = True
@classmethod
def can_identify(text: str, identify: str | bool = 'safe') -> bool: View Source

    260    @classmethod
    261    def can_identify(cls, text: str, identify: str | bool = "safe") -> bool:
    262        """Checks if text can be identified given an identify option.
    263
    264        Args:
    265            text: The text to check.
    266            identify:
    267                "always" or `True`: Always returns true.
    268                "safe": True if the identifier is case-insensitive.
    269
    270        Returns:
    271            Whether or not the given text can be identified.
    272        """
    273        if identify is True or identify == "always":
    274            return True
    275
    276        if identify == "safe":
    277            return not cls.case_sensitive(text)
    278
    279        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
  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
  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
  ESCAPE_LINE_BREAK
  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_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
  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
  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