packages/sql-semantics-mysql/tests/Unit/Lowering/Routine/Program/FlowRuleTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Lowering\Routine\Program;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\DataProvider;
9use PHPUnit\Framework\Attributes\Medium;
10use PHPUnit\Framework\TestCase;
11use SqlParser\Parser\Node;
12use SqlSemantics\Platform\MySql\Lowering\Lowering;
13use SqlSemantics\Platform\MySql\Lowering\Routine\Program\FlowRule;
14use SqlSemantics\Platform\MySql\Model\Contract\ParameterStyle;
15use SqlSemantics\Platform\MySql\Model\Lowering\Form;
16use SqlSemantics\Platform\MySql\Model\Lowering\Leaves;
17use SqlSemantics\Platform\MySql\Model\Statement\Identifier\Name;
18use SqlSemantics\Platform\MySql\Platform;
19use SqlSemantics\Platform\MySql\Semantics;
20use SqlSemantics\Platform\MySql\Statement\Expression\Comparison;
21use SqlSemantics\Platform\MySql\Statement\Expression\ComparisonOperator;
22use SqlSemantics\Platform\MySql\Statement\Expression\Operator\Arithmetic;
23use SqlSemantics\Platform\MySql\Statement\Expression\Operator\ArithmeticOperator;
24use SqlSemantics\Platform\MySql\Statement\Literal\NumberLiteral;
25use SqlSemantics\Platform\MySql\Statement\Name\ColumnUse;
26use SqlSemantics\Platform\MySql\Statement\Routine\CreateFunction;
27use SqlSemantics\Platform\MySql\Statement\Routine\CreateProcedure;
28use SqlSemantics\Platform\MySql\Statement\Routine\Program\Block;
29use SqlSemantics\Platform\MySql\Statement\Routine\Program\Flow\ConditionalBranch;
30use SqlSemantics\Platform\MySql\Statement\Routine\Program\Flow\IfStatement;
31use SqlSemantics\Platform\MySql\Statement\Routine\Program\Flow\Iterate;
32use SqlSemantics\Platform\MySql\Statement\Routine\Program\Flow\Leave;
33use SqlSemantics\Platform\MySql\Statement\Routine\Program\Flow\Loop;
34use SqlSemantics\Platform\MySql\Statement\Routine\Program\Flow\RepeatLoop;
35use SqlSemantics\Platform\MySql\Statement\Routine\Program\Flow\ReturnStatement;
36use SqlSemantics\Platform\MySql\Statement\Routine\Program\Flow\SearchedCase;
37use SqlSemantics\Platform\MySql\Statement\Routine\Program\Flow\SimpleCase;
38use SqlSemantics\Platform\MySql\Statement\Routine\Program\Flow\WhileLoop;
39use SqlSemantics\Platform\MySql\Statement\Utility\Set\NameAssignment;
40use SqlSemantics\Platform\MySql\Statement\Utility\Set\SetVariables;
41
42#[CoversClass(FlowRule::class)]
43#[Medium]
44final class FlowRuleTest extends TestCase
45{
46    /**
47     * @return iterable<string, array{string}>
48     */
49    public static function providerConditionalLowersTheBranchesAndTheElse(): iterable
50    {
51        yield 'mysql 5.6' => ['mysql-5.6.51'];
52        yield 'mysql 5.7' => ['mysql-5.7.44'];
53        yield 'mysql 8.0' => ['mysql-8.0.44'];
54        yield 'mysql 9.1' => ['mysql-9.1.0'];
55    }
56
57    #[DataProvider('providerConditionalLowersTheBranchesAndTheElse')]
58    public function testConditionalLowersTheBranchesAndTheElse(string $release): void
59    {
60        $operation = (new Semantics($release))->analyze('create procedure p(x int) if x = 1 then set @a = 1; set @a = 2; elseif x = 2 then set @a = 3; elseif x = 3 then set @a = 4; else set @a = 5; end if');
61        $statement = $operation->statement;
62        self::assertInstanceOf(CreateProcedure::class, $statement);
63        $conditional = $statement->body;
64        self::assertInstanceOf(IfStatement::class, $conditional);
65
66        self::assertCount(3, $conditional->branches);
67        self::assertEquals(new Comparison(ComparisonOperator::Equal, new ColumnUse(new Name('x')), new NumberLiteral('1')), $conditional->branches[0]->condition);
68        self::assertEquals(new Comparison(ComparisonOperator::Equal, new ColumnUse(new Name('x')), new NumberLiteral('3')), $conditional->branches[2]->condition);
69        self::assertCount(2, $conditional->branches[0]->statements);
70        self::assertCount(1, $conditional->branches[1]->statements);
71        self::assertCount(1, $conditional->otherwise);
72        self::assertContainsOnlyInstancesOf(SetVariables::class, $conditional->otherwise);
73        self::assertSame('CREATE PROCEDURE p(x INT) IF x = 1 THEN SET @a = 1; SET @a = 2; ELSEIF x = 2 THEN SET @a = 3; ELSEIF x = 3 THEN SET @a = 4; ELSE SET @a = 5; END IF', $operation->toString());
74        self::assertSame([], $operation->facts->diagnostics);
75    }
76
77    /**
78     * @return iterable<string, array{string, string, int, string}>
79     */
80    public static function providerConditionalLowersAnIfWithoutElse(): iterable
81    {
82        yield 'one branch in 5.6' => ['mysql-5.6.51', 'if x then leave b; end if', 1, 'IF x THEN LEAVE b; END IF'];
83        yield 'two branches in 8.0' => ['mysql-8.0.44', 'if x then leave b; elseif x > 1 then leave b; end if', 2, 'IF x THEN LEAVE b; ELSEIF x > 1 THEN LEAVE b; END IF'];
84        yield 'two branches in 9.1' => ['mysql-9.1.0', 'if x then leave b; elseif x > 1 then leave b; end if', 2, 'IF x THEN LEAVE b; ELSEIF x > 1 THEN LEAVE b; END IF'];
85    }
86
87    #[DataProvider('providerConditionalLowersAnIfWithoutElse')]
88    public function testConditionalLowersAnIfWithoutElse(string $release, string $sql, int $branches, string $rendering): void
89    {
90        $operation = (new Semantics($release))->analyze('create procedure p(x int) b: begin ' . $sql . '; end');
91        $statement = $operation->statement;
92        self::assertInstanceOf(CreateProcedure::class, $statement);
93        self::assertInstanceOf(Block::class, $statement->body);
94        $conditional = $statement->body->statements[0];
95        self::assertInstanceOf(IfStatement::class, $conditional);
96
97        self::assertCount($branches, $conditional->branches);
98        self::assertEquals(new ConditionalBranch(new ColumnUse(new Name('x')), [new Leave(new Name('b'))]), $conditional->branches[0]);
99        self::assertSame([], $conditional->otherwise);
100        self::assertSame('CREATE PROCEDURE p(x INT) b: BEGIN ' . $rendering . '; END', $operation->toString());
101    }
102
103    public function testConditionalRefusesAnotherProduction(): void
104    {
105        $platform = new Platform();
106        $profile = $platform->profile(null, null, ParameterStyle::Native);
107        $rule = new FlowRule(new Lowering($platform->productions($profile), new Leaves(), $profile));
108
109        $this->expectExceptionMessage('No semantic rule is implemented for: rule: IF x');
110
111        $rule->conditional(new Form(new Node('rule', 0, []), 'rule: IF x'));
112    }
113
114    /**
115     * @return iterable<string, array{string}>
116     */
117    public static function providerChoiceLowersASimpleCase(): iterable
118    {
119        yield 'mysql 5.6' => ['mysql-5.6.51'];
120        yield 'mysql 5.7' => ['mysql-5.7.44'];
121        yield 'mysql 8.0' => ['mysql-8.0.44'];
122        yield 'mysql 9.1' => ['mysql-9.1.0'];
123    }
124
125    #[DataProvider('providerChoiceLowersASimpleCase')]
126    public function testChoiceLowersASimpleCase(string $release): void
127    {
128        $operation = (new Semantics($release))->analyze('create procedure p(x int) case x when 1 then set x = 2; when 2 then set x = 3; set x = 4; else set x = 5; end case');
129        $statement = $operation->statement;
130        self::assertInstanceOf(CreateProcedure::class, $statement);
131
132        self::assertEquals(new SimpleCase(new ColumnUse(new Name('x')), [
133            new ConditionalBranch(new NumberLiteral('1'), [new SetVariables([new NameAssignment(new Name('x'), new NumberLiteral('2'))])]),
134            new ConditionalBranch(new NumberLiteral('2'), [new SetVariables([new NameAssignment(new Name('x'), new NumberLiteral('3'))]), new SetVariables([new NameAssignment(new Name('x'), new NumberLiteral('4'))])]),
135        ], [new SetVariables([new NameAssignment(new Name('x'), new NumberLiteral('5'))])]), $statement->body);
136        self::assertSame('CREATE PROCEDURE p(x INT) CASE x WHEN 1 THEN SET x = 2; WHEN 2 THEN SET x = 3; SET x = 4; ELSE SET x = 5; END CASE', $operation->toString());
137        self::assertSame([], $operation->facts->diagnostics);
138    }
139
140    /**
141     * @return iterable<string, array{string}>
142     */
143    public static function providerChoiceLowersASearchedCase(): iterable
144    {
145        yield 'mysql 5.6' => ['mysql-5.6.51'];
146        yield 'mysql 5.7' => ['mysql-5.7.44'];
147        yield 'mysql 8.0' => ['mysql-8.0.44'];
148        yield 'mysql 9.1' => ['mysql-9.1.0'];
149    }
150
151    #[DataProvider('providerChoiceLowersASearchedCase')]
152    public function testChoiceLowersASearchedCase(string $release): void
153    {
154        $operation = (new Semantics($release))->analyze('create procedure p(x int) case when x > 1 then set x = 0; end case');
155        $statement = $operation->statement;
156        self::assertInstanceOf(CreateProcedure::class, $statement);
157
158        self::assertEquals(new SearchedCase([
159            new ConditionalBranch(new Comparison(ComparisonOperator::Greater, new ColumnUse(new Name('x')), new NumberLiteral('1')), [new SetVariables([new NameAssignment(new Name('x'), new NumberLiteral('0'))])]),
160        ]), $statement->body);
161        self::assertSame('CREATE PROCEDURE p(x INT) CASE WHEN x > 1 THEN SET x = 0; END CASE', $operation->toString());
162    }
163
164    /**
165     * @return iterable<string, array{string, string, Loop|WhileLoop|RepeatLoop, string}>
166     */
167    public static function providerLabeledLowersALabeledLoop(): iterable
168    {
169        yield 'a loop with both labels in 5.6' => ['mysql-5.6.51', 'l: loop leave l; end loop l', new Loop([new Leave(new Name('l'))], new Name('l'), new Name('l')), 'l: LOOP LEAVE l; END LOOP l'];
170        yield 'a while loop with both labels in 5.7' => ['mysql-5.7.44', 'l: while 1 do iterate l; end while l', new WhileLoop(new NumberLiteral('1'), [new Iterate(new Name('l'))], new Name('l'), new Name('l')), 'l: WHILE 1 DO ITERATE l; END WHILE l'];
171        yield 'a repeat loop with a label in 8.0' => ['mysql-8.0.44', 'l: repeat leave l; until 1 end repeat', new RepeatLoop(new NumberLiteral('1'), [new Leave(new Name('l'))], new Name('l')), 'l: REPEAT LEAVE l; UNTIL 1 END REPEAT'];
172        yield 'a while loop with a label in 9.1' => ['mysql-9.1.0', 'l: while 1 do leave l; end while', new WhileLoop(new NumberLiteral('1'), [new Leave(new Name('l'))], new Name('l')), 'l: WHILE 1 DO LEAVE l; END WHILE'];
173    }
174
175    #[DataProvider('providerLabeledLowersALabeledLoop')]
176    public function testLabeledLowersALabeledLoop(string $release, string $sql, Loop|WhileLoop|RepeatLoop $expected, string $rendering): void
177    {
178        $operation = (new Semantics($release))->analyze('create procedure p() ' . $sql);
179        self::assertInstanceOf(CreateProcedure::class, $operation->statement);
180
181        self::assertEquals($expected, $operation->statement->body);
182        self::assertSame('CREATE PROCEDURE p() ' . $rendering, $operation->toString());
183        self::assertSame([], $operation->facts->diagnostics);
184    }
185
186    /**
187     * @return iterable<string, array{string, string, Name|null, string}>
188     */
189    public static function providerEndLabelLowersTheLabelAfterEnd(): iterable
190    {
191        yield 'written in 5.6' => ['mysql-5.6.51', 'l: repeat leave l; until 1 end repeat l', new Name('l'), 'l: REPEAT LEAVE l; UNTIL 1 END REPEAT l'];
192        yield 'absent in 5.7' => ['mysql-5.7.44', 'l: repeat leave l; until 1 end repeat', null, 'l: REPEAT LEAVE l; UNTIL 1 END REPEAT'];
193        yield 'written in 9.1' => ['mysql-9.1.0', 'l: repeat leave l; until 1 end repeat l', new Name('l'), 'l: REPEAT LEAVE l; UNTIL 1 END REPEAT l'];
194    }
195
196    #[DataProvider('providerEndLabelLowersTheLabelAfterEnd')]
197    public function testEndLabelLowersTheLabelAfterEnd(string $release, string $sql, ?Name $endLabel, string $rendering): void
198    {
199        $operation = (new Semantics($release))->analyze('create procedure p() ' . $sql);
200        self::assertInstanceOf(CreateProcedure::class, $operation->statement);
201        $loop = $operation->statement->body;
202        self::assertInstanceOf(RepeatLoop::class, $loop);
203
204        self::assertEquals($endLabel, $loop->endLabel);
205        self::assertSame('CREATE PROCEDURE p() ' . $rendering, $operation->toString());
206    }
207
208    /**
209     * @return iterable<string, array{string}>
210     */
211    public static function providerLoopLowersLoopWhileAndRepeat(): iterable
212    {
213        yield 'mysql 5.6' => ['mysql-5.6.51'];
214        yield 'mysql 5.7' => ['mysql-5.7.44'];
215        yield 'mysql 8.0' => ['mysql-8.0.44'];
216        yield 'mysql 9.1' => ['mysql-9.1.0'];
217    }
218
219    #[DataProvider('providerLoopLowersLoopWhileAndRepeat')]
220    public function testLoopLowersLoopWhileAndRepeat(string $release): void
221    {
222        $operation = (new Semantics($release))->analyze('create procedure p(x int) begin while x > 0 do set x = x - 1; end while; repeat set x = x + 1; until x > 9 end repeat; loop set x = 0; end loop; end');
223        $statement = $operation->statement;
224        self::assertInstanceOf(CreateProcedure::class, $statement);
225        self::assertInstanceOf(Block::class, $statement->body);
226        $x = new ColumnUse(new Name('x'));
227
228        self::assertEquals([
229            new WhileLoop(new Comparison(ComparisonOperator::Greater, $x, new NumberLiteral('0')), [new SetVariables([new NameAssignment(new Name('x'), new Arithmetic(ArithmeticOperator::Minus, $x, new NumberLiteral('1')))])]),
230            new RepeatLoop(new Comparison(ComparisonOperator::Greater, $x, new NumberLiteral('9')), [new SetVariables([new NameAssignment(new Name('x'), new Arithmetic(ArithmeticOperator::Plus, $x, new NumberLiteral('1')))])]),
231            new Loop([new SetVariables([new NameAssignment(new Name('x'), new NumberLiteral('0'))])]),
232        ], $statement->body->statements);
233        self::assertSame('CREATE PROCEDURE p(x INT) BEGIN WHILE x > 0 DO SET x = x - 1; END WHILE; REPEAT SET x = x + 1; UNTIL x > 9 END REPEAT; LOOP SET x = 0; END LOOP; END', $operation->toString());
234        self::assertSame([], $operation->facts->diagnostics);
235    }
236
237    /**
238     * @return iterable<string, array{string}>
239     */
240    public static function providerJumpLowersReturnLeaveAndIterate(): iterable
241    {
242        yield 'mysql 5.6' => ['mysql-5.6.51'];
243        yield 'mysql 5.7' => ['mysql-5.7.44'];
244        yield 'mysql 8.0' => ['mysql-8.0.44'];
245        yield 'mysql 9.1' => ['mysql-9.1.0'];
246    }
247
248    #[DataProvider('providerJumpLowersReturnLeaveAndIterate')]
249    public function testJumpLowersReturnLeaveAndIterate(string $release): void
250    {
251        $operation = (new Semantics($release))->analyze('create function f(x int) returns int begin l: loop if x > 0 then leave l; end if; iterate l; end loop; return x + 1; end');
252        $statement = $operation->statement;
253        self::assertInstanceOf(CreateFunction::class, $statement);
254        self::assertInstanceOf(Block::class, $statement->body);
255        $x = new ColumnUse(new Name('x'));
256
257        self::assertEquals([
258            new Loop([new IfStatement([new ConditionalBranch(new Comparison(ComparisonOperator::Greater, $x, new NumberLiteral('0')), [new Leave(new Name('l'))])]), new Iterate(new Name('l'))], new Name('l')),
259            new ReturnStatement(new Arithmetic(ArithmeticOperator::Plus, $x, new NumberLiteral('1'))),
260        ], $statement->body->statements);
261        self::assertSame('CREATE FUNCTION f(x INT) RETURNS INT BEGIN l: LOOP IF x > 0 THEN LEAVE l; END IF; ITERATE l; END LOOP; RETURN x + 1; END', $operation->toString());
262        self::assertSame([], $operation->facts->diagnostics);
263    }
264}
265