sqlglot.dialects.mysql API documentation

Edit on GitHub

# sqlglot.dialects.mysql

View Source

      1from __future__ import annotations
      2
      3from sqlglot import exp, generator, parser, tokens
      4from sqlglot.dialects.dialect import (
      5    Dialect,
      6    locate_to_strposition,
      7    min_or_least,
      8    no_ilike_sql,
      9    no_paren_current_date_sql,
     10    no_tablesample_sql,
     11    no_trycast_sql,
     12    rename_func,
     13    strposition_to_locate_sql,
     14)
     15from sqlglot.helper import seq_get
     16from sqlglot.tokens import TokenType
     17
     18
     19def _show_parser(*args, **kwargs):
     20    def _parse(self):
     21        return self._parse_show_mysql(*args, **kwargs)
     22
     23    return _parse
     24
     25
     26def _date_trunc_sql(self, expression):
     27    expr = self.sql(expression, "this")
     28    unit = expression.text("unit")
     29
     30    if unit == "day":
     31        return f"DATE({expr})"
     32
     33    if unit == "week":
     34        concat = f"CONCAT(YEAR({expr}), ' ', WEEK({expr}, 1), ' 1')"
     35        date_format = "%Y %u %w"
     36    elif unit == "month":
     37        concat = f"CONCAT(YEAR({expr}), ' ', MONTH({expr}), ' 1')"
     38        date_format = "%Y %c %e"
     39    elif unit == "quarter":
     40        concat = f"CONCAT(YEAR({expr}), ' ', QUARTER({expr}) * 3 - 2, ' 1')"
     41        date_format = "%Y %c %e"
     42    elif unit == "year":
     43        concat = f"CONCAT(YEAR({expr}), ' 1 1')"
     44        date_format = "%Y %c %e"
     45    else:
     46        self.unsupported(f"Unexpected interval unit: {unit}")
     47        return f"DATE({expr})"
     48
     49    return f"STR_TO_DATE({concat}, '{date_format}')"
     50
     51
     52def _str_to_date(args):
     53    date_format = MySQL.format_time(seq_get(args, 1))
     54    return exp.StrToDate(this=seq_get(args, 0), format=date_format)
     55
     56
     57def _str_to_date_sql(self, expression):
     58    date_format = self.format_time(expression)
     59    return f"STR_TO_DATE({self.sql(expression.this)}, {date_format})"
     60
     61
     62def _trim_sql(self, expression):
     63    target = self.sql(expression, "this")
     64    trim_type = self.sql(expression, "position")
     65    remove_chars = self.sql(expression, "expression")
     66
     67    # Use TRIM/LTRIM/RTRIM syntax if the expression isn't mysql-specific
     68    if not remove_chars:
     69        return self.trim_sql(expression)
     70
     71    trim_type = f"{trim_type} " if trim_type else ""
     72    remove_chars = f"{remove_chars} " if remove_chars else ""
     73    from_part = "FROM " if trim_type or remove_chars else ""
     74    return f"TRIM({trim_type}{remove_chars}{from_part}{target})"
     75
     76
     77def _date_add(expression_class):
     78    def func(args):
     79        interval = seq_get(args, 1)
     80        return expression_class(
     81            this=seq_get(args, 0),
     82            expression=interval.this,
     83            unit=exp.Literal.string(interval.text("unit").lower()),
     84        )
     85
     86    return func
     87
     88
     89def _date_add_sql(kind):
     90    def func(self, expression):
     91        this = self.sql(expression, "this")
     92        unit = expression.text("unit").upper() or "DAY"
     93        return (
     94            f"DATE_{kind}({this}, {self.sql(exp.Interval(this=expression.expression, unit=unit))})"
     95        )
     96
     97    return func
     98
     99
    100class MySQL(Dialect):
    101    time_format = "'%Y-%m-%d %T'"
    102
    103    # https://prestodb.io/docs/current/functions/datetime.html#mysql-date-functions
    104    time_mapping = {
    105        "%M": "%B",
    106        "%c": "%-m",
    107        "%e": "%-d",
    108        "%h": "%I",
    109        "%i": "%M",
    110        "%s": "%S",
    111        "%S": "%S",
    112        "%u": "%W",
    113        "%k": "%-H",
    114        "%l": "%-I",
    115        "%T": "%H:%M:%S",
    116    }
    117
    118    class Tokenizer(tokens.Tokenizer):
    119        QUOTES = ["'", '"']
    120        COMMENTS = ["--", "#", ("/*", "*/")]
    121        IDENTIFIERS = ["`"]
    122        STRING_ESCAPES = ["'", "\\"]
    123        BIT_STRINGS = [("b'", "'"), ("B'", "'"), ("0b", "")]
    124        HEX_STRINGS = [("x'", "'"), ("X'", "'"), ("0x", "")]
    125
    126        KEYWORDS = {
    127            **tokens.Tokenizer.KEYWORDS,
    128            "MEDIUMTEXT": TokenType.MEDIUMTEXT,
    129            "LONGTEXT": TokenType.LONGTEXT,
    130            "MEDIUMBLOB": TokenType.MEDIUMBLOB,
    131            "LONGBLOB": TokenType.LONGBLOB,
    132            "START": TokenType.BEGIN,
    133            "SEPARATOR": TokenType.SEPARATOR,
    134            "_ARMSCII8": TokenType.INTRODUCER,
    135            "_ASCII": TokenType.INTRODUCER,
    136            "_BIG5": TokenType.INTRODUCER,
    137            "_BINARY": TokenType.INTRODUCER,
    138            "_CP1250": TokenType.INTRODUCER,
    139            "_CP1251": TokenType.INTRODUCER,
    140            "_CP1256": TokenType.INTRODUCER,
    141            "_CP1257": TokenType.INTRODUCER,
    142            "_CP850": TokenType.INTRODUCER,
    143            "_CP852": TokenType.INTRODUCER,
    144            "_CP866": TokenType.INTRODUCER,
    145            "_CP932": TokenType.INTRODUCER,
    146            "_DEC8": TokenType.INTRODUCER,
    147            "_EUCJPMS": TokenType.INTRODUCER,
    148            "_EUCKR": TokenType.INTRODUCER,
    149            "_GB18030": TokenType.INTRODUCER,
    150            "_GB2312": TokenType.INTRODUCER,
    151            "_GBK": TokenType.INTRODUCER,
    152            "_GEOSTD8": TokenType.INTRODUCER,
    153            "_GREEK": TokenType.INTRODUCER,
    154            "_HEBREW": TokenType.INTRODUCER,
    155            "_HP8": TokenType.INTRODUCER,
    156            "_KEYBCS2": TokenType.INTRODUCER,
    157            "_KOI8R": TokenType.INTRODUCER,
    158            "_KOI8U": TokenType.INTRODUCER,
    159            "_LATIN1": TokenType.INTRODUCER,
    160            "_LATIN2": TokenType.INTRODUCER,
    161            "_LATIN5": TokenType.INTRODUCER,
    162            "_LATIN7": TokenType.INTRODUCER,
    163            "_MACCE": TokenType.INTRODUCER,
    164            "_MACROMAN": TokenType.INTRODUCER,
    165            "_SJIS": TokenType.INTRODUCER,
    166            "_SWE7": TokenType.INTRODUCER,
    167            "_TIS620": TokenType.INTRODUCER,
    168            "_UCS2": TokenType.INTRODUCER,
    169            "_UJIS": TokenType.INTRODUCER,
    170            # https://dev.mysql.com/doc/refman/8.0/en/string-literals.html
    171            "_UTF8": TokenType.INTRODUCER,
    172            "_UTF16": TokenType.INTRODUCER,
    173            "_UTF16LE": TokenType.INTRODUCER,
    174            "_UTF32": TokenType.INTRODUCER,
    175            "_UTF8MB3": TokenType.INTRODUCER,
    176            "_UTF8MB4": TokenType.INTRODUCER,
    177            "@@": TokenType.SESSION_PARAMETER,
    178        }
    179
    180        COMMANDS = tokens.Tokenizer.COMMANDS - {TokenType.SHOW}
    181
    182    class Parser(parser.Parser):
    183        FUNC_TOKENS = {*parser.Parser.FUNC_TOKENS, TokenType.SCHEMA, TokenType.DATABASE}  # type: ignore
    184
    185        FUNCTIONS = {
    186            **parser.Parser.FUNCTIONS,  # type: ignore
    187            "DATE_ADD": _date_add(exp.DateAdd),
    188            "DATE_SUB": _date_add(exp.DateSub),
    189            "STR_TO_DATE": _str_to_date,
    190            "LOCATE": locate_to_strposition,
    191            "INSTR": lambda args: exp.StrPosition(substr=seq_get(args, 1), this=seq_get(args, 0)),
    192            "LEFT": lambda args: exp.Substring(
    193                this=seq_get(args, 0), start=exp.Literal.number(1), length=seq_get(args, 1)
    194            ),
    195        }
    196
    197        FUNCTION_PARSERS = {
    198            **parser.Parser.FUNCTION_PARSERS,  # type: ignore
    199            "GROUP_CONCAT": lambda self: self.expression(
    200                exp.GroupConcat,
    201                this=self._parse_lambda(),
    202                separator=self._match(TokenType.SEPARATOR) and self._parse_field(),
    203            ),
    204        }
    205
    206        PROPERTY_PARSERS = {
    207            **parser.Parser.PROPERTY_PARSERS,  # type: ignore
    208            "ENGINE": lambda self: self._parse_property_assignment(exp.EngineProperty),
    209        }
    210
    211        STATEMENT_PARSERS = {
    212            **parser.Parser.STATEMENT_PARSERS,  # type: ignore
    213            TokenType.SHOW: lambda self: self._parse_show(),
    214        }
    215
    216        SHOW_PARSERS = {
    217            "BINARY LOGS": _show_parser("BINARY LOGS"),
    218            "MASTER LOGS": _show_parser("BINARY LOGS"),
    219            "BINLOG EVENTS": _show_parser("BINLOG EVENTS"),
    220            "CHARACTER SET": _show_parser("CHARACTER SET"),
    221            "CHARSET": _show_parser("CHARACTER SET"),
    222            "COLLATION": _show_parser("COLLATION"),
    223            "FULL COLUMNS": _show_parser("COLUMNS", target="FROM", full=True),
    224            "COLUMNS": _show_parser("COLUMNS", target="FROM"),
    225            "CREATE DATABASE": _show_parser("CREATE DATABASE", target=True),
    226            "CREATE EVENT": _show_parser("CREATE EVENT", target=True),
    227            "CREATE FUNCTION": _show_parser("CREATE FUNCTION", target=True),
    228            "CREATE PROCEDURE": _show_parser("CREATE PROCEDURE", target=True),
    229            "CREATE TABLE": _show_parser("CREATE TABLE", target=True),
    230            "CREATE TRIGGER": _show_parser("CREATE TRIGGER", target=True),
    231            "CREATE VIEW": _show_parser("CREATE VIEW", target=True),
    232            "DATABASES": _show_parser("DATABASES"),
    233            "ENGINE": _show_parser("ENGINE", target=True),
    234            "STORAGE ENGINES": _show_parser("ENGINES"),
    235            "ENGINES": _show_parser("ENGINES"),
    236            "ERRORS": _show_parser("ERRORS"),
    237            "EVENTS": _show_parser("EVENTS"),
    238            "FUNCTION CODE": _show_parser("FUNCTION CODE", target=True),
    239            "FUNCTION STATUS": _show_parser("FUNCTION STATUS"),
    240            "GRANTS": _show_parser("GRANTS", target="FOR"),
    241            "INDEX": _show_parser("INDEX", target="FROM"),
    242            "MASTER STATUS": _show_parser("MASTER STATUS"),
    243            "OPEN TABLES": _show_parser("OPEN TABLES"),
    244            "PLUGINS": _show_parser("PLUGINS"),
    245            "PROCEDURE CODE": _show_parser("PROCEDURE CODE", target=True),
    246            "PROCEDURE STATUS": _show_parser("PROCEDURE STATUS"),
    247            "PRIVILEGES": _show_parser("PRIVILEGES"),
    248            "FULL PROCESSLIST": _show_parser("PROCESSLIST", full=True),
    249            "PROCESSLIST": _show_parser("PROCESSLIST"),
    250            "PROFILE": _show_parser("PROFILE"),
    251            "PROFILES": _show_parser("PROFILES"),
    252            "RELAYLOG EVENTS": _show_parser("RELAYLOG EVENTS"),
    253            "REPLICAS": _show_parser("REPLICAS"),
    254            "SLAVE HOSTS": _show_parser("REPLICAS"),
    255            "REPLICA STATUS": _show_parser("REPLICA STATUS"),
    256            "SLAVE STATUS": _show_parser("REPLICA STATUS"),
    257            "GLOBAL STATUS": _show_parser("STATUS", global_=True),
    258            "SESSION STATUS": _show_parser("STATUS"),
    259            "STATUS": _show_parser("STATUS"),
    260            "TABLE STATUS": _show_parser("TABLE STATUS"),
    261            "FULL TABLES": _show_parser("TABLES", full=True),
    262            "TABLES": _show_parser("TABLES"),
    263            "TRIGGERS": _show_parser("TRIGGERS"),
    264            "GLOBAL VARIABLES": _show_parser("VARIABLES", global_=True),
    265            "SESSION VARIABLES": _show_parser("VARIABLES"),
    266            "VARIABLES": _show_parser("VARIABLES"),
    267            "WARNINGS": _show_parser("WARNINGS"),
    268        }
    269
    270        SET_PARSERS = {
    271            **parser.Parser.SET_PARSERS,
    272            "PERSIST": lambda self: self._parse_set_item_assignment("PERSIST"),
    273            "PERSIST_ONLY": lambda self: self._parse_set_item_assignment("PERSIST_ONLY"),
    274            "CHARACTER SET": lambda self: self._parse_set_item_charset("CHARACTER SET"),
    275            "CHARSET": lambda self: self._parse_set_item_charset("CHARACTER SET"),
    276            "NAMES": lambda self: self._parse_set_item_names(),
    277        }
    278
    279        PROFILE_TYPES = {
    280            "ALL",
    281            "BLOCK IO",
    282            "CONTEXT SWITCHES",
    283            "CPU",
    284            "IPC",
    285            "MEMORY",
    286            "PAGE FAULTS",
    287            "SOURCE",
    288            "SWAPS",
    289        }
    290
    291        def _parse_show_mysql(self, this, target=False, full=None, global_=None):
    292            if target:
    293                if isinstance(target, str):
    294                    self._match_text_seq(target)
    295                target_id = self._parse_id_var()
    296            else:
    297                target_id = None
    298
    299            log = self._parse_string() if self._match_text_seq("IN") else None
    300
    301            if this in {"BINLOG EVENTS", "RELAYLOG EVENTS"}:
    302                position = self._parse_number() if self._match_text_seq("FROM") else None
    303                db = None
    304            else:
    305                position = None
    306                db = self._parse_id_var() if self._match_text_seq("FROM") else None
    307
    308            channel = self._parse_id_var() if self._match_text_seq("FOR", "CHANNEL") else None
    309
    310            like = self._parse_string() if self._match_text_seq("LIKE") else None
    311            where = self._parse_where()
    312
    313            if this == "PROFILE":
    314                types = self._parse_csv(lambda: self._parse_var_from_options(self.PROFILE_TYPES))
    315                query = self._parse_number() if self._match_text_seq("FOR", "QUERY") else None
    316                offset = self._parse_number() if self._match_text_seq("OFFSET") else None
    317                limit = self._parse_number() if self._match_text_seq("LIMIT") else None
    318            else:
    319                types, query = None, None
    320                offset, limit = self._parse_oldstyle_limit()
    321
    322            mutex = True if self._match_text_seq("MUTEX") else None
    323            mutex = False if self._match_text_seq("STATUS") else mutex
    324
    325            return self.expression(
    326                exp.Show,
    327                this=this,
    328                target=target_id,
    329                full=full,
    330                log=log,
    331                position=position,
    332                db=db,
    333                channel=channel,
    334                like=like,
    335                where=where,
    336                types=types,
    337                query=query,
    338                offset=offset,
    339                limit=limit,
    340                mutex=mutex,
    341                **{"global": global_},
    342            )
    343
    344        def _parse_oldstyle_limit(self):
    345            limit = None
    346            offset = None
    347            if self._match_text_seq("LIMIT"):
    348                parts = self._parse_csv(self._parse_number)
    349                if len(parts) == 1:
    350                    limit = parts[0]
    351                elif len(parts) == 2:
    352                    limit = parts[1]
    353                    offset = parts[0]
    354            return offset, limit
    355
    356        def _parse_set_item_charset(self, kind):
    357            this = self._parse_string() or self._parse_id_var()
    358
    359            return self.expression(
    360                exp.SetItem,
    361                this=this,
    362                kind=kind,
    363            )
    364
    365        def _parse_set_item_names(self):
    366            charset = self._parse_string() or self._parse_id_var()
    367            if self._match_text_seq("COLLATE"):
    368                collate = self._parse_string() or self._parse_id_var()
    369            else:
    370                collate = None
    371            return self.expression(
    372                exp.SetItem,
    373                this=charset,
    374                collate=collate,
    375                kind="NAMES",
    376            )
    377
    378    class Generator(generator.Generator):
    379        LOCKING_READS_SUPPORTED = True
    380        NULL_ORDERING_SUPPORTED = False
    381
    382        TRANSFORMS = {
    383            **generator.Generator.TRANSFORMS,  # type: ignore
    384            exp.CurrentDate: no_paren_current_date_sql,
    385            exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP",
    386            exp.ILike: no_ilike_sql,
    387            exp.Min: min_or_least,
    388            exp.TableSample: no_tablesample_sql,
    389            exp.TryCast: no_trycast_sql,
    390            exp.DateAdd: _date_add_sql("ADD"),
    391            exp.DateDiff: lambda self, e: f"DATEDIFF({self.format_args(e.this, e.expression)})",
    392            exp.DateSub: _date_add_sql("SUB"),
    393            exp.DateTrunc: _date_trunc_sql,
    394            exp.DayOfWeek: rename_func("DAYOFWEEK"),
    395            exp.DayOfMonth: rename_func("DAYOFMONTH"),
    396            exp.DayOfYear: rename_func("DAYOFYEAR"),
    397            exp.WeekOfYear: rename_func("WEEKOFYEAR"),
    398            exp.GroupConcat: lambda self, e: f"""GROUP_CONCAT({self.sql(e, "this")} SEPARATOR {self.sql(e, "separator") or "','"})""",
    399            exp.StrToDate: _str_to_date_sql,
    400            exp.StrToTime: _str_to_date_sql,
    401            exp.Trim: _trim_sql,
    402            exp.NullSafeEQ: lambda self, e: self.binary(e, "<=>"),
    403            exp.NullSafeNEQ: lambda self, e: self.not_sql(self.binary(e, "<=>")),
    404            exp.StrPosition: strposition_to_locate_sql,
    405        }
    406
    407        TYPE_MAPPING = generator.Generator.TYPE_MAPPING.copy()
    408        TYPE_MAPPING.pop(exp.DataType.Type.MEDIUMTEXT)
    409        TYPE_MAPPING.pop(exp.DataType.Type.LONGTEXT)
    410        TYPE_MAPPING.pop(exp.DataType.Type.MEDIUMBLOB)
    411        TYPE_MAPPING.pop(exp.DataType.Type.LONGBLOB)
    412
    413        PROPERTIES_LOCATION = {
    414            **generator.Generator.PROPERTIES_LOCATION,  # type: ignore
    415            exp.TransientProperty: exp.Properties.Location.UNSUPPORTED,
    416        }
    417
    418        def show_sql(self, expression):
    419            this = f" {expression.name}"
    420            full = " FULL" if expression.args.get("full") else ""
    421            global_ = " GLOBAL" if expression.args.get("global") else ""
    422
    423            target = self.sql(expression, "target")
    424            target = f" {target}" if target else ""
    425            if expression.name in {"COLUMNS", "INDEX"}:
    426                target = f" FROM{target}"
    427            elif expression.name == "GRANTS":
    428                target = f" FOR{target}"
    429
    430            db = self._prefixed_sql("FROM", expression, "db")
    431
    432            like = self._prefixed_sql("LIKE", expression, "like")
    433            where = self.sql(expression, "where")
    434
    435            types = self.expressions(expression, key="types")
    436            types = f" {types}" if types else types
    437            query = self._prefixed_sql("FOR QUERY", expression, "query")
    438
    439            if expression.name == "PROFILE":
    440                offset = self._prefixed_sql("OFFSET", expression, "offset")
    441                limit = self._prefixed_sql("LIMIT", expression, "limit")
    442            else:
    443                offset = ""
    444                limit = self._oldstyle_limit_sql(expression)
    445
    446            log = self._prefixed_sql("IN", expression, "log")
    447            position = self._prefixed_sql("FROM", expression, "position")
    448
    449            channel = self._prefixed_sql("FOR CHANNEL", expression, "channel")
    450
    451            if expression.name == "ENGINE":
    452                mutex_or_status = " MUTEX" if expression.args.get("mutex") else " STATUS"
    453            else:
    454                mutex_or_status = ""
    455
    456            return f"SHOW{full}{global_}{this}{target}{types}{db}{query}{log}{position}{channel}{mutex_or_status}{like}{where}{offset}{limit}"
    457
    458        def _prefixed_sql(self, prefix, expression, arg):
    459            sql = self.sql(expression, arg)
    460            if not sql:
    461                return ""
    462            return f" {prefix} {sql}"
    463
    464        def _oldstyle_limit_sql(self, expression):
    465            limit = self.sql(expression, "limit")
    466            offset = self.sql(expression, "offset")
    467            if limit:
    468                limit_offset = f"{offset}, {limit}" if offset else limit
    469                return f" LIMIT {limit_offset}"
    470            return ""

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

    101class MySQL(Dialect):
    102    time_format = "'%Y-%m-%d %T'"
    103
    104    # https://prestodb.io/docs/current/functions/datetime.html#mysql-date-functions
    105    time_mapping = {
    106        "%M": "%B",
    107        "%c": "%-m",
    108        "%e": "%-d",
    109        "%h": "%I",
    110        "%i": "%M",
    111        "%s": "%S",
    112        "%S": "%S",
    113        "%u": "%W",
    114        "%k": "%-H",
    115        "%l": "%-I",
    116        "%T": "%H:%M:%S",
    117    }
    118
    119    class Tokenizer(tokens.Tokenizer):
    120        QUOTES = ["'", '"']
    121        COMMENTS = ["--", "#", ("/*", "*/")]
    122        IDENTIFIERS = ["`"]
    123        STRING_ESCAPES = ["'", "\\"]
    124        BIT_STRINGS = [("b'", "'"), ("B'", "'"), ("0b", "")]
    125        HEX_STRINGS = [("x'", "'"), ("X'", "'"), ("0x", "")]
    126
    127        KEYWORDS = {
    128            **tokens.Tokenizer.KEYWORDS,
    129            "MEDIUMTEXT": TokenType.MEDIUMTEXT,
    130            "LONGTEXT": TokenType.LONGTEXT,
    131            "MEDIUMBLOB": TokenType.MEDIUMBLOB,
    132            "LONGBLOB": TokenType.LONGBLOB,
    133            "START": TokenType.BEGIN,
    134            "SEPARATOR": TokenType.SEPARATOR,
    135            "_ARMSCII8": TokenType.INTRODUCER,
    136            "_ASCII": TokenType.INTRODUCER,
    137            "_BIG5": TokenType.INTRODUCER,
    138            "_BINARY": TokenType.INTRODUCER,
    139            "_CP1250": TokenType.INTRODUCER,
    140            "_CP1251": TokenType.INTRODUCER,
    141            "_CP1256": TokenType.INTRODUCER,
    142            "_CP1257": TokenType.INTRODUCER,
    143            "_CP850": TokenType.INTRODUCER,
    144            "_CP852": TokenType.INTRODUCER,
    145            "_CP866": TokenType.INTRODUCER,
    146            "_CP932": TokenType.INTRODUCER,
    147            "_DEC8": TokenType.INTRODUCER,
    148            "_EUCJPMS": TokenType.INTRODUCER,
    149            "_EUCKR": TokenType.INTRODUCER,
    150            "_GB18030": TokenType.INTRODUCER,
    151            "_GB2312": TokenType.INTRODUCER,
    152            "_GBK": TokenType.INTRODUCER,
    153            "_GEOSTD8": TokenType.INTRODUCER,
    154            "_GREEK": TokenType.INTRODUCER,
    155            "_HEBREW": TokenType.INTRODUCER,
    156            "_HP8": TokenType.INTRODUCER,
    157            "_KEYBCS2": TokenType.INTRODUCER,
    158            "_KOI8R": TokenType.INTRODUCER,
    159            "_KOI8U": TokenType.INTRODUCER,
    160            "_LATIN1": TokenType.INTRODUCER,
    161            "_LATIN2": TokenType.INTRODUCER,
    162            "_LATIN5": TokenType.INTRODUCER,
    163            "_LATIN7": TokenType.INTRODUCER,
    164            "_MACCE": TokenType.INTRODUCER,
    165            "_MACROMAN": TokenType.INTRODUCER,
    166            "_SJIS": TokenType.INTRODUCER,
    167            "_SWE7": TokenType.INTRODUCER,
    168            "_TIS620": TokenType.INTRODUCER,
    169            "_UCS2": TokenType.INTRODUCER,
    170            "_UJIS": TokenType.INTRODUCER,
    171            # https://dev.mysql.com/doc/refman/8.0/en/string-literals.html
    172            "_UTF8": TokenType.INTRODUCER,
    173            "_UTF16": TokenType.INTRODUCER,
    174            "_UTF16LE": TokenType.INTRODUCER,
    175            "_UTF32": TokenType.INTRODUCER,
    176            "_UTF8MB3": TokenType.INTRODUCER,
    177            "_UTF8MB4": TokenType.INTRODUCER,
    178            "@@": TokenType.SESSION_PARAMETER,
    179        }
    180
    181        COMMANDS = tokens.Tokenizer.COMMANDS - {TokenType.SHOW}
    182
    183    class Parser(parser.Parser):
    184        FUNC_TOKENS = {*parser.Parser.FUNC_TOKENS, TokenType.SCHEMA, TokenType.DATABASE}  # type: ignore
    185
    186        FUNCTIONS = {
    187            **parser.Parser.FUNCTIONS,  # type: ignore
    188            "DATE_ADD": _date_add(exp.DateAdd),
    189            "DATE_SUB": _date_add(exp.DateSub),
    190            "STR_TO_DATE": _str_to_date,
    191            "LOCATE": locate_to_strposition,
    192            "INSTR": lambda args: exp.StrPosition(substr=seq_get(args, 1), this=seq_get(args, 0)),
    193            "LEFT": lambda args: exp.Substring(
    194                this=seq_get(args, 0), start=exp.Literal.number(1), length=seq_get(args, 1)
    195            ),
    196        }
    197
    198        FUNCTION_PARSERS = {
    199            **parser.Parser.FUNCTION_PARSERS,  # type: ignore
    200            "GROUP_CONCAT": lambda self: self.expression(
    201                exp.GroupConcat,
    202                this=self._parse_lambda(),
    203                separator=self._match(TokenType.SEPARATOR) and self._parse_field(),
    204            ),
    205        }
    206
    207        PROPERTY_PARSERS = {
    208            **parser.Parser.PROPERTY_PARSERS,  # type: ignore
    209            "ENGINE": lambda self: self._parse_property_assignment(exp.EngineProperty),
    210        }
    211
    212        STATEMENT_PARSERS = {
    213            **parser.Parser.STATEMENT_PARSERS,  # type: ignore
    214            TokenType.SHOW: lambda self: self._parse_show(),
    215        }
    216
    217        SHOW_PARSERS = {
    218            "BINARY LOGS": _show_parser("BINARY LOGS"),
    219            "MASTER LOGS": _show_parser("BINARY LOGS"),
    220            "BINLOG EVENTS": _show_parser("BINLOG EVENTS"),
    221            "CHARACTER SET": _show_parser("CHARACTER SET"),
    222            "CHARSET": _show_parser("CHARACTER SET"),
    223            "COLLATION": _show_parser("COLLATION"),
    224            "FULL COLUMNS": _show_parser("COLUMNS", target="FROM", full=True),
    225            "COLUMNS": _show_parser("COLUMNS", target="FROM"),
    226            "CREATE DATABASE": _show_parser("CREATE DATABASE", target=True),
    227            "CREATE EVENT": _show_parser("CREATE EVENT", target=True),
    228            "CREATE FUNCTION": _show_parser("CREATE FUNCTION", target=True),
    229            "CREATE PROCEDURE": _show_parser("CREATE PROCEDURE", target=True),
    230            "CREATE TABLE": _show_parser("CREATE TABLE", target=True),
    231            "CREATE TRIGGER": _show_parser("CREATE TRIGGER", target=True),
    232            "CREATE VIEW": _show_parser("CREATE VIEW", target=True),
    233            "DATABASES": _show_parser("DATABASES"),
    234            "ENGINE": _show_parser("ENGINE", target=True),
    235            "STORAGE ENGINES": _show_parser("ENGINES"),
    236            "ENGINES": _show_parser("ENGINES"),
    237            "ERRORS": _show_parser("ERRORS"),
    238            "EVENTS": _show_parser("EVENTS"),
    239            "FUNCTION CODE": _show_parser("FUNCTION CODE", target=True),
    240            "FUNCTION STATUS": _show_parser("FUNCTION STATUS"),
    241            "GRANTS": _show_parser("GRANTS", target="FOR"),
    242            "INDEX": _show_parser("INDEX", target="FROM"),
    243            "MASTER STATUS": _show_parser("MASTER STATUS"),
    244            "OPEN TABLES": _show_parser("OPEN TABLES"),
    245            "PLUGINS": _show_parser("PLUGINS"),
    246            "PROCEDURE CODE": _show_parser("PROCEDURE CODE", target=True),
    247            "PROCEDURE STATUS": _show_parser("PROCEDURE STATUS"),
    248            "PRIVILEGES": _show_parser("PRIVILEGES"),
    249            "FULL PROCESSLIST": _show_parser("PROCESSLIST", full=True),
    250            "PROCESSLIST": _show_parser("PROCESSLIST"),
    251            "PROFILE": _show_parser("PROFILE"),
    252            "PROFILES": _show_parser("PROFILES"),
    253            "RELAYLOG EVENTS": _show_parser("RELAYLOG EVENTS"),
    254            "REPLICAS": _show_parser("REPLICAS"),
    255            "SLAVE HOSTS": _show_parser("REPLICAS"),
    256            "REPLICA STATUS": _show_parser("REPLICA STATUS"),
    257            "SLAVE STATUS": _show_parser("REPLICA STATUS"),
    258            "GLOBAL STATUS": _show_parser("STATUS", global_=True),
    259            "SESSION STATUS": _show_parser("STATUS"),
    260            "STATUS": _show_parser("STATUS"),
    261            "TABLE STATUS": _show_parser("TABLE STATUS"),
    262            "FULL TABLES": _show_parser("TABLES", full=True),
    263            "TABLES": _show_parser("TABLES"),
    264            "TRIGGERS": _show_parser("TRIGGERS"),
    265            "GLOBAL VARIABLES": _show_parser("VARIABLES", global_=True),
    266            "SESSION VARIABLES": _show_parser("VARIABLES"),
    267            "VARIABLES": _show_parser("VARIABLES"),
    268            "WARNINGS": _show_parser("WARNINGS"),
    269        }
    270
    271        SET_PARSERS = {
    272            **parser.Parser.SET_PARSERS,
    273            "PERSIST": lambda self: self._parse_set_item_assignment("PERSIST"),
    274            "PERSIST_ONLY": lambda self: self._parse_set_item_assignment("PERSIST_ONLY"),
    275            "CHARACTER SET": lambda self: self._parse_set_item_charset("CHARACTER SET"),
    276            "CHARSET": lambda self: self._parse_set_item_charset("CHARACTER SET"),
    277            "NAMES": lambda self: self._parse_set_item_names(),
    278        }
    279
    280        PROFILE_TYPES = {
    281            "ALL",
    282            "BLOCK IO",
    283            "CONTEXT SWITCHES",
    284            "CPU",
    285            "IPC",
    286            "MEMORY",
    287            "PAGE FAULTS",
    288            "SOURCE",
    289            "SWAPS",
    290        }
    291
    292        def _parse_show_mysql(self, this, target=False, full=None, global_=None):
    293            if target:
    294                if isinstance(target, str):
    295                    self._match_text_seq(target)
    296                target_id = self._parse_id_var()
    297            else:
    298                target_id = None
    299
    300            log = self._parse_string() if self._match_text_seq("IN") else None
    301
    302            if this in {"BINLOG EVENTS", "RELAYLOG EVENTS"}:
    303                position = self._parse_number() if self._match_text_seq("FROM") else None
    304                db = None
    305            else:
    306                position = None
    307                db = self._parse_id_var() if self._match_text_seq("FROM") else None
    308
    309            channel = self._parse_id_var() if self._match_text_seq("FOR", "CHANNEL") else None
    310
    311            like = self._parse_string() if self._match_text_seq("LIKE") else None
    312            where = self._parse_where()
    313
    314            if this == "PROFILE":
    315                types = self._parse_csv(lambda: self._parse_var_from_options(self.PROFILE_TYPES))
    316                query = self._parse_number() if self._match_text_seq("FOR", "QUERY") else None
    317                offset = self._parse_number() if self._match_text_seq("OFFSET") else None
    318                limit = self._parse_number() if self._match_text_seq("LIMIT") else None
    319            else:
    320                types, query = None, None
    321                offset, limit = self._parse_oldstyle_limit()
    322
    323            mutex = True if self._match_text_seq("MUTEX") else None
    324            mutex = False if self._match_text_seq("STATUS") else mutex
    325
    326            return self.expression(
    327                exp.Show,
    328                this=this,
    329                target=target_id,
    330                full=full,
    331                log=log,
    332                position=position,
    333                db=db,
    334                channel=channel,
    335                like=like,
    336                where=where,
    337                types=types,
    338                query=query,
    339                offset=offset,
    340                limit=limit,
    341                mutex=mutex,
    342                **{"global": global_},
    343            )
    344
    345        def _parse_oldstyle_limit(self):
    346            limit = None
    347            offset = None
    348            if self._match_text_seq("LIMIT"):
    349                parts = self._parse_csv(self._parse_number)
    350                if len(parts) == 1:
    351                    limit = parts[0]
    352                elif len(parts) == 2:
    353                    limit = parts[1]
    354                    offset = parts[0]
    355            return offset, limit
    356
    357        def _parse_set_item_charset(self, kind):
    358            this = self._parse_string() or self._parse_id_var()
    359
    360            return self.expression(
    361                exp.SetItem,
    362                this=this,
    363                kind=kind,
    364            )
    365
    366        def _parse_set_item_names(self):
    367            charset = self._parse_string() or self._parse_id_var()
    368            if self._match_text_seq("COLLATE"):
    369                collate = self._parse_string() or self._parse_id_var()
    370            else:
    371                collate = None
    372            return self.expression(
    373                exp.SetItem,
    374                this=charset,
    375                collate=collate,
    376                kind="NAMES",
    377            )
    378
    379    class Generator(generator.Generator):
    380        LOCKING_READS_SUPPORTED = True
    381        NULL_ORDERING_SUPPORTED = False
    382
    383        TRANSFORMS = {
    384            **generator.Generator.TRANSFORMS,  # type: ignore
    385            exp.CurrentDate: no_paren_current_date_sql,
    386            exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP",
    387            exp.ILike: no_ilike_sql,
    388            exp.Min: min_or_least,
    389            exp.TableSample: no_tablesample_sql,
    390            exp.TryCast: no_trycast_sql,
    391            exp.DateAdd: _date_add_sql("ADD"),
    392            exp.DateDiff: lambda self, e: f"DATEDIFF({self.format_args(e.this, e.expression)})",
    393            exp.DateSub: _date_add_sql("SUB"),
    394            exp.DateTrunc: _date_trunc_sql,
    395            exp.DayOfWeek: rename_func("DAYOFWEEK"),
    396            exp.DayOfMonth: rename_func("DAYOFMONTH"),
    397            exp.DayOfYear: rename_func("DAYOFYEAR"),
    398            exp.WeekOfYear: rename_func("WEEKOFYEAR"),
    399            exp.GroupConcat: lambda self, e: f"""GROUP_CONCAT({self.sql(e, "this")} SEPARATOR {self.sql(e, "separator") or "','"})""",
    400            exp.StrToDate: _str_to_date_sql,
    401            exp.StrToTime: _str_to_date_sql,
    402            exp.Trim: _trim_sql,
    403            exp.NullSafeEQ: lambda self, e: self.binary(e, "<=>"),
    404            exp.NullSafeNEQ: lambda self, e: self.not_sql(self.binary(e, "<=>")),
    405            exp.StrPosition: strposition_to_locate_sql,
    406        }
    407
    408        TYPE_MAPPING = generator.Generator.TYPE_MAPPING.copy()
    409        TYPE_MAPPING.pop(exp.DataType.Type.MEDIUMTEXT)
    410        TYPE_MAPPING.pop(exp.DataType.Type.LONGTEXT)
    411        TYPE_MAPPING.pop(exp.DataType.Type.MEDIUMBLOB)
    412        TYPE_MAPPING.pop(exp.DataType.Type.LONGBLOB)
    413
    414        PROPERTIES_LOCATION = {
    415            **generator.Generator.PROPERTIES_LOCATION,  # type: ignore
    416            exp.TransientProperty: exp.Properties.Location.UNSUPPORTED,
    417        }
    418
    419        def show_sql(self, expression):
    420            this = f" {expression.name}"
    421            full = " FULL" if expression.args.get("full") else ""
    422            global_ = " GLOBAL" if expression.args.get("global") else ""
    423
    424            target = self.sql(expression, "target")
    425            target = f" {target}" if target else ""
    426            if expression.name in {"COLUMNS", "INDEX"}:
    427                target = f" FROM{target}"
    428            elif expression.name == "GRANTS":
    429                target = f" FOR{target}"
    430
    431            db = self._prefixed_sql("FROM", expression, "db")
    432
    433            like = self._prefixed_sql("LIKE", expression, "like")
    434            where = self.sql(expression, "where")
    435
    436            types = self.expressions(expression, key="types")
    437            types = f" {types}" if types else types
    438            query = self._prefixed_sql("FOR QUERY", expression, "query")
    439
    440            if expression.name == "PROFILE":
    441                offset = self._prefixed_sql("OFFSET", expression, "offset")
    442                limit = self._prefixed_sql("LIMIT", expression, "limit")
    443            else:
    444                offset = ""
    445                limit = self._oldstyle_limit_sql(expression)
    446
    447            log = self._prefixed_sql("IN", expression, "log")
    448            position = self._prefixed_sql("FROM", expression, "position")
    449
    450            channel = self._prefixed_sql("FOR CHANNEL", expression, "channel")
    451
    452            if expression.name == "ENGINE":
    453                mutex_or_status = " MUTEX" if expression.args.get("mutex") else " STATUS"
    454            else:
    455                mutex_or_status = ""
    456
    457            return f"SHOW{full}{global_}{this}{target}{types}{db}{query}{log}{position}{channel}{mutex_or_status}{like}{where}{offset}{limit}"
    458
    459        def _prefixed_sql(self, prefix, expression, arg):
    460            sql = self.sql(expression, arg)
    461            if not sql:
    462                return ""
    463            return f" {prefix} {sql}"
    464
    465        def _oldstyle_limit_sql(self, expression):
    466            limit = self.sql(expression, "limit")
    467            offset = self.sql(expression, "offset")
    468            if limit:
    469                limit_offset = f"{offset}, {limit}" if offset else limit
    470                return f" LIMIT {limit_offset}"
    471            return ""

