packages/sql-semantics-sqlite/tests/Unit/Model/Validation/SpellingsTest.php
1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Model\Validation;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10use SqlParser\Lexer\Token;
11use SqlParser\Sqlite\SqliteParser;
12use SqlSemantics\Platform\Sqlite\Model\Validation\Spellings;
13use SqlSemantics\Platform\Sqlite\Platform;
14use SqlSemantics\Platform\Sqlite\Rules\LeafKeys;
15use SqlSemantics\Platform\Sqlite\Semantics;
16
17#[CoversClass(Spellings::class)]
18#[Medium]
19final class SpellingsTest extends TestCase
20{
21 public function testCheckAcceptsOtherSpellingsOfTheSameTokensAndTrivia(): void
22 {
23 $spellings = new Spellings(new SqliteParser(), Platform::shared()->productions((new Semantics())->profile()), new LeafKeys());
24
25 $spellings->check('SELECT a AND b', "SELECT `a` /* x */\nand b");
26
27 self::assertCount(4, $spellings->tokens('SELECT a AND b'));
28 }
29
30 public function testCheckRefusesADifferentToken(): void
31 {
32 $spellings = new Spellings(new SqliteParser(), Platform::shared()->productions((new Semantics())->profile()), new LeafKeys());
33
34 $this->expectExceptionMessage('The spelled SQL is not the rendered SQL at token 2: source has AND:AND, rendered SQL has OR:OR: SELECT a OR b');
35
36 $spellings->check('SELECT a AND b', 'SELECT a OR b');
37 }
38
39 public function testCheckRefusesATokenWrittenIntoAGap(): void
40 {
41 $spellings = new Spellings(new SqliteParser(), Platform::shared()->productions((new Semantics())->profile()), new LeafKeys());
42
43 $this->expectExceptionMessage('The spelled SQL has 5 tokens where the rendered SQL has 4: SELECT a AND NOT b');
44
45 $spellings->check('SELECT a AND b', 'SELECT a AND NOT b');
46 }
47
48 public function testTokensDropsTheEndMarker(): void
49 {
50 $tokens = (new Spellings(new SqliteParser(), Platform::shared()->productions((new Semantics())->profile()), new LeafKeys()))->tokens(" -- only a comment\n");
51
52 self::assertSame([], array_map(static fn (Token $token): string => $token->text, $tokens));
53 }
54
55 public function testTreeRefusesTextOutsideTheGrammar(): void
56 {
57 $spellings = new Spellings(new SqliteParser(), Platform::shared()->productions((new Semantics())->profile()), new LeafKeys());
58
59 $this->expectExceptionMessage('A rendered or spelled text is outside the grammar: SELECT FROM');
60
61 $spellings->tree('SELECT FROM');
62 }
63}
64