packages/sql-semantics-mysql/tests/Unit/Rules/Routine/ConditionFactsTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Rules\Routine;
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\Contract\AnalysisContext;
12use SqlSemantics\Platform\MySql\Model\Resolution\Environment;
13use SqlSemantics\Platform\MySql\Model\Statement\Fact\Diagnostic;
14use SqlSemantics\Platform\MySql\Model\Statement\Identifier\Name;
15use SqlSemantics\Platform\MySql\Model\Statement\Reference\Column\ResolvedColumn;
16use SqlSemantics\Platform\MySql\Rules\Routine\ConditionFacts;
17use SqlSemantics\Platform\MySql\Rules\Routine\ProgramScope;
18use SqlSemantics\Platform\MySql\Semantics;
19use SqlSemantics\Platform\MySql\Statement\Literal\Numeral;
20use SqlSemantics\Platform\MySql\Statement\Literal\Text;
21use SqlSemantics\Platform\MySql\Statement\Routine\Condition\Condition;
22use SqlSemantics\Platform\MySql\Statement\Routine\Condition\ConditionClass;
23use SqlSemantics\Platform\MySql\Statement\Routine\Condition\ConditionName;
24use SqlSemantics\Platform\MySql\Statement\Routine\Condition\ErrorCode;
25use SqlSemantics\Platform\MySql\Statement\Routine\Condition\GeneralCondition;
26use SqlSemantics\Platform\MySql\Statement\Routine\Condition\Signal;
27use SqlSemantics\Platform\MySql\Statement\Routine\Condition\SqlState;
28use SqlSemantics\Platform\MySql\Statement\Routine\CreateProcedure;
29use SqlSemantics\Platform\MySql\Statement\Routine\Program\ConditionDeclaration;
30use SqlSemantics\Platform\MySql\Statement\Routine\ProgramKind;
31
32#[CoversClass(ConditionFacts::class)]
33#[Medium]
34final class ConditionFactsTest extends TestCase
35{
36    /**
37     * @param list<string> $messages
38     */
39    #[DataProvider('providerValueChecksTheFormOfAnSqlState')]
40    public function testValueChecksTheFormOfAnSqlState(string $release, string $sql, array $messages): void
41    {
42        $operation = (new Semantics($release))->inspect($sql);
43
44        self::assertSame($messages, array_map(static fn (Diagnostic $diagnostic): string => $diagnostic->message(), $operation->facts->diagnostics));
45    }
46
47    /**
48     * @return iterable<string, array{string, string, list<string>}>
49     */
50    public static function providerValueChecksTheFormOfAnSqlState(): iterable
51    {
52        yield 'success in a handler' => ['mysql-9.1.0', "CREATE PROCEDURE p() BEGIN DECLARE CONTINUE HANDLER FOR SQLSTATE '00000' BEGIN END; END", ["Bad SQLSTATE: '00000'"]];
53        yield 'success in a condition in 5.6' => ['mysql-5.6.51', "CREATE PROCEDURE p() BEGIN DECLARE c CONDITION FOR SQLSTATE '00123'; END", ["Bad SQLSTATE: '00123'"]];
54        yield 'four characters in SIGNAL' => ['mysql-8.0.44', "CREATE PROCEDURE p() SIGNAL SQLSTATE '4500'", ["Bad SQLSTATE: '4500'"]];
55        yield 'six characters in SIGNAL' => ['mysql-9.1.0', "CREATE PROCEDURE p() SIGNAL SQLSTATE VALUE '450000'", ["Bad SQLSTATE: '450000'"]];
56        yield 'a lower-case letter in SIGNAL' => ['mysql-9.1.0', "CREATE PROCEDURE p() SIGNAL SQLSTATE '4500a'", ["Bad SQLSTATE: '4500a'"]];
57        yield 'a warning in SIGNAL' => ['mysql-9.1.0', "CREATE PROCEDURE p() SIGNAL SQLSTATE '01000'", []];
58        yield 'an upper-case letter in a handler' => ['mysql-5.7.44', "CREATE PROCEDURE p() BEGIN DECLARE CONTINUE HANDLER FOR SQLSTATE '42S02', NOT FOUND, SQLWARNING BEGIN END; END", []];
59    }
60
61    /**
62     * @param list<string> $messages
63     */
64    #[DataProvider('providerValueReportsAConditionNameDeclaredNowhereAround')]
65    public function testValueReportsAConditionNameDeclaredNowhereAround(string $sql, array $messages): void
66    {
67        $operation = (new Semantics())->inspect($sql);
68
69        self::assertSame($messages, array_map(static fn (Diagnostic $diagnostic): string => $diagnostic->message(), $operation->facts->diagnostics));
70    }
71
72    /**
73     * @return iterable<string, array{string, list<string>}>
74     */
75    public static function providerValueReportsAConditionNameDeclaredNowhereAround(): iterable
76    {
77        yield 'an undeclared handler condition' => ['CREATE PROCEDURE p() BEGIN DECLARE EXIT HANDLER FOR nope BEGIN END; END', ['Undefined CONDITION: nope']];
78        yield 'an undeclared SIGNAL condition' => ['CREATE PROCEDURE p() SIGNAL c', ['Undefined CONDITION: c']];
79        yield 'a condition of an inner block' => ["CREATE PROCEDURE p() BEGIN BEGIN DECLARE c CONDITION FOR SQLSTATE '45000'; END; SIGNAL c; END", ['Undefined CONDITION: c']];
80        yield 'a condition of an outer block' => ["CREATE PROCEDURE p() BEGIN DECLARE c CONDITION FOR SQLSTATE '45000'; BEGIN SIGNAL C; END; END", []];
81        yield 'a condition in another case' => ['CREATE PROCEDURE p() BEGIN DECLARE E CONDITION FOR 1051; DECLARE EXIT HANDLER FOR e BEGIN END; END', []];
82    }
83
84    /**
85     * @param list<string> $messages
86     */
87    #[DataProvider('providerSignalReportsTheBrokenRule')]
88    public function testSignalReportsTheBrokenRule(string $sql, array $messages): void
89    {
90        $operation = (new Semantics())->inspect($sql);
91
92        self::assertSame($messages, array_map(static fn (Diagnostic $diagnostic): string => $diagnostic->message(), $operation->facts->diagnostics));
93    }
94
95    /**
96     * @return iterable<string, array{string, list<string>}>
97     */
98    public static function providerSignalReportsTheBrokenRule(): iterable
99    {
100        yield 'SIGNAL of an error code condition' => ['CREATE PROCEDURE p() BEGIN DECLARE c CONDITION FOR 1051; SIGNAL c; END', ['SIGNAL/RESIGNAL can only use a CONDITION defined with SQLSTATE']];
101        yield 'RESIGNAL of an error code condition' => ['CREATE PROCEDURE p() BEGIN DECLARE c CONDITION FOR 1051; RESIGNAL c; END', ['SIGNAL/RESIGNAL can only use a CONDITION defined with SQLSTATE']];
102        yield 'SIGNAL of an SQLSTATE condition' => ["CREATE PROCEDURE p() BEGIN DECLARE c CONDITION FOR SQLSTATE '45000'; SIGNAL c SET MESSAGE_TEXT = 'm'; END", []];
103        yield 'an item set twice by SIGNAL' => ["CREATE PROCEDURE p() SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'a', MYSQL_ERRNO = 1, MESSAGE_TEXT = 'b'", ["Duplicate condition information item 'MESSAGE_TEXT'"]];
104        yield 'an item set twice by RESIGNAL' => ["CREATE PROCEDURE p() RESIGNAL SET CLASS_ORIGIN = 'a', CLASS_ORIGIN = 'b'", ["Duplicate condition information item 'CLASS_ORIGIN'"]];
105        yield 'RESIGNAL without a condition' => ['CREATE PROCEDURE p() RESIGNAL', []];
106        yield 'an unknown name in an item' => ["CREATE PROCEDURE p() SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = z", ['Column z does not exist.']];
107    }
108
109    public function testSignalResolvesTheValueOfAnItemToAParameter(): void
110    {
111        $operation = (new Semantics())->inspect("CREATE PROCEDURE p(z TEXT) SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = z, MYSQL_ERRNO = 1");
112        $create = $operation->statement;
113        self::assertInstanceOf(CreateProcedure::class, $create);
114        $signal = $create->body;
115        self::assertInstanceOf(Signal::class, $signal);
116        $resolution = $operation->facts->scalar($signal->items[0]->value)->resolution;
117        self::assertInstanceOf(ResolvedColumn::class, $resolution);
118
119        self::assertSame([], $operation->facts->diagnostics);
120        self::assertSame('z', $resolution->slot->name?->value);
121    }
122
123    /**
124     * @param list<string> $messages
125     */
126    #[DataProvider('providerTargetsReportsATargetThatIsNoVariable')]
127    public function testTargetsReportsATargetThatIsNoVariable(string $sql, array $messages): void
128    {
129        $operation = (new Semantics())->inspect($sql);
130
131        self::assertSame($messages, array_map(static fn (Diagnostic $diagnostic): string => $diagnostic->message(), $operation->facts->diagnostics));
132    }
133
134    /**
135     * @return iterable<string, array{string, list<string>}>
136     */
137    public static function providerTargetsReportsATargetThatIsNoVariable(): iterable
138    {
139        yield 'a user variable and an undeclared name' => ['CREATE PROCEDURE p() GET DIAGNOSTICS @n = NUMBER, y = ROW_COUNT', ['Undeclared variable: y']];
140        yield 'condition items' => ['CREATE PROCEDURE p() BEGIN DECLARE y INT; GET DIAGNOSTICS CONDITION 1 y = MESSAGE_TEXT, @m = RETURNED_SQLSTATE, z = CLASS_ORIGIN; END', ['Undeclared variable: z']];
141        yield 'a variable of a closed block' => ['CREATE PROCEDURE p() BEGIN DECLARE x INT; BEGIN BEGIN DECLARE y INT; END; GET DIAGNOSTICS x = NUMBER, y = ROW_COUNT; END; END', ['Undeclared variable: y']];
142        yield 'a parameter in another case' => ['CREATE PROCEDURE p(OUT n INT) GET DIAGNOSTICS N = NUMBER', []];
143        yield 'variables of a handler' => ['CREATE PROCEDURE p() BEGIN DECLARE m TEXT; DECLARE EXIT HANDLER FOR SQLEXCEPTION GET STACKED DIAGNOSTICS CONDITION 1 m = MESSAGE_TEXT; END', []];
144    }
145
146    /**
147     * @param list<string> $messages
148     */
149    #[DataProvider('providerValueReportsTheErrorCodeZero')]
150    public function testValueReportsTheErrorCodeZero(string $release, string $sql, array $messages): void
151    {
152        $operation = (new Semantics($release))->inspect($sql);
153
154        self::assertSame($messages, array_map(static fn (Diagnostic $diagnostic): string => $diagnostic->message(), $operation->facts->diagnostics));
155    }
156
157    /**
158     * @return iterable<string, array{string, string, list<string>}>
159     */
160    public static function providerValueReportsTheErrorCodeZero(): iterable
161    {
162        yield 'zero in a condition in 5.6' => ['mysql-5.6.51', 'CREATE PROCEDURE p() BEGIN DECLARE c CONDITION FOR 0; END', ["Incorrect CONDITION value: '0'"]];
163        yield 'zero in a handler in 8.0' => ['mysql-8.0.44', 'CREATE PROCEDURE p() BEGIN DECLARE CONTINUE HANDLER FOR 0 BEGIN END; END', ["Incorrect CONDITION value: '0'"]];
164        yield 'a decimal below one in 9.1' => ['mysql-9.1.0', 'CREATE PROCEDURE p() BEGIN DECLARE c CONDITION FOR 0.7; END', ["Incorrect CONDITION value: '0'"]];
165        yield 'a hexadecimal zero in 9.1' => ['mysql-9.1.0', 'CREATE PROCEDURE p() BEGIN DECLARE c CONDITION FOR 0x00; END', ["Incorrect CONDITION value: '0'"]];
166        yield 'a floating number in 9.1' => ['mysql-9.1.0', 'CREATE PROCEDURE p() BEGIN DECLARE c CONDITION FOR 1e2; END', []];
167    }
168
169    public function testMeaningAnswersTheDeclaredValueOfAConditionName(): void
170    {
171        $scope = new ProgramScope(new Environment(new AnalysisContext((new Semantics())->profile(), [new Name('db')])), ProgramKind::Procedure, conditions: [new ConditionDeclaration(new Name('c'), new ErrorCode(new Numeral('1051')))]);
172        $code = new ErrorCode(new Numeral('1052'));
173
174        self::assertEquals(new ErrorCode(new Numeral('1051')), (new ConditionFacts())->meaning(new ConditionName(new Name('C')), $scope));
175        self::assertNull((new ConditionFacts())->meaning(new ConditionName(new Name('d')), $scope));
176        self::assertSame($code, (new ConditionFacts())->meaning($code, $scope));
177    }
178
179    #[DataProvider('providerSameComparesTheValues')]
180    public function testSameComparesTheValues(Condition $left, Condition $right, bool $expected): void
181    {
182        self::assertSame($expected, (new ConditionFacts())->same($left, $right));
183    }
184
185    /**
186     * @return iterable<string, array{Condition, Condition, bool}>
187     */
188    public static function providerSameComparesTheValues(): iterable
189    {
190        yield 'one general condition' => [new GeneralCondition(ConditionClass::SqlException), new GeneralCondition(ConditionClass::SqlException), true];
191        yield 'two general conditions' => [new GeneralCondition(ConditionClass::SqlException), new GeneralCondition(ConditionClass::NotFound), false];
192        yield 'one error number in two spellings' => [new ErrorCode(new Numeral('1051')), new ErrorCode(new Numeral('41B', true)), true];
193        yield 'two error numbers' => [new ErrorCode(new Numeral('1051')), new ErrorCode(new Numeral('1052')), false];
194        yield 'one SQLSTATE value' => [new SqlState(new Text('42S02')), new SqlState(new Text('42S02')), true];
195        yield 'two SQLSTATE values' => [new SqlState(new Text('42S02')), new SqlState(new Text('42S01')), false];
196        yield 'an error number and an SQLSTATE value' => [new ErrorCode(new Numeral('1051')), new SqlState(new Text('42S02')), false];
197    }
198}
199