##### Inherited Members

sqlglot.dialects.dialect.Dialect
  get_or_raise
  format_time
  parse
  parse_into
  generate
  transpile
  tokenize
  parser
  generator

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

    119    class Tokenizer(tokens.Tokenizer):
    120        QUOTES = ["'", '"']
    121        COMMENTS = ["--", "#", ("/*", "*/")]
    122        IDENTIFIERS = ["`"]
    123        STRING_ESCAPES = ["'", "\\"]
    124        BIT_STRINGS = [("b'", "'"), ("B'", "'"), ("0b", "")]
    125        HEX_STRINGS = [("x'", "'"), ("X'", "'"), ("0x", "")]
    126
    127        KEYWORDS = {
    128            **tokens.Tokenizer.KEYWORDS,
    129            "MEDIUMTEXT": TokenType.MEDIUMTEXT,
    130            "LONGTEXT": TokenType.LONGTEXT,
    131            "MEDIUMBLOB": TokenType.MEDIUMBLOB,
    132            "LONGBLOB": TokenType.LONGBLOB,
    133            "START": TokenType.BEGIN,
    134            "SEPARATOR": TokenType.SEPARATOR,
    135            "_ARMSCII8": TokenType.INTRODUCER,
    136            "_ASCII": TokenType.INTRODUCER,
    137            "_BIG5": TokenType.INTRODUCER,
    138            "_BINARY": TokenType.INTRODUCER,
    139            "_CP1250": TokenType.INTRODUCER,
    140            "_CP1251": TokenType.INTRODUCER,
    141            "_CP1256": TokenType.INTRODUCER,
    142            "_CP1257": TokenType.INTRODUCER,
    143            "_CP850": TokenType.INTRODUCER,
    144            "_CP852": TokenType.INTRODUCER,
    145            "_CP866": TokenType.INTRODUCER,
    146            "_CP932": TokenType.INTRODUCER,
    147            "_DEC8": TokenType.INTRODUCER,
    148            "_EUCJPMS": TokenType.INTRODUCER,
    149            "_EUCKR": TokenType.INTRODUCER,
    150            "_GB18030": TokenType.INTRODUCER,
    151            "_GB2312": TokenType.INTRODUCER,
    152            "_GBK": TokenType.INTRODUCER,
    153            "_GEOSTD8": TokenType.INTRODUCER,
    154            "_GREEK": TokenType.INTRODUCER,
    155            "_HEBREW": TokenType.INTRODUCER,
    156            "_HP8": TokenType.INTRODUCER,
    157            "_KEYBCS2": TokenType.INTRODUCER,
    158            "_KOI8R": TokenType.INTRODUCER,
    159            "_KOI8U": TokenType.INTRODUCER,
    160            "_LATIN1": TokenType.INTRODUCER,
    161            "_LATIN2": TokenType.INTRODUCER,
    162            "_LATIN5": TokenType.INTRODUCER,
    163            "_LATIN7": TokenType.INTRODUCER,
    164            "_MACCE": TokenType.INTRODUCER,
    165            "_MACROMAN": TokenType.INTRODUCER,
    166            "_SJIS": TokenType.INTRODUCER,
    167            "_SWE7": TokenType.INTRODUCER,
    168            "_TIS620": TokenType.INTRODUCER,
    169            "_UCS2": TokenType.INTRODUCER,
    170            "_UJIS": TokenType.INTRODUCER,
    171            # https://dev.mysql.com/doc/refman/8.0/en/string-literals.html
    172            "_UTF8": TokenType.INTRODUCER,
    173            "_UTF16": TokenType.INTRODUCER,
    174            "_UTF16LE": TokenType.INTRODUCER,
    175            "_UTF32": TokenType.INTRODUCER,
    176            "_UTF8MB3": TokenType.INTRODUCER,
    177            "_UTF8MB4": TokenType.INTRODUCER,
    178            "@@": TokenType.SESSION_PARAMETER,
    179        }
    180
    181        COMMANDS = tokens.Tokenizer.COMMANDS - {TokenType.SHOW}

