packages/sql-semantics-mysql/src/Lowering/Query/Shared/TailRule.php
1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Lowering\Query\Shared;
6
7use SqlParser\Parser\Node;
8use SqlSemantics\Platform\MySql\Lowering\Lowering;
9use SqlSemantics\Platform\MySql\Model\Diagnostic\ImplementationGap;
10use SqlSemantics\Platform\MySql\Model\Lowering\Lists;
11use SqlSemantics\Platform\MySql\Model\Statement\Scalar;
12use SqlSemantics\Platform\MySql\Statement\Literal\NumberLiteral;
13use SqlSemantics\Platform\MySql\Statement\Query\Clause\OffsetSpelling;
14use SqlSemantics\Platform\MySql\Statement\Query\Clause\ProcedureAnalyse;
15use SqlSemantics\Platform\MySql\Statement\Query\Clause\ProgramVariable;
16use SqlSemantics\Platform\MySql\Statement\Query\Clause\RowLimit;
17use SqlSemantics\Platform\MySql\Statement\Query\Into\IntoDestination;
18use SqlSemantics\Platform\MySql\Statement\Query\Into\IntoDumpfile;
19use SqlSemantics\Platform\MySql\Statement\Query\Into\IntoOutfile;
20use SqlSemantics\Platform\MySql\Statement\Query\Into\IntoVariables;
21use SqlSemantics\Platform\MySql\Statement\Query\Locking\LockedRowAction;
22use SqlSemantics\Platform\MySql\Statement\Query\Locking\LockingClause;
23use SqlSemantics\Platform\MySql\Statement\Query\Locking\LockStrength;
24
25/**
26 * Lowers the clauses written after a query: LIMIT, PROCEDURE ANALYSE, INTO and the locking clauses.
27 *
28 * Rule: MYSQL-QUERY-TAIL-001. Scope: opt_limit_clause, opt_limit_clause_init,
29 * limit_clause, limit_options, limit_option, opt_simple_limit,
30 * procedure_analyse_clause, opt_procedure_analyse_clause,
31 * opt_procedure_analyse_params, procedure_analyse_param, into, into_clause,
32 * opt_into, into_destination, select_var_list_init, select_var_list,
33 * select_var_ident, select_lock_type, opt_select_lock_type,
34 * locking_clause_list, locking_clause, lock_strength, table_locking_list,
35 * opt_locked_row_action, locked_row_action. A LIMIT operand is an unsigned
36 * integer, a parameter marker or a stored program variable; an INTO target
37 * written with `@` is a user variable, a bare one a stored program variable.
38 * Constructs: RowLimit, ProcedureAnalyse, IntoVariables, IntoOutfile,
39 * IntoDumpfile, ProgramVariable, LockingClause. Terminates: lists are
40 * flattened iteratively. Source: https://dev.mysql.com/doc/refman/8.4/en/select.html,
41 * https://dev.mysql.com/doc/refman/8.4/en/select-into.html,
42 * https://dev.mysql.com/doc/refman/8.4/en/innodb-locking-reads.html.
43 * Status: Implemented.
44 *
45 * @visibility SqlSemantics\Platform\MySql\Lowering\Query
46 */
47final class TailRule
48{
49 /**
50 * The productions of a locked row action.
51 */
52 private const ACTIONS = ['opt_locked_row_action:' => null, 'locked_row_action: SKIP_SYM LOCKED_SYM' => LockedRowAction::SkipLocked, 'locked_row_action: NOWAIT_SYM' => LockedRowAction::Nowait];
53
54 /**
55 * The productions of the 5.x locking clause; null when absent.
56 */
57 private const LEGACY_LOCKS = [
58 'select_lock_type:' => null, 'opt_select_lock_type:' => null, 'select_lock_type: FOR_SYM UPDATE_SYM' => LockStrength::Update,
59 'opt_select_lock_type: FOR_SYM UPDATE_SYM' => LockStrength::Update, 'select_lock_type: LOCK_SYM IN_SYM SHARE_SYM MODE_SYM' => LockStrength::ShareMode,
60 'opt_select_lock_type: LOCK_SYM IN_SYM SHARE_SYM MODE_SYM' => LockStrength::ShareMode,
61 ];
62
63 /**
64 * @param Lowering $lowering The lowering this rule belongs to
65 */
66 public function __construct(private readonly Lowering $lowering)
67 {
68 }
69
70 /**
71 * Lowers a LIMIT clause; an absent clause is null.
72 *
73 * @throws ImplementationGap When a production has no rule
74 */
75 public function limit(Node $clause): ?RowLimit
76 {
77 $form = $this->lowering->form($clause);
78
79 return match ($form->signature) {
80 'opt_limit_clause:', 'opt_limit_clause_init:', 'opt_simple_limit:' => null,
81 'opt_limit_clause: limit_clause', 'opt_limit_clause_init: limit_clause' => $this->limit($form->node(0)),
82 'limit_clause: LIMIT limit_options' => $this->options($form->node(1)),
83 'opt_simple_limit: LIMIT limit_option' => new RowLimit($this->value($form->node(1))),
84 default => throw ImplementationGap::production($form),
85 };
86 }
87
88 /**
89 * Lowers the operands of a LIMIT clause.
90 *
91 * @throws ImplementationGap When a production has no rule
92 */
93 public function options(Node $options): RowLimit
94 {
95 $form = $this->lowering->form($options);
96
97 return match ($form->signature) {
98 'limit_options: limit_option' => new RowLimit($this->value($form->node(0))),
99 'limit_options: limit_option , limit_option' => new RowLimit($this->value($form->node(2)), $this->value($form->node(0)), OffsetSpelling::Comma),
100 'limit_options: limit_option OFFSET_SYM limit_option' => new RowLimit($this->value($form->node(0)), $this->value($form->node(2)), OffsetSpelling::Keyword),
101 default => throw ImplementationGap::production($form),
102 };
103 }
104
105 /**
106 * Lowers one LIMIT operand.
107 *
108 * @throws ImplementationGap When the production has no rule
109 */
110 public function value(Node $option): Scalar
111 {
112 $form = $this->lowering->form($option);
113
114 return match ($form->signature) {
115 'limit_option: ident' => new ProgramVariable($this->lowering->names->identifier($form->node(0))),
116 'limit_option: param_marker' => $this->lowering->literals->parameter($form->node(0)),
117 'limit_option: ULONGLONG_NUM', 'limit_option: LONG_NUM', 'limit_option: NUM' => $this->lowering->leaves->record(new NumberLiteral($form->token(0)->text)),
118 default => throw ImplementationGap::production($form),
119 };
120 }
121
122 /**
123 * Lowers a PROCEDURE ANALYSE clause; an absent clause is null.
124 *
125 * @throws ImplementationGap When a production has no rule
126 */
127 public function procedure(Node $clause): ?ProcedureAnalyse
128 {
129 $form = $this->lowering->form($clause);
130 if ($form->signature === 'procedure_analyse_clause:' || $form->signature === 'opt_procedure_analyse_clause:') {
131 return null;
132 }
133 if ($form->signature !== 'procedure_analyse_clause: PROCEDURE_SYM ANALYSE_SYM ( opt_procedure_analyse_params )' && $form->signature !== 'opt_procedure_analyse_clause: PROCEDURE_SYM ANALYSE_SYM ( opt_procedure_analyse_params )') {
134 throw ImplementationGap::production($form);
135 }
136 $params = $this->lowering->form($form->node(3));
137 $positions = match ($params->signature) {
138 'opt_procedure_analyse_params:' => [],
139 'opt_procedure_analyse_params: procedure_analyse_param' => [0],
140 'opt_procedure_analyse_params: procedure_analyse_param , procedure_analyse_param' => [0, 2],
141 default => throw ImplementationGap::production($params),
142 };
143 $arguments = [];
144 foreach ($positions as $position) {
145 $param = $this->lowering->form($params->node($position));
146 if ($param->signature !== 'procedure_analyse_param: NUM') {
147 throw ImplementationGap::production($param);
148 }
149 $arguments[] = $this->lowering->leaves->record(new NumberLiteral($param->token(0)->text));
150 }
151
152 return new ProcedureAnalyse($arguments);
153 }
154
155 /**
156 * Lowers an INTO clause; an absent clause is null.
157 *
158 * @throws ImplementationGap When a production has no rule
159 */
160 public function into(Node $clause): ?IntoDestination
161 {
162 $form = $this->lowering->form($clause);
163
164 return match ($form->signature) {
165 'opt_into:' => null,
166 'opt_into: into' => $this->into($form->node(0)),
167 'into: INTO into_destination', 'into_clause: INTO into_destination' => $this->destination($form->node(1)),
168 default => throw ImplementationGap::production($form),
169 };
170 }
171
172 /**
173 * Lowers the destination of an INTO clause.
174 *
175 * @throws ImplementationGap When a production has no rule
176 */
177 public function destination(Node $destination): IntoDestination
178 {
179 $form = $this->lowering->form($destination);
180
181 return match ($form->signature) {
182 'into_destination: OUTFILE TEXT_STRING_filesystem opt_load_data_charset opt_field_term opt_line_term' => new IntoOutfile($this->lowering->literals->text($form->node(1)), $this->lowering->dml->fileFormat($form->node(2), $form->node(3), $form->node(4))),
183 'into_destination: DUMPFILE TEXT_STRING_filesystem' => new IntoDumpfile($this->lowering->literals->text($form->node(1))),
184 'into_destination: select_var_list_init' => $this->destination($form->node(0)),
185 'select_var_list_init: select_var_list', 'into_destination: select_var_list' => $this->variables($form->node(0)),
186 default => throw ImplementationGap::production($form),
187 };
188 }
189
190 /**
191 * Lowers the variables of an INTO clause in written order.
192 *
193 * @throws ImplementationGap When a production has no rule
194 */
195 public function variables(Node $list): IntoVariables
196 {
197 $form = $this->lowering->form($list);
198 if ($form->signature !== 'select_var_list: select_var_list , select_var_ident' && $form->signature !== 'select_var_list: select_var_ident') {
199 throw ImplementationGap::production($form);
200 }
201 $targets = [];
202 foreach ((new Lists())->items($list) as $item) {
203 $target = $this->lowering->form($item);
204 $targets[] = match ($target->signature) {
205 'select_var_ident: @ ident_or_text' => $this->lowering->variables->user($target->node(1)),
206 'select_var_ident: ident_or_text' => new ProgramVariable($this->lowering->names->identifier($target->node(0))),
207 default => throw ImplementationGap::production($target),
208 };
209 }
210
211 return new IntoVariables($targets);
212 }
213
214 /**
215 * Lowers the locking clause of the 5.x grammars or the locking clause list of 8.0 and later; an absent clause is empty.
216 *
217 * @return list<LockingClause>
218 * @throws ImplementationGap When a production has no rule
219 */
220 public function locking(Node $clause): array
221 {
222 $form = $this->lowering->form($clause);
223 if (array_key_exists($form->signature, self::LEGACY_LOCKS)) {
224 $strength = self::LEGACY_LOCKS[$form->signature];
225
226 return $strength === null ? [] : [new LockingClause($strength)];
227 }
228 if ($form->signature !== 'locking_clause_list: locking_clause_list locking_clause' && $form->signature !== 'locking_clause_list: locking_clause') {
229 throw ImplementationGap::production($form);
230 }
231 $clauses = [];
232 foreach ((new Lists())->items($clause) as $item) {
233 $clauses[] = $this->lock($item);
234 }
235
236 return $clauses;
237 }
238
239 /**
240 * Lowers one locking clause of 8.0 and later.
241 *
242 * @throws ImplementationGap When a production has no rule
243 */
244 public function lock(Node $clause): LockingClause
245 {
246 $form = $this->lowering->form($clause);
247 if ($form->signature === 'locking_clause: LOCK_SYM IN_SYM SHARE_SYM MODE_SYM') {
248 return new LockingClause(LockStrength::ShareMode);
249 }
250 $tables = [];
251 $wildcards = [];
252 if ($form->signature === 'locking_clause: FOR_SYM lock_strength table_locking_list opt_locked_row_action') {
253 $list = $this->lowering->form($form->node(2));
254 if ($list->signature !== 'table_locking_list: OF_SYM table_alias_ref_list') {
255 throw ImplementationGap::production($list);
256 }
257 $tables = $this->lowering->dml->deleteTargets($list->node(1));
258 $wildcards = $this->lowering->dml->wildcards($list->node(1));
259 } elseif ($form->signature !== 'locking_clause: FOR_SYM lock_strength opt_locked_row_action') {
260 throw ImplementationGap::production($form);
261 }
262 $strength = $this->lowering->form($form->node(1));
263 $action = $this->lowering->form($form->node(count($form->node->children) - 1));
264 if ($action->signature === 'opt_locked_row_action: locked_row_action') {
265 $action = $this->lowering->form($action->node(0));
266 }
267 if (!array_key_exists($action->signature, self::ACTIONS)) {
268 throw ImplementationGap::production($action);
269 }
270
271 return new LockingClause(match ($strength->signature) {
272 'lock_strength: UPDATE_SYM' => LockStrength::Update,
273 'lock_strength: SHARE_SYM' => LockStrength::Share,
274 default => throw ImplementationGap::production($strength),
275 }, $tables, self::ACTIONS[$action->signature], $wildcards);
276 }
277}
278