packages/sql-semantics-mysql/tests/Unit/Lowering/Routine/Program/BlockRuleTest.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\BlockRule;
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\Operator\Arithmetic;
21use SqlSemantics\Platform\MySql\Statement\Expression\Operator\ArithmeticOperator;
22use SqlSemantics\Platform\MySql\Statement\Literal\NumberLiteral;
23use SqlSemantics\Platform\MySql\Statement\Literal\StringLiteral;
24use SqlSemantics\Platform\MySql\Statement\Literal\Text;
25use SqlSemantics\Platform\MySql\Statement\Name\CollationName;
26use SqlSemantics\Platform\MySql\Statement\Query\Select;
27use SqlSemantics\Platform\MySql\Statement\Query\Set\SetOperation;
28use SqlSemantics\Platform\MySql\Statement\Routine\Condition\ConditionClass;
29use SqlSemantics\Platform\MySql\Statement\Routine\Condition\GeneralCondition;
30use SqlSemantics\Platform\MySql\Statement\Routine\Condition\SqlState;
31use SqlSemantics\Platform\MySql\Statement\Routine\CreateProcedure;
32use SqlSemantics\Platform\MySql\Statement\Routine\Program\Block;
33use SqlSemantics\Platform\MySql\Statement\Routine\Program\ConditionDeclaration;
34use SqlSemantics\Platform\MySql\Statement\Routine\Program\Cursor\CloseCursor;
35use SqlSemantics\Platform\MySql\Statement\Routine\Program\Cursor\CursorDeclaration;
36use SqlSemantics\Platform\MySql\Statement\Routine\Program\Cursor\FetchCursor;
37use SqlSemantics\Platform\MySql\Statement\Routine\Program\Cursor\OpenCursor;
38use SqlSemantics\Platform\MySql\Statement\Routine\Program\Flow\Leave;
39use SqlSemantics\Platform\MySql\Statement\Routine\Program\HandlerAction;
40use SqlSemantics\Platform\MySql\Statement\Routine\Program\HandlerDeclaration;
41use SqlSemantics\Platform\MySql\Statement\Routine\Program\VariableDeclaration;
42use SqlSemantics\Platform\MySql\Statement\Type\Character;
43use SqlSemantics\Platform\MySql\Statement\Type\Integral;
44use SqlSemantics\Platform\MySql\Statement\Type\Kind\CharacterKind;
45use SqlSemantics\Platform\MySql\Statement\Type\Kind\IntegralKind;
46use SqlSemantics\Platform\MySql\Statement\Utility\Set\NameAssignment;
47use SqlSemantics\Platform\MySql\Statement\Utility\Set\SetVariables;
48
49#[CoversClass(BlockRule::class)]
50#[Medium]
51final class BlockRuleTest extends TestCase
52{
53    /**
54     * @return iterable<string, array{string}>
55     */
56    public static function providerBlockLowersAnUnlabeledBlock(): iterable
57    {
58        yield 'mysql 5.6' => ['mysql-5.6.51'];
59        yield 'mysql 5.7' => ['mysql-5.7.44'];
60        yield 'mysql 8.0' => ['mysql-8.0.44'];
61        yield 'mysql 9.1' => ['mysql-9.1.0'];
62    }
63
64    #[DataProvider('providerBlockLowersAnUnlabeledBlock')]
65    public function testBlockLowersAnUnlabeledBlock(string $release): void
66    {
67        $semantics = new Semantics($release);
68        $empty = $semantics->analyze('create procedure p() begin end');
69        self::assertInstanceOf(CreateProcedure::class, $empty->statement);
70        self::assertEquals(new Block(), $empty->statement->body);
71        self::assertSame('CREATE PROCEDURE p() BEGIN END', $empty->toString());
72
73        $full = $semantics->analyze('create procedure p() begin declare x int; set x = 1; set x = 2; end');
74        self::assertInstanceOf(CreateProcedure::class, $full->statement);
75        self::assertEquals(new Block(
76            [new VariableDeclaration([new Name('x')], new Integral(IntegralKind::Int))],
77            [new SetVariables([new NameAssignment(new Name('x'), new NumberLiteral('1'))]), new SetVariables([new NameAssignment(new Name('x'), new NumberLiteral('2'))])],
78        ), $full->statement->body);
79        self::assertSame('CREATE PROCEDURE p() BEGIN DECLARE x INT; SET x = 1; SET x = 2; END', $full->toString());
80    }
81
82    /**
83     * @return iterable<string, array{string, string, Name|null, string}>
84     */
85    public static function providerBlockLowersALabeledBlock(): iterable
86    {
87        yield 'with the end label in 5.6' => ['mysql-5.6.51', 'create procedure p() b: begin leave b; end b', new Name('b'), 'CREATE PROCEDURE p() b: BEGIN LEAVE b; END b'];
88        yield 'without the end label in 5.7' => ['mysql-5.7.44', 'create procedure p() b: begin leave b; end', null, 'CREATE PROCEDURE p() b: BEGIN LEAVE b; END'];
89        yield 'with the end label in 8.0' => ['mysql-8.0.44', 'create procedure p() b: begin leave b; end b', new Name('b'), 'CREATE PROCEDURE p() b: BEGIN LEAVE b; END b'];
90        yield 'without the end label in 9.1' => ['mysql-9.1.0', 'create procedure p() b: begin leave b; end', null, 'CREATE PROCEDURE p() b: BEGIN LEAVE b; END'];
91    }
92
93    #[DataProvider('providerBlockLowersALabeledBlock')]
94    public function testBlockLowersALabeledBlock(string $release, string $sql, ?Name $endLabel, string $rendering): void
95    {
96        $operation = (new Semantics($release))->analyze($sql);
97        self::assertInstanceOf(CreateProcedure::class, $operation->statement);
98
99        self::assertEquals(new Block([], [new Leave(new Name('b'))], new Name('b'), $endLabel), $operation->statement->body);
100        self::assertSame($rendering, $operation->toString());
101        self::assertSame([], $operation->facts->diagnostics);
102    }
103
104    public function testBlockRefusesAnotherProduction(): void
105    {
106        $platform = new Platform();
107        $profile = $platform->profile(null, null, ParameterStyle::Native);
108        $rule = new BlockRule(new Lowering($platform->productions($profile), new Leaves(), $profile));
109
110        $this->expectExceptionMessage('No semantic rule is implemented for: rule: BEGIN x');
111
112        $rule->block(new Form(new Node('rule', 0, []), 'rule: BEGIN x'));
113    }
114
115    /**
116     * @return iterable<string, array{string}>
117     */
118    public static function providerDeclarationLowersAVariableWithItsCollationAndDefault(): iterable
119    {
120        yield 'mysql 5.6' => ['mysql-5.6.51'];
121        yield 'mysql 5.7' => ['mysql-5.7.44'];
122        yield 'mysql 8.0' => ['mysql-8.0.44'];
123        yield 'mysql 9.1' => ['mysql-9.1.0'];
124    }
125
126    #[DataProvider('providerDeclarationLowersAVariableWithItsCollationAndDefault')]
127    public function testDeclarationLowersAVariableWithItsCollationAndDefault(string $release): void
128    {
129        $operation = (new Semantics($release))->analyze("create procedure p() begin declare s varchar(5) collate utf8mb4_bin default 'a'; end");
130        $statement = $operation->statement;
131        self::assertInstanceOf(CreateProcedure::class, $statement);
132        self::assertInstanceOf(Block::class, $statement->body);
133
134        self::assertEquals([new VariableDeclaration([new Name('s')], new Character(CharacterKind::VarChar, '5'), new CollationName(new Name('utf8mb4_bin')), new StringLiteral(['a']))], $statement->body->declarations);
135        self::assertSame("CREATE PROCEDURE p() BEGIN DECLARE s VARCHAR(5) COLLATE utf8mb4_bin DEFAULT 'a'; END", $operation->toString());
136    }
137
138    /**
139     * @return iterable<string, array{string, string, class-string, string}>
140     */
141    public static function providerDeclarationLowersACursor(): iterable
142    {
143        yield 'a select in 5.6' => ['mysql-5.6.51', 'select 1', Select::class, 'SELECT 1'];
144        yield 'a union in 5.7' => ['mysql-5.7.44', 'select 1 union select 2', SetOperation::class, 'SELECT 1 UNION SELECT 2'];
145        yield 'a select in 8.0' => ['mysql-8.0.44', 'select 1', Select::class, 'SELECT 1'];
146        yield 'a union in 9.1' => ['mysql-9.1.0', 'select 1 union select 2', SetOperation::class, 'SELECT 1 UNION SELECT 2'];
147    }
148
149    /**
150     * @param class-string $class
151     */
152    #[DataProvider('providerDeclarationLowersACursor')]
153    public function testDeclarationLowersACursor(string $release, string $query, string $class, string $rendering): void
154    {
155        $operation = (new Semantics($release))->analyze('create procedure p() begin declare c cursor for ' . $query . '; end');
156        $statement = $operation->statement;
157        self::assertInstanceOf(CreateProcedure::class, $statement);
158        self::assertInstanceOf(Block::class, $statement->body);
159        $declaration = $statement->body->declarations[0];
160        self::assertInstanceOf(CursorDeclaration::class, $declaration);
161
162        self::assertSame('c', $declaration->name->value);
163        self::assertInstanceOf($class, $declaration->query);
164        self::assertSame('CREATE PROCEDURE p() BEGIN DECLARE c CURSOR FOR ' . $rendering . '; END', $operation->toString());
165    }
166
167    /**
168     * @return iterable<string, array{string}>
169     */
170    public static function providerDeclarationLowersAConditionAndAHandler(): iterable
171    {
172        yield 'mysql 5.6' => ['mysql-5.6.51'];
173        yield 'mysql 5.7' => ['mysql-5.7.44'];
174        yield 'mysql 8.0' => ['mysql-8.0.44'];
175        yield 'mysql 9.1' => ['mysql-9.1.0'];
176    }
177
178    #[DataProvider('providerDeclarationLowersAConditionAndAHandler')]
179    public function testDeclarationLowersAConditionAndAHandler(string $release): void
180    {
181        $operation = (new Semantics($release))->analyze("create procedure p() begin declare x int; declare e condition for sqlstate '22012'; declare exit handler for not found set x = 0; declare continue handler for sqlwarning begin end; end");
182        $statement = $operation->statement;
183        self::assertInstanceOf(CreateProcedure::class, $statement);
184        self::assertInstanceOf(Block::class, $statement->body);
185
186        self::assertEquals([
187            new VariableDeclaration([new Name('x')], new Integral(IntegralKind::Int)),
188            new ConditionDeclaration(new Name('e'), new SqlState(new Text('22012'))),
189            new HandlerDeclaration(HandlerAction::Exit, [new GeneralCondition(ConditionClass::NotFound)], new SetVariables([new NameAssignment(new Name('x'), new NumberLiteral('0'))])),
190            new HandlerDeclaration(HandlerAction::Continue, [new GeneralCondition(ConditionClass::SqlWarning)], new Block()),
191        ], $statement->body->declarations);
192        self::assertSame("CREATE PROCEDURE p() BEGIN DECLARE x INT; DECLARE e CONDITION FOR SQLSTATE '22012'; DECLARE EXIT HANDLER FOR NOT FOUND SET x = 0; DECLARE CONTINUE HANDLER FOR SQLWARNING BEGIN END; END", $operation->toString());
193        self::assertSame([], $operation->facts->diagnostics);
194    }
195
196
197    /**
198     * @return iterable<string, array{string}>
199     */
200    public static function providerNamesLowersTheDeclaredAndTheFetchedNames(): iterable
201    {
202        yield 'mysql 5.6' => ['mysql-5.6.51'];
203        yield 'mysql 5.7' => ['mysql-5.7.44'];
204        yield 'mysql 8.0' => ['mysql-8.0.44'];
205        yield 'mysql 9.1' => ['mysql-9.1.0'];
206    }
207
208    #[DataProvider('providerNamesLowersTheDeclaredAndTheFetchedNames')]
209    public function testNamesLowersTheDeclaredAndTheFetchedNames(string $release): void
210    {
211        $operation = (new Semantics($release))->analyze('create procedure p() begin declare a, b, c int; declare k cursor for select 1, 2, 3; fetch k into a, b, c; end');
212        $statement = $operation->statement;
213        self::assertInstanceOf(CreateProcedure::class, $statement);
214        self::assertInstanceOf(Block::class, $statement->body);
215        $variables = $statement->body->declarations[0];
216        self::assertInstanceOf(VariableDeclaration::class, $variables);
217
218        self::assertEquals([new Name('a'), new Name('b'), new Name('c')], $variables->names);
219        self::assertEquals([new FetchCursor(new Name('k'), [new Name('a'), new Name('b'), new Name('c')])], $statement->body->statements);
220        self::assertSame('CREATE PROCEDURE p() BEGIN DECLARE a, b, c INT; DECLARE k CURSOR FOR SELECT 1, 2, 3; FETCH k INTO a, b, c; END', $operation->toString());
221    }
222
223    /**
224     * @return iterable<string, array{string, string, Arithmetic|null, string}>
225     */
226    public static function providerInitialLowersTheDefaultClause(): iterable
227    {
228        yield 'absent in 5.6' => ['mysql-5.6.51', 'declare x int', null, 'DECLARE x INT'];
229        yield 'an expression in 5.7' => ['mysql-5.7.44', 'declare x int default 1 + 2', new Arithmetic(ArithmeticOperator::Plus, new NumberLiteral('1'), new NumberLiteral('2')), 'DECLARE x INT DEFAULT 1 + 2'];
230        yield 'absent in 8.0' => ['mysql-8.0.44', 'declare x int', null, 'DECLARE x INT'];
231        yield 'an expression in 9.1' => ['mysql-9.1.0', 'declare x int default 1 + 2', new Arithmetic(ArithmeticOperator::Plus, new NumberLiteral('1'), new NumberLiteral('2')), 'DECLARE x INT DEFAULT 1 + 2'];
232    }
233
234    #[DataProvider('providerInitialLowersTheDefaultClause')]
235    public function testInitialLowersTheDefaultClause(string $release, string $declaration, ?Arithmetic $default, string $rendering): void
236    {
237        $operation = (new Semantics($release))->analyze('create procedure p() begin ' . $declaration . '; end');
238        $statement = $operation->statement;
239        self::assertInstanceOf(CreateProcedure::class, $statement);
240        self::assertInstanceOf(Block::class, $statement->body);
241
242        self::assertEquals([new VariableDeclaration([new Name('x')], new Integral(IntegralKind::Int), null, $default)], $statement->body->declarations);
243        self::assertSame('CREATE PROCEDURE p() BEGIN ' . $rendering . '; END', $operation->toString());
244    }
245
246    /**
247     * @return iterable<string, array{string}>
248     */
249    public static function providerCursorLowersOpenFetchAndClose(): iterable
250    {
251        yield 'mysql 5.6' => ['mysql-5.6.51'];
252        yield 'mysql 5.7' => ['mysql-5.7.44'];
253        yield 'mysql 8.0' => ['mysql-8.0.44'];
254        yield 'mysql 9.1' => ['mysql-9.1.0'];
255    }
256
257    #[DataProvider('providerCursorLowersOpenFetchAndClose')]
258    public function testCursorLowersOpenFetchAndClose(string $release): void
259    {
260        $operation = (new Semantics($release))->analyze('create procedure p() begin declare a int; declare k cursor for select 1; open k; fetch next from k into a; fetch from k into a; fetch k into a; close k; end');
261        $statement = $operation->statement;
262        self::assertInstanceOf(CreateProcedure::class, $statement);
263        self::assertInstanceOf(Block::class, $statement->body);
264
265        self::assertEquals([
266            new OpenCursor(new Name('k')),
267            new FetchCursor(new Name('k'), [new Name('a')]),
268            new FetchCursor(new Name('k'), [new Name('a')]),
269            new FetchCursor(new Name('k'), [new Name('a')]),
270            new CloseCursor(new Name('k')),
271        ], $statement->body->statements);
272        self::assertSame('CREATE PROCEDURE p() BEGIN DECLARE a INT; DECLARE k CURSOR FOR SELECT 1; OPEN k; FETCH k INTO a; FETCH k INTO a; FETCH k INTO a; CLOSE k; END', $operation->toString());
273        self::assertSame([], $operation->facts->diagnostics);
274    }
275}
276