##### Inherited Members

sqlglot.tokens.Tokenizer
  reset
  tokenize

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

    183    class Parser(parser.Parser):
    184        FUNC_TOKENS = {*parser.Parser.FUNC_TOKENS, TokenType.SCHEMA, TokenType.DATABASE}  # type: ignore
    185
    186        FUNCTIONS = {
    187            **parser.Parser.FUNCTIONS,  # type: ignore
    188            "DATE_ADD": _date_add(exp.DateAdd),
    189            "DATE_SUB": _date_add(exp.DateSub),
    190            "STR_TO_DATE": _str_to_date,
    191            "LOCATE": locate_to_strposition,
    192            "INSTR": lambda args: exp.StrPosition(substr=seq_get(args, 1), this=seq_get(args, 0)),
    193            "LEFT": lambda args: exp.Substring(
    194                this=seq_get(args, 0), start=exp.Literal.number(1), length=seq_get(args, 1)
    195            ),
    196        }
    197
    198        FUNCTION_PARSERS = {
    199            **parser.Parser.FUNCTION_PARSERS,  # type: ignore
    200            "GROUP_CONCAT": lambda self: self.expression(
    201                exp.GroupConcat,
    202                this=self._parse_lambda(),
    203                separator=self._match(TokenType.SEPARATOR) and self._parse_field(),
    204            ),
    205        }
    206
    207        PROPERTY_PARSERS = {
    208            **parser.Parser.PROPERTY_PARSERS,  # type: ignore
    209            "ENGINE": lambda self: self._parse_property_assignment(exp.EngineProperty),
    210        }
    211
    212        STATEMENT_PARSERS = {
    213            **parser.Parser.STATEMENT_PARSERS,  # type: ignore
    214            TokenType.SHOW: lambda self: self._parse_show(),
    215        }
    216
    217        SHOW_PARSERS = {
    218            "BINARY LOGS": _show_parser("BINARY LOGS"),
    219            "MASTER LOGS": _show_parser("BINARY LOGS"),
    220            "BINLOG EVENTS": _show_parser("BINLOG EVENTS"),
    221            "CHARACTER SET": _show_parser("CHARACTER SET"),
    222            "CHARSET": _show_parser("CHARACTER SET"),
    223            "COLLATION": _show_parser("COLLATION"),
    224            "FULL COLUMNS": _show_parser("COLUMNS", target="FROM", full=True),
    225            "COLUMNS": _show_parser("COLUMNS", target="FROM"),
    226            "CREATE DATABASE": _show_parser("CREATE DATABASE", target=True),
    227            "CREATE EVENT": _show_parser("CREATE EVENT", target=True),
    228            "CREATE FUNCTION": _show_parser("CREATE FUNCTION", target=True),
    229            "CREATE PROCEDURE": _show_parser("CREATE PROCEDURE", target=True),
    230            "CREATE TABLE": _show_parser("CREATE TABLE", target=True),
    231            "CREATE TRIGGER": _show_parser("CREATE TRIGGER", target=True),
    232            "CREATE VIEW": _show_parser("CREATE VIEW", target=True),
    233            "DATABASES": _show_parser("DATABASES"),
    234            "ENGINE": _show_parser("ENGINE", target=True),
    235            "STORAGE ENGINES": _show_parser("ENGINES"),
    236            "ENGINES": _show_parser("ENGINES"),
    237            "ERRORS": _show_parser("ERRORS"),
    238            "EVENTS": _show_parser("EVENTS"),
    239            "FUNCTION CODE": _show_parser("FUNCTION CODE", target=True),
    240            "FUNCTION STATUS": _show_parser("FUNCTION STATUS"),
    241            "GRANTS": _show_parser("GRANTS", target="FOR"),
    242            "INDEX": _show_parser("INDEX", target="FROM"),
    243            "MASTER STATUS": _show_parser("MASTER STATUS"),
    244            "OPEN TABLES": _show_parser("OPEN TABLES"),
    245            "PLUGINS": _show_parser("PLUGINS"),
    246            "PROCEDURE CODE": _show_parser("PROCEDURE CODE", target=True),
    247            "PROCEDURE STATUS": _show_parser("PROCEDURE STATUS"),
    248            "PRIVILEGES": _show_parser("PRIVILEGES"),
    249            "FULL PROCESSLIST": _show_parser("PROCESSLIST", full=True),
    250            "PROCESSLIST": _show_parser("PROCESSLIST"),
    251            "PROFILE": _show_parser("PROFILE"),
    252            "PROFILES": _show_parser("PROFILES"),
    253            "RELAYLOG EVENTS": _show_parser("RELAYLOG EVENTS"),
    254            "REPLICAS": _show_parser("REPLICAS"),
    255            "SLAVE HOSTS": _show_parser("REPLICAS"),
    256            "REPLICA STATUS": _show_parser("REPLICA STATUS"),
    257            "SLAVE STATUS": _show_parser("REPLICA STATUS"),
    258            "GLOBAL STATUS": _show_parser("STATUS", global_=True),
    259            "SESSION STATUS": _show_parser("STATUS"),
    260            "STATUS": _show_parser("STATUS"),
    261            "TABLE STATUS": _show_parser("TABLE STATUS"),
    262            "FULL TABLES": _show_parser("TABLES", full=True),
    263            "TABLES": _show_parser("TABLES"),
    264            "TRIGGERS": _show_parser("TRIGGERS"),
    265            "GLOBAL VARIABLES": _show_parser("VARIABLES", global_=True),
    266            "SESSION VARIABLES": _show_parser("VARIABLES"),
    267            "VARIABLES": _show_parser("VARIABLES"),
    268            "WARNINGS": _show_parser("WARNINGS"),
    269        }
    270
    271        SET_PARSERS = {
    272            **parser.Parser.SET_PARSERS,
    273            "PERSIST": lambda self: self._parse_set_item_assignment("PERSIST"),
    274            "PERSIST_ONLY": lambda self: self._parse_set_item_assignment("PERSIST_ONLY"),
    275            "CHARACTER SET": lambda self: self._parse_set_item_charset("CHARACTER SET"),
    276            "CHARSET": lambda self: self._parse_set_item_charset("CHARACTER SET"),
    277            "NAMES": lambda self: self._parse_set_item_names(),
    278        }
    279
    280        PROFILE_TYPES = {
    281            "ALL",
    282            "BLOCK IO",
    283            "CONTEXT SWITCHES",
    284            "CPU",
    285            "IPC",
    286            "MEMORY",
    287            "PAGE FAULTS",
    288            "SOURCE",
    289            "SWAPS",
    290        }
    291
    292        def _parse_show_mysql(self, this, target=False, full=None, global_=None):
    293            if target:
    294                if isinstance(target, str):
    295                    self._match_text_seq(target)
    296                target_id = self._parse_id_var()
    297            else:
    298                target_id = None
    299
    300            log = self._parse_string() if self._match_text_seq("IN") else None
    301
    302            if this in {"BINLOG EVENTS", "RELAYLOG EVENTS"}:
    303                position = self._parse_number() if self._match_text_seq("FROM") else None
    304                db = None
    305            else:
    306                position = None
    307                db = self._parse_id_var() if self._match_text_seq("FROM") else None
    308
    309            channel = self._parse_id_var() if self._match_text_seq("FOR", "CHANNEL") else None
    310
    311            like = self._parse_string() if self._match_text_seq("LIKE") else None
    312            where = self._parse_where()
    313
    314            if this == "PROFILE":
    315                types = self._parse_csv(lambda: self._parse_var_from_options(self.PROFILE_TYPES))
    316                query = self._parse_number() if self._match_text_seq("FOR", "QUERY") else None
    317                offset = self._parse_number() if self._match_text_seq("OFFSET") else None
    318                limit = self._parse_number() if self._match_text_seq("LIMIT") else None
    319            else:
    320                types, query = None, None
    321                offset, limit = self._parse_oldstyle_limit()
    322
    323            mutex = True if self._match_text_seq("MUTEX") else None
    324            mutex = False if self._match_text_seq("STATUS") else mutex
    325
    326            return self.expression(
    327                exp.Show,
    328                this=this,
    329                target=target_id,
    330                full=full,
    331                log=log,
    332                position=position,
    333                db=db,
    334                channel=channel,
    335                like=like,
    336                where=where,
    337                types=types,
    338                query=query,
    339                offset=offset,
    340                limit=limit,
    341                mutex=mutex,
    342                **{"global": global_},
    343            )
    344
    345        def _parse_oldstyle_limit(self):
    346            limit = None
    347            offset = None
    348            if self._match_text_seq("LIMIT"):
    349                parts = self._parse_csv(self._parse_number)
    350                if len(parts) == 1:
    351                    limit = parts[0]
    352                elif len(parts) == 2:
    353                    limit = parts[1]
    354                    offset = parts[0]
    355            return offset, limit
    356
    357        def _parse_set_item_charset(self, kind):
    358            this = self._parse_string() or self._parse_id_var()
    359
    360            return self.expression(
    361                exp.SetItem,
    362                this=this,
    363                kind=kind,
    364            )
    365
    366        def _parse_set_item_names(self):
    367            charset = self._parse_string() or self._parse_id_var()
    368            if self._match_text_seq("COLLATE"):
    369                collate = self._parse_string() or self._parse_id_var()
    370            else:
    371                collate = None
    372            return self.expression(
    373                exp.SetItem,
    374                this=charset,
    375                collate=collate,
    376                kind="NAMES",
    377            )

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

