packages/sql-semantics-sqlite/tests/Unit/Model/Validation/PublicationTest.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 SqlSemantics\Platform\Sqlite\Model\Statement\Identifier\Name;
11use SqlSemantics\Platform\Sqlite\Model\Statement\Identifier\QualifiedName;
12use SqlSemantics\Platform\Sqlite\Model\Statement\Reference\Column\ResolvedColumn;
13use SqlSemantics\Platform\Sqlite\Model\Statement\Script;
14use SqlSemantics\Platform\Sqlite\Model\Validation\Publication;
15use SqlSemantics\Platform\Sqlite\Semantics;
16use SqlSemantics\Platform\Sqlite\Statement\Expression\ColumnUse;
17use SqlSemantics\Platform\Sqlite\Statement\Expression\Literal\IntegerLiteral;
18use SqlSemantics\Platform\Sqlite\Statement\Query\ResultColumn;
19use SqlSemantics\Platform\Sqlite\Statement\Query\Select;
20use SqlSemantics\Platform\Sqlite\Statement\Relation\TableInput;
21
22#[CoversClass(Publication::class)]
23#[Medium]
24final class PublicationTest extends TestCase
25{
26 public function testEstablishDerivesTheFactsAndRendersCorrespondingSql(): void
27 {
28 $semantics = new Semantics();
29 $table = $semantics->analyze('CREATE TABLE t (a INTEGER)');
30 $use = new ColumnUse(new Name('a'));
31 $statement = new Select([new ResultColumn($use, new Name('order'))], new TableInput(new QualifiedName(new Name('t'))));
32
33 [$facts, $sql] = (new Publication())->establish($semantics->context([$table]), $statement);
34
35 self::assertSame('SELECT a AS `order` FROM t', $sql);
36 self::assertInstanceOf(ResolvedColumn::class, $facts->scalar($use)->resolution);
37 self::assertSame($table->declarations()[0]->columns[0], $facts->scalar($use)->resolution->declaration());
38 self::assertSame('order', $facts->output?->fields()?->at(0)->name?->value);
39 }
40
41 public function testEstablishRefusesANodeUsedAtTwoPositions(): void
42 {
43 $context = (new Semantics())->context([]);
44 $literal = new IntegerLiteral('1');
45
46 $this->expectExceptionMessage('A statement node occurs at one position only.');
47
48 (new Publication())->establish($context, new Select([new ResultColumn($literal), new ResultColumn($literal)]));
49 }
50
51 public function testRootIsTheOnlyStatementOrAScript(): void
52 {
53 $semantics = new Semantics();
54 $first = $semantics->analyze('SELECT 1')->statement;
55 $second = $semantics->analyze('SELECT 2')->statement;
56
57 $publication = new Publication();
58
59 self::assertSame($first, $publication->root([$first]));
60 $script = $publication->root([$first, $second]);
61 self::assertInstanceOf(Script::class, $script);
62 self::assertSame([$first, $second], $script->statements);
63 $empty = $publication->root([]);
64 self::assertInstanceOf(Script::class, $empty);
65 self::assertSame([], $empty->statements);
66 }
67}
68