packages/sql-semantics-mysql/tests/Unit/Statement/Routine/Program/Flow/IterateTest.php
1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Routine\Program\Flow;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\DataProvider;
9use PHPUnit\Framework\Attributes\Medium;
10use PHPUnit\Framework\TestCase;
11use SqlSemantics\Platform\MySql\Model\Statement\Fact\Diagnostic;
12use SqlSemantics\Platform\MySql\Semantics;
13use SqlSemantics\Platform\MySql\Statement\Routine\Program\Flow\Iterate;
14
15#[CoversClass(Iterate::class)]
16#[Medium]
17final class IterateTest extends TestCase
18{
19 /**
20 * @param list<string> $messages
21 */
22 #[DataProvider('providerDeriveProgramRequiresAnEnclosingLoop')]
23 public function testDeriveProgramRequiresAnEnclosingLoop(string $sql, array $messages): void
24 {
25 $operation = (new Semantics())->inspect($sql);
26
27 self::assertSame($messages, array_map(static fn (Diagnostic $diagnostic): string => $diagnostic->message(), $operation->facts->diagnostics));
28 }
29
30 /**
31 * @return iterable<string, array{string, list<string>}>
32 */
33 public static function providerDeriveProgramRequiresAnEnclosingLoop(): iterable
34 {
35 yield 'the label of a LOOP' => ['CREATE PROCEDURE p() again: LOOP ITERATE again; END LOOP', []];
36 yield 'the label of a WHILE' => ['CREATE PROCEDURE p(a INT) w: WHILE a > 0 DO ITERATE w; END WHILE w', []];
37 yield 'the label of a REPEAT' => ['CREATE PROCEDURE p(a INT) r: REPEAT ITERATE r; UNTIL a > 0 END REPEAT r', []];
38 yield 'the label of an outer loop' => ['CREATE PROCEDURE p() o: LOOP i: LOOP ITERATE O; END LOOP; END LOOP', []];
39 yield 'the label of a block' => ['CREATE PROCEDURE p() b: BEGIN l: LOOP ITERATE b; END LOOP; END', ['ITERATE with no matching label: b']];
40 yield 'the label of a closed loop' => ['CREATE PROCEDURE p() b: BEGIN l: LOOP LEAVE b; END LOOP; ITERATE l; END', ['ITERATE with no matching label: l']];
41 yield 'no label' => ['CREATE PROCEDURE p() ITERATE zz', ['ITERATE with no matching label: zz']];
42 }
43
44 #[DataProvider('providerRenderWritesTheStatement')]
45 public function testRenderWritesTheStatement(string $release, string $sql, string $expected): void
46 {
47 self::assertSame($expected, (new Semantics($release))->inspect($sql)->toString());
48 }
49
50 /**
51 * @return iterable<string, array{string, string, string}>
52 */
53 public static function providerRenderWritesTheStatement(): iterable
54 {
55 yield '5.7' => ['mysql-5.7.44', 'create procedure p() l: loop iterate l; end loop', 'CREATE PROCEDURE p() l: LOOP ITERATE l; END LOOP'];
56 yield 'a quoted label in 9.1' => ['mysql-9.1.0', 'create procedure p() `my label`: loop iterate `my label`; end loop', 'CREATE PROCEDURE p() `my label`: LOOP ITERATE `my label`; END LOOP'];
57 }
58}
59