###### Arguments:

- error_level: the desired error level. Default: ErrorLevel.RAISE
- error_message_context: determines the amount of context to capture from a query string when displaying the error message (in number of characters). Default: 50.
- index_offset: Index offset for arrays eg ARRAY[0] vs ARRAY[1] as the head of a list. Default: 0
- alias_post_tablesample: If the table alias comes after tablesample. Default: False
- 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
- null_ordering: Indicates the default null ordering method to use if not explicitly set. Options are "nulls_are_small", "nulls_are_large", "nulls_are_last". Default: "nulls_are_small"

##### Inherited Members

sqlglot.parser.Parser
  Parser
  reset
  parse
  parse_into
  check_errors
  raise_error
  expression
  validate_expression

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

    379    class Generator(generator.Generator):
    380        LOCKING_READS_SUPPORTED = True
    381        NULL_ORDERING_SUPPORTED = False
    382
    383        TRANSFORMS = {
    384            **generator.Generator.TRANSFORMS,  # type: ignore
    385            exp.CurrentDate: no_paren_current_date_sql,
    386            exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP",
    387            exp.ILike: no_ilike_sql,
    388            exp.Min: min_or_least,
    389            exp.TableSample: no_tablesample_sql,
    390            exp.TryCast: no_trycast_sql,
    391            exp.DateAdd: _date_add_sql("ADD"),
    392            exp.DateDiff: lambda self, e: f"DATEDIFF({self.format_args(e.this, e.expression)})",
    393            exp.DateSub: _date_add_sql("SUB"),
    394            exp.DateTrunc: _date_trunc_sql,
    395            exp.DayOfWeek: rename_func("DAYOFWEEK"),
    396            exp.DayOfMonth: rename_func("DAYOFMONTH"),
    397            exp.DayOfYear: rename_func("DAYOFYEAR"),
    398            exp.WeekOfYear: rename_func("WEEKOFYEAR"),
    399            exp.GroupConcat: lambda self, e: f"""GROUP_CONCAT({self.sql(e, "this")} SEPARATOR {self.sql(e, "separator") or "','"})""",
    400            exp.StrToDate: _str_to_date_sql,
    401            exp.StrToTime: _str_to_date_sql,
    402            exp.Trim: _trim_sql,
    403            exp.NullSafeEQ: lambda self, e: self.binary(e, "<=>"),
    404            exp.NullSafeNEQ: lambda self, e: self.not_sql(self.binary(e, "<=>")),
    405            exp.StrPosition: strposition_to_locate_sql,
    406        }
    407
    408        TYPE_MAPPING = generator.Generator.TYPE_MAPPING.copy()
    409        TYPE_MAPPING.pop(exp.DataType.Type.MEDIUMTEXT)
    410        TYPE_MAPPING.pop(exp.DataType.Type.LONGTEXT)
    411        TYPE_MAPPING.pop(exp.DataType.Type.MEDIUMBLOB)
    412        TYPE_MAPPING.pop(exp.DataType.Type.LONGBLOB)
    413
    414        PROPERTIES_LOCATION = {
    415            **generator.Generator.PROPERTIES_LOCATION,  # type: ignore
    416            exp.TransientProperty: exp.Properties.Location.UNSUPPORTED,
    417        }
    418
    419        def show_sql(self, expression):
    420            this = f" {expression.name}"
    421            full = " FULL" if expression.args.get("full") else ""
    422            global_ = " GLOBAL" if expression.args.get("global") else ""
    423
    424            target = self.sql(expression, "target")
    425            target = f" {target}" if target else ""
    426            if expression.name in {"COLUMNS", "INDEX"}:
    427                target = f" FROM{target}"
    428            elif expression.name == "GRANTS":
    429                target = f" FOR{target}"
    430
    431            db = self._prefixed_sql("FROM", expression, "db")
    432
    433            like = self._prefixed_sql("LIKE", expression, "like")
    434            where = self.sql(expression, "where")
    435
    436            types = self.expressions(expression, key="types")
    437            types = f" {types}" if types else types
    438            query = self._prefixed_sql("FOR QUERY", expression, "query")
    439
    440            if expression.name == "PROFILE":
    441                offset = self._prefixed_sql("OFFSET", expression, "offset")
    442                limit = self._prefixed_sql("LIMIT", expression, "limit")
    443            else:
    444                offset = ""
    445                limit = self._oldstyle_limit_sql(expression)
    446
    447            log = self._prefixed_sql("IN", expression, "log")
    448            position = self._prefixed_sql("FROM", expression, "position")
    449
    450            channel = self._prefixed_sql("FOR CHANNEL", expression, "channel")
    451
    452            if expression.name == "ENGINE":
    453                mutex_or_status = " MUTEX" if expression.args.get("mutex") else " STATUS"
    454            else:
    455                mutex_or_status = ""
    456
    457            return f"SHOW{full}{global_}{this}{target}{types}{db}{query}{log}{position}{channel}{mutex_or_status}{like}{where}{offset}{limit}"
    458
    459        def _prefixed_sql(self, prefix, expression, arg):
    460            sql = self.sql(expression, arg)
    461            if not sql:
    462                return ""
    463            return f" {prefix} {sql}"
    464
    465        def _oldstyle_limit_sql(self, expression):
    466            limit = self.sql(expression, "limit")
    467            offset = self.sql(expression, "offset")
    468            if limit:
    469                limit_offset = f"{offset}, {limit}" if offset else limit
    470                return f" LIMIT {limit_offset}"
    471            return ""

