packages/sql-semantics-sqlite/tests/Unit/Rules/Query/CompoundFactsTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Rules\Query;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10use SqlSemantics\Platform\Sqlite\Model\Construction\Derivation;
11use SqlSemantics\Platform\Sqlite\Model\Resolution\CommonBinding;
12use SqlSemantics\Platform\Sqlite\Model\Resolution\Environment;
13use SqlSemantics\Platform\Sqlite\Model\Statement\Reference\Column\AliasTarget;
14use SqlSemantics\Platform\Sqlite\Model\Statement\Shape\Field;
15use SqlSemantics\Platform\Sqlite\Model\Statement\Shape\OpenStar;
16use SqlSemantics\Platform\Sqlite\Model\Statement\Shape\OutputSlot;
17use SqlSemantics\Platform\Sqlite\Model\Statement\Shape\RowShape;
18use SqlSemantics\Platform\Sqlite\Model\Statement\Type\Choice;
19use SqlSemantics\Platform\Sqlite\Model\Statement\Type\Known;
20use SqlSemantics\Platform\Sqlite\Model\Statement\Type\Nullability;
21use SqlSemantics\Platform\Sqlite\Rules\Query\CompoundFacts;
22use SqlSemantics\Platform\Sqlite\Semantics;
23use SqlSemantics\Platform\Sqlite\Statement\Query\Compound;
24use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\ArityMismatch;
25use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\ArityRule;
26use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\MisuseRule;
27use SqlSemantics\Platform\Sqlite\Statement\Query\Select;
28use SqlSemantics\Platform\Sqlite\Statement\Query\With\WithQuery;
29use SqlSemantics\Platform\Sqlite\Statement\Type\Storage;
30
31#[CoversClass(CompoundFacts::class)]
32#[Medium]
33final class CompoundFactsTest extends TestCase
34{
35    public function testDeriveCombinesTheArmsAndOrdersByTheNamesOfEveryArm(): void
36    {
37        $semantics = new Semantics();
38        $compound = $semantics->inspect("SELECT 1 AS a, 'x' AS b UNION SELECT NULL AS c, 2 ORDER BY c, 2 LIMIT 1")->statement;
39        self::assertInstanceOf(Compound::class, $compound);
40        $derivation = new Derivation($semantics->context([]));
41
42        $fact = (new CompoundFacts())->derive($compound, $derivation, $derivation->environment());
43        $facts = $derivation->facts();
44
45        self::assertSame(['a', 'b'], array_map(static fn (object $item): ?string => $item instanceof Field ? $item->name?->value : null, $fact->projection));
46        self::assertSame(Nullability::Nullable, $fact->shape->slots[0]->nullability);
47        self::assertInstanceOf(Choice::class, $fact->shape->slots[1]->type);
48        self::assertSame([Storage::Integer, Storage::Text], $fact->shape->slots[1]->type->alternatives);
49        $first = $facts->scalar($compound->orderBy[0]->expression)->resolution;
50        $second = $facts->scalar($compound->orderBy[1]->expression)->resolution;
51        self::assertInstanceOf(AliasTarget::class, $first);
52        self::assertSame(0, $first->field->position);
53        self::assertInstanceOf(AliasTarget::class, $second);
54        self::assertSame(1, $second->field->position);
55        self::assertNotNull($compound->limit);
56        self::assertTrue($facts->covers($compound->limit->count));
57        self::assertSame([], $facts->diagnostics);
58    }
59
60    public function testDeriveReportsAnOrderingOrALimitOnAnEarlierArm(): void
61    {
62        $semantics = new Semantics();
63        $compound = $semantics->inspect('SELECT 1 ORDER BY 1 UNION SELECT 2 LIMIT 1 UNION SELECT 3')->statement;
64        self::assertInstanceOf(Compound::class, $compound);
65        $derivation = new Derivation($semantics->context([]));
66
67        (new CompoundFacts())->derive($compound, $derivation, $derivation->environment());
68
69        self::assertSame([MisuseRule::OrderByBeforeCompound->value, MisuseRule::LimitBeforeCompound->value], array_map(static fn (object $problem): string => $problem->message(), $derivation->facts()->diagnostics));
70    }
71
72    public function testCombinedTakesTheNamesOfTheFirstArmAndReportsAnotherWidthOnce(): void
73    {
74        $semantics = new Semantics();
75        $query = $semantics->inspect("SELECT 1 AS a UNION SELECT 'x', 2 UNION SELECT NULL, 3, 4");
76        $compound = $query->statement;
77        self::assertInstanceOf(Compound::class, $compound);
78        $facts = [$query->facts->query($compound->first), $query->facts->query($compound->steps[0]->query), $query->facts->query($compound->steps[1]->query)];
79        $derivation = new Derivation($semantics->context([]));
80
81        $items = (new CompoundFacts())->combined($facts, $derivation);
82
83        self::assertCount(1, $items);
84        self::assertInstanceOf(Field::class, $items[0]);
85        self::assertSame('a', $items[0]->name?->value);
86        self::assertInstanceOf(Known::class, $items[0]->type);
87        self::assertSame(Storage::Integer, $items[0]->type->descriptor);
88        self::assertSame(Nullability::NotNull, $items[0]->nullability);
89        self::assertSame($facts[0]->shape->slots[0], $items[0]->slot->origin);
90        self::assertCount(1, $derivation->facts()->diagnostics);
91        self::assertInstanceOf(ArityMismatch::class, $derivation->facts()->diagnostics[0]);
92        self::assertSame(ArityRule::CompoundArms, $derivation->facts()->diagnostics[0]->rule);
93        self::assertSame(2, $derivation->facts()->diagnostics[0]->actual);
94    }
95
96    public function testCombinedAnswersAnOpenStarWhenTheFirstArmIsOpen(): void
97    {
98        $semantics = new Semantics();
99        $query = $semantics->inspect('SELECT * FROM t UNION SELECT 1');
100        $compound = $query->statement;
101        self::assertInstanceOf(Compound::class, $compound);
102        $derivation = new Derivation($semantics->context());
103
104        $items = (new CompoundFacts())->combined([$query->facts->query($compound->first), $query->facts->query($compound->steps[0]->query)], $derivation);
105
106        self::assertCount(1, $items);
107        self::assertInstanceOf(OpenStar::class, $items[0]);
108        self::assertSame('the declaration of relation t', $items[0]->missing[0]->describe());
109    }
110
111    public function testCombinedDependsOnAnOpenLaterArm(): void
112    {
113        $semantics = new Semantics();
114        $query = $semantics->inspect('SELECT 1 AS a UNION SELECT * FROM t');
115        $compound = $query->statement;
116        self::assertInstanceOf(Compound::class, $compound);
117
118        $items = (new CompoundFacts())->combined([$query->facts->query($compound->first), $query->facts->query($compound->steps[0]->query)], new Derivation($semantics->context()));
119
120        self::assertInstanceOf(Field::class, $items[0]);
121        self::assertSame(Nullability::Dependent, $items[0]->nullability);
122    }
123
124    public function testAliasesNamesTheOutputAfterEveryArm(): void
125    {
126        $semantics = new Semantics();
127        $query = $semantics->inspect('SELECT 1 AS a, 2 UNION SELECT 3 AS b, 4 AS c');
128        $compound = $query->statement;
129        self::assertInstanceOf(Compound::class, $compound);
130        $arms = [$compound->first, $compound->steps[0]->query];
131        $facts = [$query->facts->query($compound->first), $query->facts->query($compound->steps[0]->query)];
132        $output = $query->facts->output;
133        self::assertNotNull($output);
134
135        $aliases = (new CompoundFacts())->aliases($arms, $facts, $output->projection);
136
137        self::assertSame(['a', 'b', 'c'], array_map(static fn (Field $field): ?string => $field->name?->value, $aliases));
138        self::assertSame([0, 0, 1], array_map(static fn (Field $field): int => $field->position, $aliases));
139        self::assertSame($query->field(1)->slot, $aliases[2]->slot->origin);
140        self::assertSame([], (new CompoundFacts())->aliases($arms, $facts, []));
141    }
142
143    public function testSpelledTellsANameTakenFromTheTextOfAnExpression(): void
144    {
145        $semantics = new Semantics();
146        $query = $semantics->inspect('SELECT 1+1, (a), 2 AS b, * FROM (SELECT 1 AS a)');
147        $select = $query->statement;
148        self::assertInstanceOf(Select::class, $select);
149        $facts = new CompoundFacts();
150
151        self::assertTrue($facts->spelled($select, $query->field(0)));
152        self::assertFalse($facts->spelled($select, $query->field(1)));
153        self::assertFalse($facts->spelled($select, $query->field(2)));
154        self::assertFalse($facts->spelled($select, $query->field(3)));
155        self::assertFalse($facts->spelled(null, $query->field(0)));
156    }
157
158    public function testReboundGivesTheRecursiveReferenceTheNamesOfTheColumnListAndAnyStorageClass(): void
159    {
160        $semantics = new Semantics();
161        $query = $semantics->inspect('WITH RECURSIVE c(n, true, N) AS (SELECT 1 AS x, 2, 3 UNION ALL SELECT n + 1, 2, 3 FROM c) SELECT * FROM c', []);
162        $statement = $query->statement;
163        self::assertInstanceOf(WithQuery::class, $statement);
164        $table = $statement->with->tables[0];
165        $compound = $table->query;
166        self::assertInstanceOf(Compound::class, $compound);
167        $outer = new Environment($query->context, null, [], [new CommonBinding($table->name, $table, new RowShape([]))]);
168
169        $rebound = (new CompoundFacts())->rebound($compound, $query->facts->query($compound->first), $outer, new Derivation($query->context));
170        $slot = $rebound->commonTables[0]->shape->slots[0];
171
172        self::assertNotSame($outer, $rebound);
173        self::assertSame($table, $rebound->commonTables[0]->definition);
174        self::assertSame(['n', 'column2', 'N:1'], array_map(static fn (OutputSlot $slot): ?string => $slot->name?->value, $rebound->commonTables[0]->shape->slots));
175        self::assertInstanceOf(Choice::class, $slot->type);
176        self::assertSame(Storage::cases(), $slot->type->alternatives);
177        self::assertSame(Nullability::Nullable, $slot->nullability);
178    }
179
180    public function testReboundNamesTheColumnsAfterTheFirstArmWithoutAColumnList(): void
181    {
182        $semantics = new Semantics();
183        $query = $semantics->inspect('WITH RECURSIVE c AS (SELECT 1 AS x, 1+1 UNION ALL SELECT x + 1, 2 FROM c) SELECT * FROM c', []);
184        $statement = $query->statement;
185        self::assertInstanceOf(WithQuery::class, $statement);
186        $table = $statement->with->tables[0];
187        $compound = $table->query;
188        self::assertInstanceOf(Compound::class, $compound);
189        $outer = new Environment($query->context, null, [], [new CommonBinding($table->name, $table, new RowShape([]))]);
190
191        $rebound = (new CompoundFacts())->rebound($compound, $query->facts->query($compound->first), $outer, new Derivation($query->context));
192
193        self::assertSame('x', $rebound->commonTables[0]->shape->slots[0]->name?->value);
194        self::assertSame('1+1', $rebound->commonTables[0]->shape->slots[1]->name?->value);
195    }
196
197    public function testReboundLeavesAnEnvironmentWithoutTheTableUntouched(): void
198    {
199        $semantics = new Semantics();
200        $query = $semantics->inspect('SELECT 1 UNION SELECT 2');
201        $compound = $query->statement;
202        self::assertInstanceOf(Compound::class, $compound);
203        $outer = new Environment($query->context);
204
205        self::assertSame($outer, (new CompoundFacts())->rebound($compound, $query->facts->query($compound->first), $outer, new Derivation($query->context)));
206    }
207}
208