packages/sql-semantics-mysql/src/Lowering/Routine/Program/BlockRule.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Lowering\Routine\Program;
6
7use SqlParser\Parser\Node;
8use SqlSemantics\Platform\MySql\Lowering\Lowering;
9use SqlSemantics\Platform\MySql\Lowering\Routine\Condition\ConditionRule;
10use SqlSemantics\Platform\MySql\Lowering\Routine\ParameterRule;
11use SqlSemantics\Platform\MySql\Lowering\Routine\Sequence;
12use SqlSemantics\Platform\MySql\Model\Diagnostic\ImplementationGap;
13use SqlSemantics\Platform\MySql\Model\Lowering\Form;
14use SqlSemantics\Platform\MySql\Model\Statement\Identifier\Name;
15use SqlSemantics\Platform\MySql\Model\Statement\Scalar;
16use SqlSemantics\Platform\MySql\Statement\Routine\Program\Block;
17use SqlSemantics\Platform\MySql\Statement\Routine\Program\ConditionDeclaration;
18use SqlSemantics\Platform\MySql\Statement\Routine\Program\Cursor\CloseCursor;
19use SqlSemantics\Platform\MySql\Statement\Routine\Program\Cursor\CursorDeclaration;
20use SqlSemantics\Platform\MySql\Statement\Routine\Program\Cursor\FetchCursor;
21use SqlSemantics\Platform\MySql\Statement\Routine\Program\Cursor\OpenCursor;
22use SqlSemantics\Platform\MySql\Statement\Routine\Program\Declaration;
23use SqlSemantics\Platform\MySql\Statement\Routine\Program\HandlerAction;
24use SqlSemantics\Platform\MySql\Statement\Routine\Program\HandlerDeclaration;
25use SqlSemantics\Platform\MySql\Statement\Routine\Program\VariableDeclaration;
26
27/**
28 * Lowers BEGIN ... END blocks, their declarations and the cursor statements.
29 *
30 * Rule: MYSQL-PROGRAM-BLOCK-LOWERING-001. Scope: sp_labeled_block,
31 * sp_unlabeled_block, sp_block_content, sp_decls, sp_decl, sp_decl_idents,
32 * sp_opt_default, sp_handler_type, sp_proc_stmt_open, sp_proc_stmt_fetch,
33 * sp_proc_stmt_close, sp_opt_fetch_noise, sp_fetch_list. The words NEXT
34 * FROM and FROM of FETCH hold no operand. Constructs: Block,
35 * VariableDeclaration, ConditionDeclaration, CursorDeclaration,
36 * HandlerDeclaration, OpenCursor, FetchCursor, CloseCursor. Terminates:
37 * every child is a strict subtree; lists are flattened iteratively.
38 * Source: https://dev.mysql.com/doc/refman/8.4/en/begin-end.html,
39 * https://dev.mysql.com/doc/refman/8.4/en/declare.html,
40 * https://dev.mysql.com/doc/refman/8.4/en/cursors.html.
41 * Status: Implemented.
42 *
43 * @visibility SqlSemantics\Platform\MySql
44 */
45final class BlockRule
46{
47    /**
48     * The handler actions.
49     */
50    private const ACTIONS = ['sp_handler_type: EXIT_SYM' => HandlerAction::Exit, 'sp_handler_type: CONTINUE_SYM' => HandlerAction::Continue];
51
52    /**
53     * The optional words of FETCH, which hold no operand.
54     */
55    private const FETCH_WORDS = ['sp_opt_fetch_noise:' => true, 'sp_opt_fetch_noise: NEXT_SYM FROM' => true, 'sp_opt_fetch_noise: FROM' => true];
56
57    /**
58     * @param Lowering $lowering The lowering this rule belongs to
59     */
60    public function __construct(private readonly Lowering $lowering)
61    {
62    }
63
64    /**
65     * Lowers a block: the form of `sp_labeled_block` or `sp_unlabeled_block`.
66     *
67     * @throws ImplementationGap When a production has no rule
68     */
69    public function block(Form $form): Block
70    {
71        [$content, $label, $end] = match ($form->signature) {
72            'sp_unlabeled_block: sp_block_content' => [$form->node(0), null, null],
73            'sp_labeled_block: label_ident : sp_block_content sp_opt_label' => [$form->node(2), $this->lowering->names->identifier($form->node(0)), (new FlowRule($this->lowering))->endLabel($form->node(3))],
74            default => throw ImplementationGap::production($form),
75        };
76        $body = $this->lowering->form($content);
77        if ($body->signature !== 'sp_block_content: BEGIN_SYM sp_decls sp_proc_stmts END') {
78            throw ImplementationGap::production($body);
79        }
80        $declarations = [];
81        foreach ((new Sequence($this->lowering))->items($body->node(1), ['sp_decls:', 'sp_decls: sp_decls sp_decl ;']) as $item) {
82            $declarations[] = $this->declaration($item);
83        }
84
85        return new Block($declarations, (new StatementRule($this->lowering))->statements($body->node(2)), $label, $end);
86    }
87
88    /**
89     * Lowers one DECLARE: a node of `sp_decl`.
90     *
91     * @throws ImplementationGap When a production has no rule
92     */
93    public function declaration(Node $declaration): Declaration
94    {
95        $form = $this->lowering->form($declaration);
96        $parameters = new ParameterRule($this->lowering);
97        switch ($form->signature) {
98            case 'sp_decl: DECLARE_SYM sp_decl_idents type_with_opt_collate sp_opt_default':
99                [$type, $collation] = $parameters->declared($form->node(2), null);
100
101                return new VariableDeclaration($this->names($form->node(1), 'sp_decl_idents'), $type, $collation, $this->initial($form->node(3)));
102            case 'sp_decl: DECLARE_SYM sp_decl_idents type opt_collate sp_opt_default':
103                [$type, $collation] = $parameters->declared($form->node(2), $form->node(3));
104
105                return new VariableDeclaration($this->names($form->node(1), 'sp_decl_idents'), $type, $collation, $this->initial($form->node(4)));
106            case 'sp_decl: DECLARE_SYM ident CONDITION_SYM FOR_SYM sp_cond':
107                return new ConditionDeclaration($this->lowering->names->identifier($form->node(1)), (new ConditionRule($this->lowering))->value($form->node(4)));
108            case 'sp_decl: DECLARE_SYM sp_handler_type HANDLER_SYM FOR_SYM sp_hcond_list sp_proc_stmt':
109                $action = $this->lowering->form($form->node(1));
110
111                return new HandlerDeclaration(
112                    self::ACTIONS[$action->signature] ?? throw ImplementationGap::production($action),
113                    (new ConditionRule($this->lowering))->handled($form->node(4)),
114                    (new StatementRule($this->lowering))->statement($form->node(5)),
115                );
116            case 'sp_decl: DECLARE_SYM ident CURSOR_SYM FOR_SYM select':
117            case 'sp_decl: DECLARE_SYM ident CURSOR_SYM FOR_SYM select_stmt':
118                return new CursorDeclaration($this->lowering->names->identifier($form->node(1)), $this->lowering->queries->query($form->node(4)));
119            default:
120                throw ImplementationGap::production($form);
121        }
122    }
123
124    /**
125     * Lowers a comma-separated list of names: a node of `sp_decl_idents` or `sp_fetch_list`.
126     *
127     * @return list<Name>
128     * @throws ImplementationGap When a production has no rule
129     */
130    public function names(Node $list, string $rule): array
131    {
132        $names = [];
133        foreach ((new Sequence($this->lowering))->items($list, $rule === 'sp_decl_idents' ? ['sp_decl_idents: ident', 'sp_decl_idents: sp_decl_idents , ident'] : ['sp_fetch_list: ident', 'sp_fetch_list: sp_fetch_list , ident']) as $item) {
134            $names[] = $this->lowering->names->identifier($item);
135        }
136
137        return $names;
138    }
139
140    /**
141     * Lowers the DEFAULT clause of a variable declaration: a node of `sp_opt_default`; an absent clause is null.
142     *
143     * @throws ImplementationGap When a production has no rule
144     */
145    public function initial(Node $default): ?Scalar
146    {
147        $form = $this->lowering->form($default);
148
149        return match ($form->signature) {
150            'sp_opt_default:' => null,
151            'sp_opt_default: DEFAULT expr', 'sp_opt_default: DEFAULT_SYM expr' => $this->lowering->expressions->expression($form->node(1)),
152            default => throw ImplementationGap::production($form),
153        };
154    }
155
156    /**
157     * Lowers OPEN, FETCH or CLOSE: the form of `sp_proc_stmt_open`, `sp_proc_stmt_fetch` or `sp_proc_stmt_close`.
158     *
159     * @throws ImplementationGap When a production has no rule
160     */
161    public function cursor(Form $form): OpenCursor|FetchCursor|CloseCursor
162    {
163        if ($form->signature === 'sp_proc_stmt_fetch: FETCH_SYM sp_opt_fetch_noise ident INTO sp_fetch_list') {
164            $words = $this->lowering->form($form->node(1));
165            if (!isset(self::FETCH_WORDS[$words->signature])) {
166                throw ImplementationGap::production($words);
167            }
168
169            return new FetchCursor($this->lowering->names->identifier($form->node(2)), $this->names($form->node(4), 'sp_fetch_list'));
170        }
171
172        return match ($form->signature) {
173            'sp_proc_stmt_open: OPEN_SYM ident' => new OpenCursor($this->lowering->names->identifier($form->node(1))),
174            'sp_proc_stmt_close: CLOSE_SYM ident' => new CloseCursor($this->lowering->names->identifier($form->node(1))),
175            default => throw ImplementationGap::production($form),
176        };
177    }
178}
179