sqlglot.dialects.mysql API documentation

Edit on GitHub

# sqlglot.dialects.mysql

View Source

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

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

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

TIME_FORMAT = "'%Y-%m-%d %T'"
TIME_MAPPING: Dict[str, str] = {'%M': '%B', '%c': '%-m', '%e': '%-d', '%h': '%I', '%i': '%M', '%s': '%S', '%S': '%S', '%u': '%W', '%k': '%-H', '%l': '%-I', '%T': '%H:%M:%S', '%W': '%a'}
tokenizer_class = <class 'sqlglot.dialects.mysql.MySQL.Tokenizer'>
parser_class = <class 'sqlglot.dialects.mysql.MySQL.Parser'>
generator_class = <class 'sqlglot.dialects.mysql.MySQL.Generator'>
TIME_TRIE: Dict = {'%': {'M': {0: True}, 'c': {0: True}, 'e': {0: True}, 'h': {0: True}, 'i': {0: True}, 's': {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}, '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
  IDENTIFIERS_CAN_START_WITH_DIGIT
  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

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

##### Inherited Members

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

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

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

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.USMALLINT: 'USMALLINT'>, <TokenType.INT4RANGE: 'INT4RANGE'>, <TokenType.VARCHAR: 'VARCHAR'>, <TokenType.IPADDRESS: 'IPADDRESS'>, <TokenType.INDEX: 'INDEX'>, <TokenType.BOOLEAN: 'BOOLEAN'>, <TokenType.INT128: 'INT128'>, <TokenType.USERDEFINED: 'USERDEFINED'>, <TokenType.JSONB: 'JSONB'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.JSON: 'JSON'>, <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, <TokenType.LIKE: 'LIKE'>, <TokenType.ALL: 'ALL'>, <TokenType.BINARY: 'BINARY'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.ROW: 'ROW'>, <TokenType.INT8RANGE: 'INT8RANGE'>, <TokenType.TSRANGE: 'TSRANGE'>, <TokenType.XML: 'XML'>, <TokenType.UNNEST: 'UNNEST'>, <TokenType.LEFT: 'LEFT'>, <TokenType.SERIAL: 'SERIAL'>, <TokenType.UUID: 'UUID'>, <TokenType.BIGSERIAL: 'BIGSERIAL'>, <TokenType.NVARCHAR: 'NVARCHAR'>, <TokenType.OBJECT: 'OBJECT'>, <TokenType.TIME: 'TIME'>, <TokenType.VARBINARY: 'VARBINARY'>, <TokenType.MAP: 'MAP'>, <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, <TokenType.OFFSET: 'OFFSET'>, <TokenType.DATERANGE: 'DATERANGE'>, <TokenType.DECIMAL: 'DECIMAL'>, <TokenType.XOR: 'XOR'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.CHAR: 'CHAR'>, <TokenType.FORMAT: 'FORMAT'>, <TokenType.RANGE: 'RANGE'>, <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, <TokenType.STRUCT: 'STRUCT'>, <TokenType.SMALLMONEY: 'SMALLMONEY'>, <TokenType.NCHAR: 'NCHAR'>, <TokenType.REPLACE: 'REPLACE'>, <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, <TokenType.INTERVAL: 'INTERVAL'>, <TokenType.SUPER: 'SUPER'>, <TokenType.SMALLSERIAL: 'SMALLSERIAL'>, <TokenType.MONEY: 'MONEY'>, <TokenType.HLLSKETCH: 'HLLSKETCH'>, <TokenType.ANY: 'ANY'>, <TokenType.FILTER: 'FILTER'>, <TokenType.RIGHT: 'RIGHT'>, <TokenType.INET: 'INET'>, <TokenType.ENUM: 'ENUM'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.RLIKE: 'RLIKE'>, <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <TokenType.LONGBLOB: 'LONGBLOB'>, <TokenType.WINDOW: 'WINDOW'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.BIT: 'BIT'>, <TokenType.NUMRANGE: 'NUMRANGE'>, <TokenType.NULLABLE: 'NULLABLE'>, <TokenType.INT: 'INT'>, <TokenType.TIMESTAMP: 'TIMESTAMP'>, <TokenType.TINYINT: 'TINYINT'>, <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, <TokenType.ILIKE: 'ILIKE'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.GLOB: 'GLOB'>, <TokenType.DATETIME64: 'DATETIME64'>, <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, <TokenType.FIRST: 'FIRST'>, <TokenType.IMAGE: 'IMAGE'>, <TokenType.UINT256: 'UINT256'>, <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, <TokenType.IPPREFIX: 'IPPREFIX'>, <TokenType.SOME: 'SOME'>, <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, <TokenType.VAR: 'VAR'>, <TokenType.TABLE: 'TABLE'>, <TokenType.UINT: 'UINT'>, <TokenType.SMALLINT: 'SMALLINT'>, <TokenType.INT256: 'INT256'>, <TokenType.HSTORE: 'HSTORE'>, <TokenType.VARIANT: 'VARIANT'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.GEOMETRY: 'GEOMETRY'>, <TokenType.VALUES: 'VALUES'>, <TokenType.FLOAT: 'FLOAT'>, <TokenType.TSTZRANGE: 'TSTZRANGE'>, <TokenType.ROWVERSION: 'ROWVERSION'>, <TokenType.TEXT: 'TEXT'>, <TokenType.UINT128: 'UINT128'>, <TokenType.ARRAY: 'ARRAY'>, <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>, <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, <TokenType.DOUBLE: 'DOUBLE'>, <TokenType.LONGTEXT: 'LONGTEXT'>, <TokenType.MERGE: 'MERGE'>, <TokenType.IDENTIFIER: 'IDENTIFIER'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.UTINYINT: 'UTINYINT'>, <TokenType.DATE: 'DATE'>, <TokenType.DATETIME: 'DATETIME'>, <TokenType.UBIGINT: 'UBIGINT'>, <TokenType.BIGINT: 'BIGINT'>, <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>, <TokenType.ISNULL: 'ISNULL'>}
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'>}
TABLE_ALIAS_TOKENS = {<TokenType.VARCHAR: 'VARCHAR'>, <TokenType.INT128: 'INT128'>, <TokenType.TEMPORARY: 'TEMPORARY'>, <TokenType.JSON: 'JSON'>, <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.ROW: 'ROW'>, <TokenType.INT8RANGE: 'INT8RANGE'>, <TokenType.CONSTRAINT: 'CONSTRAINT'>, <TokenType.TSRANGE: 'TSRANGE'>, <TokenType.COMMENT: 'COMMENT'>, <TokenType.TRUE: 'TRUE'>, <TokenType.XML: 'XML'>, <TokenType.SHOW: 'SHOW'>, <TokenType.UUID: 'UUID'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.BIGSERIAL: 'BIGSERIAL'>, <TokenType.NVARCHAR: 'NVARCHAR'>, <TokenType.OBJECT: 'OBJECT'>, <TokenType.TIME: 'TIME'>, <TokenType.DATERANGE: 'DATERANGE'>, <TokenType.DECIMAL: 'DECIMAL'>, <TokenType.FORMAT: 'FORMAT'>, <TokenType.RANGE: 'RANGE'>, <TokenType.KEEP: 'KEEP'>, <TokenType.NCHAR: 'NCHAR'>, <TokenType.INTERVAL: 'INTERVAL'>, <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, <TokenType.SMALLSERIAL: 'SMALLSERIAL'>, <TokenType.HLLSKETCH: 'HLLSKETCH'>, <TokenType.FILTER: 'FILTER'>, <TokenType.ENUM: 'ENUM'>, <TokenType.DESC: 'DESC'>, <TokenType.VIEW: 'VIEW'>, <TokenType.DICTIONARY: 'DICTIONARY'>, <TokenType.CACHE: 'CACHE'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.ORDINALITY: 'ORDINALITY'>, <TokenType.DATETIME64: 'DATETIME64'>, <TokenType.PROCEDURE: 'PROCEDURE'>, <TokenType.IMAGE: 'IMAGE'>, <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, <TokenType.FIRST: 'FIRST'>, <TokenType.OVERWRITE: 'OVERWRITE'>, <TokenType.TOP: 'TOP'>, <TokenType.UINT256: 'UINT256'>, <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, <TokenType.IPPREFIX: 'IPPREFIX'>, <TokenType.TABLE: 'TABLE'>, <TokenType.INT256: 'INT256'>, <TokenType.HSTORE: 'HSTORE'>, <TokenType.FLOAT: 'FLOAT'>, <TokenType.PERCENT: 'PERCENT'>, <TokenType.TEXT: 'TEXT'>, <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, <TokenType.DELETE: 'DELETE'>, <TokenType.LONGTEXT: 'LONGTEXT'>, <TokenType.CASE: 'CASE'>, <TokenType.MERGE: 'MERGE'>, <TokenType.ASC: 'ASC'>, <TokenType.SEMI: 'SEMI'>, <TokenType.UTINYINT: 'UTINYINT'>, <TokenType.DATE: 'DATE'>, <TokenType.DATETIME: 'DATETIME'>, <TokenType.MONEY: 'MONEY'>, <TokenType.DIV: 'DIV'>, <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.USMALLINT: 'USMALLINT'>, <TokenType.INT4RANGE: 'INT4RANGE'>, <TokenType.IPADDRESS: 'IPADDRESS'>, <TokenType.INDEX: 'INDEX'>, <TokenType.BOOLEAN: 'BOOLEAN'>, <TokenType.USERDEFINED: 'USERDEFINED'>, <TokenType.JSONB: 'JSONB'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.DESCRIBE: 'DESCRIBE'>, <TokenType.COMMIT: 'COMMIT'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.ALL: 'ALL'>, <TokenType.BINARY: 'BINARY'>, <TokenType.PIVOT: 'PIVOT'>, <TokenType.ESCAPE: 'ESCAPE'>, <TokenType.END: 'END'>, <TokenType.COLUMN: 'COLUMN'>, <TokenType.ROWS: 'ROWS'>, <TokenType.PRAGMA: 'PRAGMA'>, <TokenType.SERIAL: 'SERIAL'>, <TokenType.ANTI: 'ANTI'>, <TokenType.VARBINARY: 'VARBINARY'>, <TokenType.IF: 'IF'>, <TokenType.MAP: 'MAP'>, <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.CHAR: 'CHAR'>, <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, <TokenType.STRUCT: 'STRUCT'>, <TokenType.SMALLMONEY: 'SMALLMONEY'>, <TokenType.SUPER: 'SUPER'>, <TokenType.VOLATILE: 'VOLATILE'>, <TokenType.PARTITION: 'PARTITION'>, <TokenType.FALSE: 'FALSE'>, <TokenType.ANY: 'ANY'>, <TokenType.INET: 'INET'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.DEFAULT: 'DEFAULT'>, <TokenType.UNPIVOT: 'UNPIVOT'>, <TokenType.REFERENCES: 'REFERENCES'>, <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <TokenType.LONGBLOB: 'LONGBLOB'>, <TokenType.BIT: 'BIT'>, <TokenType.NUMRANGE: 'NUMRANGE'>, <TokenType.NULLABLE: 'NULLABLE'>, <TokenType.INT: 'INT'>, <TokenType.TINYINT: 'TINYINT'>, <TokenType.TIMESTAMP: 'TIMESTAMP'>, <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, <TokenType.SET: 'SET'>, <TokenType.FUNCTION: 'FUNCTION'>, <TokenType.SOME: 'SOME'>, <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, <TokenType.VAR: 'VAR'>, <TokenType.UINT: 'UINT'>, <TokenType.SMALLINT: 'SMALLINT'>, <TokenType.VARIANT: 'VARIANT'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.GEOMETRY: 'GEOMETRY'>, <TokenType.TSTZRANGE: 'TSTZRANGE'>, <TokenType.ROWVERSION: 'ROWVERSION'>, <TokenType.UINT128: 'UINT128'>, <TokenType.LOAD: 'LOAD'>, <TokenType.ARRAY: 'ARRAY'>, <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, <TokenType.SETTINGS: 'SETTINGS'>, <TokenType.DOUBLE: 'DOUBLE'>, <TokenType.IS: 'IS'>, <TokenType.UNIQUE: 'UNIQUE'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.BEGIN: 'BEGIN'>, <TokenType.NEXT: 'NEXT'>, <TokenType.UBIGINT: 'UBIGINT'>, <TokenType.BIGINT: 'BIGINT'>}
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.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_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'>>, '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'>>, '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'>>, '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_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'>>, '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>>, '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.FROM: 'FROM'>: <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>>, '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>>, 'FULLTEXT': <function MySQL.Parser.<lambda>>, 'INDEX': <function MySQL.Parser.<lambda>>, 'KEY': <function MySQL.Parser.<lambda>>, 'SPATIAL': <function MySQL.Parser.<lambda>>}
SCHEMA_UNNAMED_CONSTRAINTS = {'CHECK', 'INDEX', 'LIKE', 'SPATIAL', 'KEY', 'UNIQUE', 'FULLTEXT', 'PRIMARY KEY', 'FOREIGN KEY'}
PROFILE_TYPES = {'SWAPS', 'CONTEXT SWITCHES', 'MEMORY', 'IPC', 'BLOCK IO', 'ALL', 'CPU', 'SOURCE', 'PAGE FAULTS'}
TYPE_TOKENS = {<TokenType.USMALLINT: 'USMALLINT'>, <TokenType.INT4RANGE: 'INT4RANGE'>, <TokenType.VARCHAR: 'VARCHAR'>, <TokenType.IPADDRESS: 'IPADDRESS'>, <TokenType.BOOLEAN: 'BOOLEAN'>, <TokenType.INT128: 'INT128'>, <TokenType.USERDEFINED: 'USERDEFINED'>, <TokenType.JSONB: 'JSONB'>, <TokenType.JSON: 'JSON'>, <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, <TokenType.BINARY: 'BINARY'>, <TokenType.INT8RANGE: 'INT8RANGE'>, <TokenType.TSRANGE: 'TSRANGE'>, <TokenType.XML: 'XML'>, <TokenType.SERIAL: 'SERIAL'>, <TokenType.UUID: 'UUID'>, <TokenType.BIGSERIAL: 'BIGSERIAL'>, <TokenType.NVARCHAR: 'NVARCHAR'>, <TokenType.OBJECT: 'OBJECT'>, <TokenType.TIME: 'TIME'>, <TokenType.VARBINARY: 'VARBINARY'>, <TokenType.MAP: 'MAP'>, <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, <TokenType.DATERANGE: 'DATERANGE'>, <TokenType.DECIMAL: 'DECIMAL'>, <TokenType.CHAR: 'CHAR'>, <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, <TokenType.STRUCT: 'STRUCT'>, <TokenType.SMALLMONEY: 'SMALLMONEY'>, <TokenType.NCHAR: 'NCHAR'>, <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, <TokenType.INTERVAL: 'INTERVAL'>, <TokenType.SUPER: 'SUPER'>, <TokenType.SMALLSERIAL: 'SMALLSERIAL'>, <TokenType.DATETIME: 'DATETIME'>, <TokenType.HLLSKETCH: 'HLLSKETCH'>, <TokenType.INET: 'INET'>, <TokenType.ENUM: 'ENUM'>, <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <TokenType.LONGBLOB: 'LONGBLOB'>, <TokenType.BIT: 'BIT'>, <TokenType.NUMRANGE: 'NUMRANGE'>, <TokenType.NULLABLE: 'NULLABLE'>, <TokenType.INT: 'INT'>, <TokenType.TINYINT: 'TINYINT'>, <TokenType.TIMESTAMP: 'TIMESTAMP'>, <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, <TokenType.DATETIME64: 'DATETIME64'>, <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, <TokenType.IMAGE: 'IMAGE'>, <TokenType.UINT256: 'UINT256'>, <TokenType.SET: 'SET'>, <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, <TokenType.IPPREFIX: 'IPPREFIX'>, <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, <TokenType.UINT: 'UINT'>, <TokenType.SMALLINT: 'SMALLINT'>, <TokenType.INT256: 'INT256'>, <TokenType.HSTORE: 'HSTORE'>, <TokenType.VARIANT: 'VARIANT'>, <TokenType.GEOMETRY: 'GEOMETRY'>, <TokenType.FLOAT: 'FLOAT'>, <TokenType.TSTZRANGE: 'TSTZRANGE'>, <TokenType.ROWVERSION: 'ROWVERSION'>, <TokenType.TEXT: 'TEXT'>, <TokenType.UINT128: 'UINT128'>, <TokenType.ARRAY: 'ARRAY'>, <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, <TokenType.DOUBLE: 'DOUBLE'>, <TokenType.LONGTEXT: 'LONGTEXT'>, <TokenType.UTINYINT: 'UTINYINT'>, <TokenType.DATE: 'DATE'>, <TokenType.MONEY: 'MONEY'>, <TokenType.UBIGINT: 'UBIGINT'>, <TokenType.BIGINT: 'BIGINT'>, <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>}
ENUM_TYPE_TOKENS = {<TokenType.ENUM: 'ENUM'>, <TokenType.SET: 'SET'>}
LOG_DEFAULTS_TO_LN = True
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}, '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', '%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}, '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
  NESTED_TYPE_TOKENS
  SUBQUERY_PREDICATES
  RESERVED_KEYWORDS
  DB_CREATABLES
  CREATABLES
  ID_VAR_TOKENS
  INTERVAL_VARS
  COMMENT_TABLE_ALIAS_TOKENS
  UPDATE_ALIAS_TOKENS
  TRIM_TYPES
  EQUALITY
  COMPARISON
  BITWISE
  TERM
  FACTOR
  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
  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
  ADD_CONSTRAINT_TOKENS
  STRICT_CAST
  CONCAT_NULL_OUTPUTS_STRING
  PREFIXED_PIVOT_COLUMNS
  IDENTIFY_PIVOT_STRINGS
  LOG_BASE_FIRST
  INDEX_OFFSET
  UNNEST_COLUMN_ONLY
  ALIAS_POST_TABLESAMPLE
  STRICT_STRING_CONCAT
  NORMALIZE_FUNCTIONS
  NULL_ORDERING
  FORMAT_MAPPING
  error_level
  error_message_context
  max_errors
  reset
  parse
  parse_into
  check_errors
  raise_error
  expression
  validate_expression
  errors
  sql

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

    490    class Generator(generator.Generator):
    491        LOCKING_READS_SUPPORTED = True
    492        NULL_ORDERING_SUPPORTED = False
    493        JOIN_HINTS = False
    494        TABLE_HINTS = True
    495        DUPLICATE_KEY_UPDATE_WITH_SET = False
    496        QUERY_HINT_SEP = " "
    497        VALUES_AS_TABLE = False
    498
    499        TRANSFORMS = {
    500            **generator.Generator.TRANSFORMS,
    501            exp.CurrentDate: no_paren_current_date_sql,
    502            exp.DateDiff: lambda self, e: self.func("DATEDIFF", e.this, e.expression),
    503            exp.DateAdd: _date_add_sql("ADD"),
    504            exp.DateStrToDate: datestrtodate_sql,
    505            exp.DateSub: _date_add_sql("SUB"),
    506            exp.DateTrunc: _date_trunc_sql,
    507            exp.DayOfMonth: rename_func("DAYOFMONTH"),
    508            exp.DayOfWeek: rename_func("DAYOFWEEK"),
    509            exp.DayOfYear: rename_func("DAYOFYEAR"),
    510            exp.GroupConcat: lambda self, e: f"""GROUP_CONCAT({self.sql(e, "this")} SEPARATOR {self.sql(e, "separator") or "','"})""",
    511            exp.ILike: no_ilike_sql,
    512            exp.JSONExtractScalar: arrow_json_extract_scalar_sql,
    513            exp.Max: max_or_greatest,
    514            exp.Min: min_or_least,
    515            exp.NullSafeEQ: lambda self, e: self.binary(e, "<=>"),
    516            exp.NullSafeNEQ: lambda self, e: self.not_sql(self.binary(e, "<=>")),
    517            exp.Pivot: no_pivot_sql,
    518            exp.Select: transforms.preprocess([transforms.eliminate_distinct_on]),
    519            exp.StrPosition: strposition_to_locate_sql,
    520            exp.StrToDate: _str_to_date_sql,
    521            exp.StrToTime: _str_to_date_sql,
    522            exp.TableSample: no_tablesample_sql,
    523            exp.TimeStrToUnix: rename_func("UNIX_TIMESTAMP"),
    524            exp.TimeStrToTime: lambda self, e: self.sql(exp.cast(e.this, "datetime", copy=True)),
    525            exp.TimeToStr: lambda self, e: self.func("DATE_FORMAT", e.this, self.format_time(e)),
    526            exp.Trim: _trim_sql,
    527            exp.TryCast: no_trycast_sql,
    528            exp.WeekOfYear: rename_func("WEEKOFYEAR"),
    529        }
    530
    531        TYPE_MAPPING = generator.Generator.TYPE_MAPPING.copy()
    532        TYPE_MAPPING.pop(exp.DataType.Type.MEDIUMTEXT)
    533        TYPE_MAPPING.pop(exp.DataType.Type.LONGTEXT)
    534        TYPE_MAPPING.pop(exp.DataType.Type.MEDIUMBLOB)
    535        TYPE_MAPPING.pop(exp.DataType.Type.LONGBLOB)
    536
    537        PROPERTIES_LOCATION = {
    538            **generator.Generator.PROPERTIES_LOCATION,
    539            exp.TransientProperty: exp.Properties.Location.UNSUPPORTED,
    540            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    541        }
    542
    543        LIMIT_FETCH = "LIMIT"
    544
    545        # MySQL doesn't support many datatypes in cast.
    546        # https://dev.mysql.com/doc/refman/8.0/en/cast-functions.html#function_cast
    547        CAST_MAPPING = {
    548            exp.DataType.Type.BIGINT: "SIGNED",
    549            exp.DataType.Type.BOOLEAN: "SIGNED",
    550            exp.DataType.Type.INT: "SIGNED",
    551            exp.DataType.Type.TEXT: "CHAR",
    552            exp.DataType.Type.UBIGINT: "UNSIGNED",
    553            exp.DataType.Type.VARCHAR: "CHAR",
    554        }
    555
    556        def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    557            # MySQL requires simple literal values for its LIMIT clause.
    558            expression = simplify_literal(expression.copy())
    559            return super().limit_sql(expression, top=top)
    560
    561        def offset_sql(self, expression: exp.Offset) -> str:
    562            # MySQL requires simple literal values for its OFFSET clause.
    563            expression = simplify_literal(expression.copy())
    564            return super().offset_sql(expression)
    565
    566        def xor_sql(self, expression: exp.Xor) -> str:
    567            if expression.expressions:
    568                return self.expressions(expression, sep=" XOR ")
    569            return super().xor_sql(expression)
    570
    571        def jsonarraycontains_sql(self, expression: exp.JSONArrayContains) -> str:
    572            return f"{self.sql(expression, 'this')} MEMBER OF({self.sql(expression, 'expression')})"
    573
    574        def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    575            to = self.CAST_MAPPING.get(expression.to.this)
    576
    577            if to:
    578                expression = expression.copy()
    579                expression.to.set("this", to)
    580            return super().cast_sql(expression)
    581
    582        def show_sql(self, expression: exp.Show) -> str:
    583            this = f" {expression.name}"
    584            full = " FULL" if expression.args.get("full") else ""
    585            global_ = " GLOBAL" if expression.args.get("global") else ""
    586
    587            target = self.sql(expression, "target")
    588            target = f" {target}" if target else ""
    589            if expression.name in {"COLUMNS", "INDEX"}:
    590                target = f" FROM{target}"
    591            elif expression.name == "GRANTS":
    592                target = f" FOR{target}"
    593
    594            db = self._prefixed_sql("FROM", expression, "db")
    595
    596            like = self._prefixed_sql("LIKE", expression, "like")
    597            where = self.sql(expression, "where")
    598
    599            types = self.expressions(expression, key="types")
    600            types = f" {types}" if types else types
    601            query = self._prefixed_sql("FOR QUERY", expression, "query")
    602
    603            if expression.name == "PROFILE":
    604                offset = self._prefixed_sql("OFFSET", expression, "offset")
    605                limit = self._prefixed_sql("LIMIT", expression, "limit")
    606            else:
    607                offset = ""
    608                limit = self._oldstyle_limit_sql(expression)
    609
    610            log = self._prefixed_sql("IN", expression, "log")
    611            position = self._prefixed_sql("FROM", expression, "position")
    612
    613            channel = self._prefixed_sql("FOR CHANNEL", expression, "channel")
    614
    615            if expression.name == "ENGINE":
    616                mutex_or_status = " MUTEX" if expression.args.get("mutex") else " STATUS"
    617            else:
    618                mutex_or_status = ""
    619
    620            return f"SHOW{full}{global_}{this}{target}{types}{db}{query}{log}{position}{channel}{mutex_or_status}{like}{where}{offset}{limit}"
    621
    622        def _prefixed_sql(self, prefix: str, expression: exp.Expression, arg: str) -> str:
    623            sql = self.sql(expression, arg)
    624            return f" {prefix} {sql}" if sql else ""
    625
    626        def _oldstyle_limit_sql(self, expression: exp.Show) -> str:
    627            limit = self.sql(expression, "limit")
    628            offset = self.sql(expression, "offset")
    629            if limit:
    630                limit_offset = f"{offset}, {limit}" if offset else limit
    631                return f" LIMIT {limit_offset}"
    632            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
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.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.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.OnCommitProperty'>: <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.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.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>>}
TYPE_MAPPING = {<Type.NCHAR: 'NCHAR'>: 'CHAR', <Type.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <Type.INET: 'INET'>: 'INET'}
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.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'}
def limit_sql(self, expression: sqlglot.expressions.Limit, top: bool = False) -> str: View Source

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

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

    561        def offset_sql(self, expression: exp.Offset) -> str:
    562            # MySQL requires simple literal values for its OFFSET clause.
    563            expression = simplify_literal(expression.copy())
    564            return super().offset_sql(expression)

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

    566        def xor_sql(self, expression: exp.Xor) -> str:
    567            if expression.expressions:
    568                return self.expressions(expression, sep=" XOR ")
    569            return super().xor_sql(expression)

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

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

    574        def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    575            to = self.CAST_MAPPING.get(expression.to.this)
    576
    577            if to:
    578                expression = expression.copy()
    579                expression.to.set("this", to)
    580            return super().cast_sql(expression)

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

    582        def show_sql(self, expression: exp.Show) -> str:
    583            this = f" {expression.name}"
    584            full = " FULL" if expression.args.get("full") else ""
    585            global_ = " GLOBAL" if expression.args.get("global") else ""
    586
    587            target = self.sql(expression, "target")
    588            target = f" {target}" if target else ""
    589            if expression.name in {"COLUMNS", "INDEX"}:
    590                target = f" FROM{target}"
    591            elif expression.name == "GRANTS":
    592                target = f" FOR{target}"
    593
    594            db = self._prefixed_sql("FROM", expression, "db")
    595
    596            like = self._prefixed_sql("LIKE", expression, "like")
    597            where = self.sql(expression, "where")
    598
    599            types = self.expressions(expression, key="types")
    600            types = f" {types}" if types else types
    601            query = self._prefixed_sql("FOR QUERY", expression, "query")
    602
    603            if expression.name == "PROFILE":
    604                offset = self._prefixed_sql("OFFSET", expression, "offset")
    605                limit = self._prefixed_sql("LIMIT", expression, "limit")
    606            else:
    607                offset = ""
    608                limit = self._oldstyle_limit_sql(expression)
    609
    610            log = self._prefixed_sql("IN", expression, "log")
    611            position = self._prefixed_sql("FROM", expression, "position")
    612
    613            channel = self._prefixed_sql("FOR CHANNEL", expression, "channel")
    614
    615            if expression.name == "ENGINE":
    616                mutex_or_status = " MUTEX" if expression.args.get("mutex") else " STATUS"
    617            else:
    618                mutex_or_status = ""
    619
    620            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}}}
@classmethod
def can_identify(text: str, identify: str | bool = 'safe') -> bool: View Source

    253    @classmethod
    254    def can_identify(cls, text: str, identify: str | bool = "safe") -> bool:
    255        """Checks if text can be identified given an identify option.
    256
    257        Args:
    258            text: The text to check.
    259            identify:
    260                "always" or `True`: Always returns true.
    261                "safe": True if the identifier is case-insensitive.
    262
    263        Returns:
    264            Whether or not the given text can be identified.
    265        """
    266        if identify is True or identify == "always":
    267            return True
    268
    269        if identify == "safe":
    270            return not cls.case_sensitive(text)
    271
    272        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 = '`'
STRING_ESCAPE = "'"
IDENTIFIER_ESCAPE = '"'
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
  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
  IDENTIFIERS_CAN_START_WITH_DIGIT
  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
  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
  datatypesize_sql
  datatype_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
  onconflict_sql
  returning_sql
  rowformatdelimitedproperty_sql
  withtablehint_sql
  indextablehint_sql
  table_sql
  tablesample_sql
  pivot_sql
  tuple_sql
  update_sql
  values_sql
  var_sql
  into_sql
  from_sql
  group_sql
  having_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
  jsonobject_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