Generator interprets the given syntax tree and produces a SQL string as an output.

###### Arguments:

- time_mapping (dict): the dictionary of custom time mappings in which the key represents a python time format and the output the target time format
- time_trie (trie): a trie of the time_mapping keys
- pretty (bool): if set to True the returned string will be formatted. Default: False.
- quote_start (str): specifies which starting character to use to delimit quotes. Default: '.
- quote_end (str): specifies which ending character to use to delimit quotes. Default: '.
- identifier_start (str): specifies which starting character to use to delimit identifiers. Default: ".
- identifier_end (str): specifies which ending character to use to delimit identifiers. Default: ".
- identify (bool | str): 'always': always quote, 'safe': quote identifiers if they don't contain an upcase, True defaults to always.
- normalize (bool): if set to True all identifiers will lower cased
- string_escape (str): specifies a string escape character. Default: '.
- identifier_escape (str): specifies an identifier escape character. Default: ".
- pad (int): determines padding in a formatted string. Default: 2.
- indent (int): determines the size of indentation in a formatted string. Default: 4.
- unnest_column_only (bool): if true unnest table aliases are considered only as column aliases
- normalize_functions (str): normalize function names, "upper", "lower", or None Default: "upper"
- alias_post_tablesample (bool): if the table alias comes after tablesample Default: False
- unsupported_level (ErrorLevel): determines the generator's behavior when it encounters unsupported expressions. Default ErrorLevel.WARN.
- null_ordering (str): Indicates the default null ordering method to use if not explicitly set. Options are "nulls_are_small", "nulls_are_large", "nulls_are_last". Default: "nulls_are_small"
- max_unsupported (int): 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 (bool): if the the comma is leading or trailing in select statements 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

