packages/sql-parser/src/MySql/MySqlParser.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlParser\MySql;
6
7use RuntimeException;
8use SqlParser\Lexer\LexicalException;
9use SqlParser\Lexer\ParameterSyntax;
10use SqlParser\Lexer\TerminalIndex;
11use SqlParser\Lexer\Token;
12use SqlParser\MySql\Lexer\KeywordTable;
13use SqlParser\MySql\Lexer\MySqlLexer;
14use SqlParser\Parser\LrParser;
15use SqlParser\Parser\Node;
16use SqlParser\Parser\SqlParser;
17use SqlParser\Parser\SyntaxException;
18use SqlParser\Resource\VersionRegistry;
19use SqlParser\Table\ParseTable;
20use SqlParser\Table\TableFile;
21
22/**
23 * Parses MySQL statements with the grammar of a chosen server release.
24 *
25 * The parse table is built from the `sql_yacc.yy` of that release and the
26 * lexer follows its `sql_lex.cc`, so the tree names the nonterminals of the
27 * official grammar. One statement is parsed at a time, as the server does.
28 *
29 * @visibility public
30 *
31 * @example Parsing with the default release
32 *     $parser = new \SqlParser\MySql\MySqlParser();
33 *     $tree = $parser->parse('SELECT id FROM users WHERE id = ?');
34 *     $tree->name // => 'start_entry'
35 *     count($tree->find('table_reference')) // => 1
36 * @example Writing a parsed statement back
37 *     $sql = "SELECT id FROM users -- everyone\n";
38 *     $parser = new \SqlParser\MySql\MySqlParser();
39 *     $parser->parse($sql)->toString() === $sql // => true
40 * @example Choosing a release
41 *     $parser = new \SqlParser\MySql\MySqlParser('mysql-5.7.44');
42 *     $parser->version() // => 'mysql-5.7.44'
43 * @example Rejecting an unsupported release
44 *     new \SqlParser\MySql\MySqlParser('mysql-4.1.0') // throws \RuntimeException: Unsupported
45 * @example Reading a named placeholder
46 *     $parser = new \SqlParser\MySql\MySqlParser(parameters: \SqlParser\Lexer\ParameterSyntax::Named);
47 *     $parser->tokenize('SELECT id FROM users WHERE id = :id')[7]->name // => 'PARAM_MARKER'
48 */
49final class MySqlParser implements SqlParser
50{
51    private readonly MySqlVersion $version;
52
53    private readonly ParseTable $table;
54
55    private readonly MySqlLexer $lexer;
56
57    /**
58     * Loads the parser of one release.
59     *
60     * @param string|null $version Release tag such as `mysql-8.4.7`, or null for the newest shipped
61     * @param SqlMode $mode The `sql_mode` flags that change tokenization
62     * @param VersionRegistry $registry Record of shipped releases
63     * @param ParameterSyntax $parameters Which parameter markers are read; the server reads only `?`
64     *
65     * @throws RuntimeException When the release is not shipped or its resources are missing
66     */
67    public function __construct(?string $version = null, SqlMode $mode = new SqlMode(), VersionRegistry $registry = new VersionRegistry(), ParameterSyntax $parameters = ParameterSyntax::Native)
68    {
69        $this->version = MySqlVersion::resolve($version, $registry);
70        $this->table = (new TableFile())->load($this->version->release->tablePath);
71        $this->lexer = new MySqlLexer(KeywordTable::load($this->version->release->keywordPath), $this->version, $mode, parameters: $parameters);
72    }
73
74    /**
75     * Answers the release the parser reads for.
76     *
77     * @return string Release tag such as `mysql-8.4.7`
78     */
79    public function version(): string
80    {
81        return $this->version->name();
82    }
83
84    /**
85     * Reads SQL text into the terminals of the grammar, the end marker last.
86     *
87     * A token carries the whitespace and comments skipped before it and the
88     * end marker what follows the last of them, so the tokens hold every byte
89     * of the text.
90     *
91     * @param string $sql The SQL text
92     *
93     * @return list<Token> The tokens in text order
94     *
95     * @throws LexicalException When the text holds something no token starts with
96     */
97    public function tokenize(string $sql): array
98    {
99        return (new TerminalIndex($this->table->symbols))->tokens($this->lexer->scan($sql), $sql);
100    }
101
102    /**
103     * Parses one statement.
104     *
105     * @param string $sql The SQL text
106     *
107     * @return Node The tree, rooted at the grammar's start symbol, holding every byte of the text
108     *
109     * @throws LexicalException When the text holds something no token starts with
110     * @throws SyntaxException When the statement is not in the grammar of the release
111     */
112    public function parse(string $sql): Node
113    {
114        return (new LrParser($this->table))->parse($this->tokenize($sql), $sql);
115    }
116
117    /**
118     * Answers every release tag the package ships a MySQL grammar for, oldest first.
119     *
120     * @return list<string> Release tags
121     */
122    public static function versions(): array
123    {
124        return (new VersionRegistry())->names(MySqlVersion::DIALECT);
125    }
126}
127