packages/sql-semantics-mysql/src/Lowering/Query/QueryRules.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Lowering\Query;
6
7use SqlParser\Parser\Node;
8use SqlSemantics\Platform\MySql\Lowering\Lowering;
9use SqlSemantics\Platform\MySql\Lowering\Query\Legacy\BlockRule;
10use SqlSemantics\Platform\MySql\Lowering\Query\Legacy\SubqueryRule;
11use SqlSemantics\Platform\MySql\Lowering\Query\Legacy\UnionRule;
12use SqlSemantics\Platform\MySql\Lowering\Query\Modern\ExpressionRule;
13use SqlSemantics\Platform\MySql\Lowering\Query\Modern\PrimaryRule;
14use SqlSemantics\Platform\MySql\Lowering\Query\Shared\ClauseRule;
15use SqlSemantics\Platform\MySql\Lowering\Query\Shared\FromRule;
16use SqlSemantics\Platform\MySql\Lowering\Query\Shared\ItemRule;
17use SqlSemantics\Platform\MySql\Lowering\Query\Shared\TableRule;
18use SqlSemantics\Platform\MySql\Lowering\Query\Shared\TailRule;
19use SqlSemantics\Platform\MySql\Lowering\Query\Shared\Trailer;
20use SqlSemantics\Platform\MySql\Model\Diagnostic\Check;
21use SqlSemantics\Platform\MySql\Model\Diagnostic\ImplementationGap;
22use SqlSemantics\Platform\MySql\Model\Statement\Identifier\Name;
23use SqlSemantics\Platform\MySql\Model\Statement\Query;
24use SqlSemantics\Platform\MySql\Model\Statement\Relation;
25use SqlSemantics\Platform\MySql\Model\Statement\Scalar;
26use SqlSemantics\Platform\MySql\Model\Statement\Statement;
27use SqlSemantics\Platform\MySql\Statement\Name\AliasMark;
28use SqlSemantics\Platform\MySql\Statement\Name\TableWildcard;
29use SqlSemantics\Platform\MySql\Statement\Query\Direction;
30use SqlSemantics\Platform\MySql\Statement\Query\Limit;
31use SqlSemantics\Platform\MySql\Statement\Query\OrderItem;
32use SqlSemantics\Platform\MySql\Statement\Query\ParenthesizedQuery;
33use SqlSemantics\Platform\MySql\Statement\Query\SelectExpression;
34use SqlSemantics\Platform\MySql\Statement\Query\Star;
35use SqlSemantics\Platform\MySql\Statement\Query\WithClause;
36use SqlSemantics\Platform\MySql\Statement\Relation\Hint\PrimaryIndex;
37
38/**
39 * The entry rules of the query family: the methods other families and the statement dispatcher call.
40 *
41 * Rule: MYSQL-QUERY-ENTRY-001. Scope: SELECT, set operations, VALUES and
42 * TABLE statements, WITH, table references, joins, grouping, ordering,
43 * limits, locking and INTO, in both grammar generations: the rules of
44 * Lowering/Query/Modern (8.0 and later), Lowering/Query/Legacy (5.6 and
45 * 5.7) and Lowering/Query/Shared. A query that a subquery, a derived table
46 * or a common table expression writes in the parentheses its syntax
47 * requires is answered without those parentheses; the construct that holds
48 * it writes them. Source: https://dev.mysql.com/doc/refman/8.4/en/select.html.
49 * Status: Implemented.
50 *
51 * @visibility SqlSemantics\Platform\MySql
52 */
53final class QueryRules
54{
55    /**
56     * @param Lowering $lowering The lowering this rule belongs to
57     */
58    public function __construct(public readonly Lowering $lowering)
59    {
60    }
61
62    /**
63     * Lowers a query statement: a node of `select` (5.6, 5.7) or `select_stmt` (8.0 and later).
64     *
65     * @throws ImplementationGap When a production has no rule
66     */
67    public function statement(Node $statement): Statement
68    {
69        $query = $this->query($statement);
70        Check::invariant($query instanceof Statement, 'Every query of the query family is also a statement.');
71
72        return $query;
73    }
74
75    /**
76     * Lowers a query used inside another statement: a node of `select`, `select_stmt`, `subselect`,
77     * `subquery`, `table_subquery`, `row_subquery`, `query_expression`, `query_expression_parens`,
78     * `query_expression_with_opt_locking_clauses` or `view_select_aux`.
79     *
80     * @throws ImplementationGap When a production has no rule
81     */
82    public function query(Node $query): Query
83    {
84        $expressions = new ExpressionRule($this->lowering);
85
86        return match ($query->name) {
87            'select' => (new UnionRule($this->lowering))->statement($query),
88            'select_stmt' => $expressions->statement($query),
89            'subselect' => (new SubqueryRule($this->lowering))->subselect($query),
90            'subquery', 'table_subquery', 'row_subquery' => $expressions->subquery($query),
91            'query_expression' => $expressions->expression($query, new Trailer()),
92            'query_expression_parens' => $expressions->inner($query),
93            'query_expression_with_opt_locking_clauses' => $expressions->locked($query),
94            'view_select_aux' => (new UnionRule($this->lowering))->viewQuery($query),
95            default => throw ImplementationGap::production($this->lowering->form($query)),
96        };
97    }
98
99    /**
100     * Lowers the query of CREATE TABLE ... SELECT and INSERT ... SELECT of MySQL 5.6 and 5.7: a node of
101     * `create_select` and the node of `union_clause`, `opt_union_clause` or `union_opt` that follows it.
102     *
103     * @throws ImplementationGap When a production has no rule
104     */
105    public function legacyQuery(Node $select, ?Node $union = null): Query
106    {
107        return (new UnionRule($this->lowering))->chain((new BlockRule($this->lowering))->create($select), $union);
108    }
109
110    /**
111     * Lowers the parenthesized query of CREATE TABLE ... SELECT and INSERT ... SELECT of MySQL 5.6 and 5.7: the
112     * node of `create_select` written in parentheses (`create3`, `insert_values`, `insert_query_expression`:
113     * `( create_select ) union_opt`) and the node of `union_opt` that follows the parentheses. The
114     * parentheses are kept as a parenthesized query; the holding statement writes nothing for them.
115     *
116     * @throws ImplementationGap When a production has no rule
117     */
118    public function legacyParenthesizedQuery(Node $select, Node $union): Query
119    {
120        return (new UnionRule($this->lowering))->chain(new ParenthesizedQuery((new BlockRule($this->lowering))->create($select)->select()), $union);
121    }
122
123    /**
124     * Lowers a row predicate: a node of `where_clause` or `opt_where_clause`; an absent clause is null.
125     *
126     * @throws ImplementationGap When a production has no rule
127     */
128    public function where(Node $clause): ?Scalar
129    {
130        return (new ClauseRule($this->lowering))->predicate($clause);
131    }
132
133    /**
134     * Lowers ordering or grouping expressions: a node of `opt_order_clause`, `order_clause`, `order_list`
135     * or `group_list`; an absent clause is empty. Integers stay the expressions they are.
136     *
137     * @return list<OrderItem>
138     * @throws ImplementationGap When a production has no rule
139     */
140    public function ordering(Node $clause): array
141    {
142        return (new ClauseRule($this->lowering))->orderItems($clause);
143    }
144
145    /**
146     * Lowers one ordering expression: a node of `order_expr`, or a node of `order_ident` with the node of
147     * `order_dir` that follows it.
148     *
149     * @throws ImplementationGap When a production has no rule
150     */
151    public function orderItem(Node $item, ?Node $direction = null): OrderItem
152    {
153        return (new ClauseRule($this->lowering))->item($item, $direction);
154    }
155
156    /**
157     * Lowers a sort direction: a node of `order_dir`, `opt_ordering_direction` or `ordering_direction`; no
158     * direction is null.
159     *
160     * @throws ImplementationGap When a production has no rule
161     */
162    public function direction(Node $direction): ?Direction
163    {
164        return (new ClauseRule($this->lowering))->direction($direction);
165    }
166
167    /**
168     * Lowers a LIMIT clause: a node of `opt_limit_clause`, `limit_clause`, `opt_simple_limit` or
169     * `opt_limit_clause_init`; an absent clause is null.
170     *
171     * @throws ImplementationGap When a production has no rule
172     */
173    public function limit(Node $clause): ?Limit
174    {
175        return (new TailRule($this->lowering))->limit($clause);
176    }
177
178    /**
179     * Lowers one LIMIT operand: a node of `limit_option`.
180     *
181     * @throws ImplementationGap When a production has no rule
182     */
183    public function limitValue(Node $option): Scalar
184    {
185        return (new TailRule($this->lowering))->value($option);
186    }
187
188    /**
189     * Lowers the table references of UPDATE and DELETE: a node of `join_table_list` or
190     * `table_reference_list`.
191     *
192     * @return list<Relation>
193     * @throws ImplementationGap When a production has no rule
194     */
195    public function tables(Node $list): array
196    {
197        return (new FromRule($this->lowering))->members($list);
198    }
199
200    /**
201     * Lowers an explicit partition selection: a node of `opt_use_partition` or `use_partition`; an absent
202     * selection is empty.
203     *
204     * @return list<Name>
205     * @throws ImplementationGap When a production has no rule
206     */
207    public function partitions(Node $selection): array
208    {
209        return (new TableRule($this->lowering))->partitions($selection);
210    }
211
212    /**
213     * Lowers an optional alias: a node of `opt_table_alias` or `select_alias`.
214     *
215     * @throws ImplementationGap When a production has no rule
216     */
217    public function alias(Node $alias): ?Name
218    {
219        return $alias->name === 'select_alias' ? (new ItemRule($this->lowering))->alias($alias) : (new TableRule($this->lowering))->alias($alias);
220    }
221
222    /**
223     * Answers what is written before an optional alias: a node of `opt_table_alias` or `select_alias`.
224     *
225     * @throws ImplementationGap When a production has no rule
226     */
227    public function mark(Node $alias): AliasMark
228    {
229        return $alias->name === 'select_alias' ? (new ItemRule($this->lowering))->mark($alias) : (new TableRule($this->lowering))->mark($alias);
230    }
231
232    /**
233     * Lowers the column names of a derived table, view or VALUES alias: a node of
234     * `opt_derived_column_list`; an absent list is empty.
235     *
236     * @return list<Name>
237     * @throws ImplementationGap When a production has no rule
238     */
239    public function columnAliases(Node $list): array
240    {
241        return (new TableRule($this->lowering))->columns($list);
242    }
243
244    /**
245     * Lowers a WITH clause: a node of `opt_with_clause` or `with_clause`; an absent clause is null.
246     *
247     * @throws ImplementationGap When a production has no rule
248     */
249    public function with(Node $clause): ?WithClause
250    {
251        return (new PrimaryRule($this->lowering))->with($clause);
252    }
253
254    /**
255     * Lowers a select list: a node of `select_item_list`.
256     *
257     * @return list<SelectExpression|Star|TableWildcard>
258     * @throws ImplementationGap When a production has no rule
259     */
260    public function selectItems(Node $list): array
261    {
262        return (new ItemRule($this->lowering))->items($list);
263    }
264
265    /**
266     * Lowers the index names of an index hint or of CACHE INDEX: a node of `opt_key_usage_list`; an absent
267     * list is empty. A list that names the primary key with PRIMARY is lowered by indexKeys().
268     *
269     * @return list<Name>
270     * @throws ImplementationGap When the list names PRIMARY or a production has no rule
271     */
272    public function indexNames(Node $list): array
273    {
274        $names = [];
275        foreach ($this->indexKeys($list) as $key) {
276            $names[] = $key instanceof Name ? $key : throw ImplementationGap::rule('an index list naming PRIMARY, which indexKeys() lowers');
277        }
278
279        return $names;
280    }
281
282    /**
283     * Lowers the indexes of an index hint or of CACHE INDEX, where PRIMARY names the primary key: a node of
284     * `opt_key_usage_list` or `key_usage_list`; an absent list is empty.
285     *
286     * @return list<Name|PrimaryIndex>
287     * @throws ImplementationGap When a production has no rule
288     */
289    public function indexKeys(Node $list): array
290    {
291        return (new TableRule($this->lowering))->indexes($list);
292    }
293}
294