def show_sql(self, expression): View Source

    419        def show_sql(self, expression):
    420            this = f" {expression.name}"
    421            full = " FULL" if expression.args.get("full") else ""
    422            global_ = " GLOBAL" if expression.args.get("global") else ""
    423
    424            target = self.sql(expression, "target")
    425            target = f" {target}" if target else ""
    426            if expression.name in {"COLUMNS", "INDEX"}:
    427                target = f" FROM{target}"
    428            elif expression.name == "GRANTS":
    429                target = f" FOR{target}"
    430
    431            db = self._prefixed_sql("FROM", expression, "db")
    432
    433            like = self._prefixed_sql("LIKE", expression, "like")
    434            where = self.sql(expression, "where")
    435
    436            types = self.expressions(expression, key="types")
    437            types = f" {types}" if types else types
    438            query = self._prefixed_sql("FOR QUERY", expression, "query")
    439
    440            if expression.name == "PROFILE":
    441                offset = self._prefixed_sql("OFFSET", expression, "offset")
    442                limit = self._prefixed_sql("LIMIT", expression, "limit")
    443            else:
    444                offset = ""
    445                limit = self._oldstyle_limit_sql(expression)
    446
    447            log = self._prefixed_sql("IN", expression, "log")
    448            position = self._prefixed_sql("FROM", expression, "position")
    449
    450            channel = self._prefixed_sql("FOR CHANNEL", expression, "channel")
    451
    452            if expression.name == "ENGINE":
    453                mutex_or_status = " MUTEX" if expression.args.get("mutex") else " STATUS"
    454            else:
    455                mutex_or_status = ""
    456
    457            return f"SHOW{full}{global_}{this}{target}{types}{db}{query}{log}{position}{channel}{mutex_or_status}{like}{where}{offset}{limit}"

