packages/sql-semantics-sqlite/tests/Unit/Model/Statement/Reference/Table/ConditionalTableTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Model\Statement\Reference\Table;
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\Missing\UndeclaredRelation;
13use SqlSemantics\Platform\Sqlite\Model\Statement\Reference\Table\ConditionalTable;
14use SqlSemantics\Platform\Sqlite\Model\Statement\Reference\Table\DeclaredTable;
15use SqlSemantics\Platform\Sqlite\Semantics;
16
17#[CoversClass(ConditionalTable::class)]
18#[Medium]
19final class ConditionalTableTest extends TestCase
20{
21    public function testCandidatesAreKeptWhileAnEarlierSchemaIsUnknown(): void
22    {
23        $semantics = new Semantics();
24        $table = $semantics->analyze('CREATE TABLE main.t (a INTEGER)');
25        $query = $semantics->analyze('SELECT a FROM t', $semantics->context([$table], false));
26
27        $resolution = $query->facts->relation($query->singleNamedInput())->table;
28
29        self::assertInstanceOf(ConditionalTable::class, $resolution);
30        self::assertSame([$table->declarations()[0]], $resolution->candidates);
31        self::assertSame('the declaration of relation t', $resolution->missing->describe());
32        self::assertFalse($query->facts->relation($query->singleNamedInput())->shape->complete());
33    }
34
35    public function testCandidatesAreNotNeededWhenTheContextIsComplete(): void
36    {
37        $semantics = new Semantics();
38        $table = $semantics->analyze('CREATE TABLE main.t (a INTEGER)');
39        $query = $semantics->analyze('SELECT a FROM t', [$table]);
40
41        self::assertInstanceOf(DeclaredTable::class, $query->facts->relation($query->singleNamedInput())->table);
42    }
43
44    public function testCandidatesAreAtLeastOne(): void
45    {
46        $this->expectExceptionMessage('A conditional table has at least one candidate.');
47
48        new ConditionalTable([], new UndeclaredRelation(new QualifiedName(new Name('t'))));
49    }
50}
51