##### Inherited Members

sqlglot.generator.Generator
  Generator
  generate
  unsupported
  sep
  seg
  pad_comment
  maybe_comment
  wrap
  no_identify
  normalize_func
  indent
  sql
  uncache_sql
  cache_sql
  characterset_sql
  column_sql
  columndef_sql
  columnconstraint_sql
  autoincrementcolumnconstraint_sql
  compresscolumnconstraint_sql
  generatedasidentitycolumnconstraint_sql
  notnullcolumnconstraint_sql
  primarykeycolumnconstraint_sql
  uniquecolumnconstraint_sql
  create_sql
  describe_sql
  prepend_ctes
  with_sql
  cte_sql
  tablealias_sql
  bitstring_sql
  hexstring_sql
  datatype_sql
  directory_sql
  delete_sql
  drop_sql
  except_sql
  except_op
  fetch_sql
  filter_sql
  hint_sql
  index_sql
  identifier_sql
  national_sql
  partition_sql
  properties_sql
  root_properties
  properties
  with_properties
  locate_properties
  property_sql
  likeproperty_sql
  fallbackproperty_sql
  journalproperty_sql
  freespaceproperty_sql
  afterjournalproperty_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
  returning_sql
  rowformatdelimitedproperty_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
  limit_sql
  offset_sql
  setitem_sql
  set_sql
  lock_sql
  literal_sql
  loaddata_sql
  null_sql
  boolean_sql
  order_sql
  cluster_sql
  distribute_sql
  sort_sql
  ordered_sql
  matchrecognize_sql
  query_modifiers
  select_sql
  schema_sql
  star_sql
  structkwarg_sql
  parameter_sql
  sessionparameter_sql
  placeholder_sql
  subquery_sql
  qualify_sql
  union_sql
  union_op
  unnest_sql
  where_sql
  window_sql
  partition_by_sql
  window_spec_sql
  withingroup_sql
  between_sql
  bracket_sql
  all_sql
  any_sql
  exists_sql
  case_sql
  constraint_sql
  extract_sql
  trim_sql
  concat_sql
  check_sql
  foreignkey_sql
  primarykey_sql
  unique_sql
  if_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
  cast_sql
  currentdate_sql
  collate_sql
  command_sql
  comment_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
  div_sql
  overlaps_sql
  distance_sql
  dot_sql
  eq_sql
  escape_sql
  glob_sql
  gt_sql
  gte_sql
  ilike_sql
  is_sql
  like_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