packages/sql-semantics-sqlite/tests/Unit/Statement/Query/CompoundTest.php
1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Query;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10use SqlSemantics\Platform\Sqlite\Model\Statement\Operation;
11use SqlSemantics\Platform\Sqlite\Model\Statement\Reference\Column\AliasTarget;
12use SqlSemantics\Platform\Sqlite\Model\Statement\Shape\OpenStar;
13use SqlSemantics\Platform\Sqlite\Model\Statement\Type\Choice;
14use SqlSemantics\Platform\Sqlite\Model\Statement\Type\Nullability;
15use SqlSemantics\Platform\Sqlite\Semantics;
16use SqlSemantics\Platform\Sqlite\Statement\Expression\Literal\IntegerLiteral;
17use SqlSemantics\Platform\Sqlite\Statement\Expression\Literal\NullLiteral;
18use SqlSemantics\Platform\Sqlite\Statement\Query\Compound;
19use SqlSemantics\Platform\Sqlite\Statement\Query\CompoundOperator;
20use SqlSemantics\Platform\Sqlite\Statement\Query\CompoundStep;
21use SqlSemantics\Platform\Sqlite\Statement\Query\Limit;
22use SqlSemantics\Platform\Sqlite\Statement\Query\Ordering\SortTerm;
23use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\ArityMismatch;
24use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\ArityRule;
25use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\Misuse;
26use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\MisuseRule;
27use SqlSemantics\Platform\Sqlite\Statement\Query\ResultColumn;
28use SqlSemantics\Platform\Sqlite\Statement\Query\Select;
29use SqlSemantics\Platform\Sqlite\Statement\Query\ValueRow;
30use SqlSemantics\Platform\Sqlite\Statement\Query\ValuesClause;
31use SqlSemantics\Platform\Sqlite\Statement\Type\Storage;
32
33#[CoversClass(Compound::class)]
34#[Medium]
35final class CompoundTest extends TestCase
36{
37 public function testDeriveStatementNamesTheOutputAfterTheFirstArm(): void
38 {
39 $query = (new Semantics())->inspect("SELECT 1 AS a, 'x' AS b UNION ALL SELECT 2 AS c, 'y' AS d");
40
41 self::assertInstanceOf(Compound::class, $query->statement);
42 self::assertSame(['a', 'b'], array_map(static fn (object $field): ?string => $field->name?->value, [...$query->fields() ?? []]));
43 self::assertSame([], $query->facts->diagnostics);
44 }
45
46 public function testDeriveQueryChoosesTheTypeOverTheArmsAndTheirNullability(): void
47 {
48 $query = (new Semantics())->inspect("SELECT 1 AS a UNION SELECT 'x' UNION SELECT NULL");
49 $type = $query->field('a')->type;
50
51 self::assertInstanceOf(Choice::class, $type);
52 self::assertSame([Storage::Integer, Storage::Text], $type->alternatives);
53 self::assertSame(Nullability::Nullable, $query->field('a')->nullability);
54 }
55
56 public function testDeriveQueryReportsArmsOfDifferentWidthOnce(): void
57 {
58 $query = (new Semantics())->inspect('SELECT 1 UNION SELECT 2, 3 UNION SELECT 4, 5, 6');
59
60 self::assertCount(1, $query->facts->diagnostics);
61 self::assertInstanceOf(ArityMismatch::class, $query->facts->diagnostics[0]);
62 self::assertSame('SELECTs to the left and right of a compound operator do not have the same number of result columns: 1 and 2.', $query->facts->diagnostics[0]->message());
63 self::assertSame(ArityRule::CompoundArms, $query->facts->diagnostics[0]->rule);
64 self::assertCount(1, $query->fields() ?? []);
65 }
66
67 public function testDeriveQueryOrdersTheCombinedRowsByTheNamesOfEveryArm(): void
68 {
69 $query = (new Semantics())->inspect('SELECT 1 AS a UNION ALL SELECT 2 AS b ORDER BY b');
70
71 self::assertInstanceOf(Compound::class, $query->statement);
72 self::assertInstanceOf(Select::class, $query->statement->steps[0]->query);
73 self::assertSame([], $query->statement->steps[0]->query->orderBy);
74 $resolution = $query->facts->scalar($query->statement->orderBy[0]->expression)->resolution;
75 self::assertInstanceOf(AliasTarget::class, $resolution);
76 self::assertSame(0, $resolution->field->position);
77 self::assertSame('b', $resolution->field->name?->value);
78 }
79
80 public function testDeriveQueryReportsAnOrderByOrALimitBeforeTheOperator(): void
81 {
82 $semantics = new Semantics();
83 $ordered = $semantics->inspect('SELECT 1 ORDER BY 1 UNION SELECT 2');
84 $limited = $semantics->inspect('SELECT 1 LIMIT 1 UNION SELECT 2');
85
86 self::assertInstanceOf(Misuse::class, $ordered->facts->diagnostics[0]);
87 self::assertSame(MisuseRule::OrderByBeforeCompound, $ordered->facts->diagnostics[0]->rule);
88 self::assertInstanceOf(Misuse::class, $limited->facts->diagnostics[0]);
89 self::assertSame(MisuseRule::LimitBeforeCompound, $limited->facts->diagnostics[0]->rule);
90 }
91
92 public function testDeriveQueryKeepsAnUndeclaredFirstArmOpen(): void
93 {
94 $query = (new Semantics())->inspect('SELECT * FROM t UNION SELECT 1');
95
96 self::assertNull($query->fields());
97 self::assertInstanceOf(OpenStar::class, $query->facts->output?->projection[0]);
98 }
99
100 public function testRenderWritesTheArmsThenTheOrderingAndTheLimit(): void
101 {
102 $query = (new Semantics())->inspect('select 1 as a union all values (2) intersect select 3 except select 4 order by a desc limit 1 offset 1');
103
104 self::assertSame('SELECT 1 AS a UNION ALL VALUES (2) INTERSECT SELECT 3 EXCEPT SELECT 4 ORDER BY a DESC LIMIT 1 OFFSET 1', $query->toString());
105 }
106
107 public function testRenderWritesANewlyBuiltCompound(): void
108 {
109 $semantics = new Semantics();
110 $first = new ValuesClause([new ValueRow([new IntegerLiteral('1')])]);
111 $compound = new Compound($first, [new CompoundStep(CompoundOperator::Union, new Select([new ResultColumn(new IntegerLiteral('2'))]))], [], new Limit(new IntegerLiteral('1')));
112 $operation = new Operation($semantics->context(), $compound);
113
114 self::assertSame('VALUES (1) UNION SELECT 2 LIMIT 1', $operation->toString());
115 self::assertSame('column1', $operation->field(0)->name?->value);
116 }
117
118 public function testRenderRefusesAnOrderingLeftOnTheLastArm(): void
119 {
120 $ordered = (new Semantics())->inspect('SELECT 1 AS a ORDER BY a')->statement;
121 self::assertInstanceOf(Select::class, $ordered);
122
123 $this->expectExceptionMessage('ORDER BY and LIMIT after the last arm belong to the compound query.');
124
125 new Compound(new ValuesClause([new ValueRow([new NullLiteral()])]), [new CompoundStep(CompoundOperator::Union, $ordered)]);
126 }
127
128 public function testRenderRefusesAnOrderingAfterAValuesArm(): void
129 {
130 $this->expectExceptionMessage('ORDER BY and LIMIT cannot follow a VALUES clause.');
131
132 new Compound(new Select([new ResultColumn(new IntegerLiteral('1'))]), [new CompoundStep(CompoundOperator::Union, new ValuesClause([new ValueRow([new NullLiteral()])]))], [], new Limit(new IntegerLiteral('1')));
133 }
134
135 public function testRenderRefusesAnIntegerConstantAsAnOrdinaryOrderByTerm(): void
136 {
137 $this->expectExceptionMessage('An integer constant in ORDER BY is a result column position.');
138
139 new Compound(new Select([new ResultColumn(new IntegerLiteral('1'))]), [new CompoundStep(CompoundOperator::Union, new Select([new ResultColumn(new IntegerLiteral('2'))]))], [new SortTerm(new IntegerLiteral('1'))]);
140 }
141
142 public function testRenderRefusesASingleArm(): void
143 {
144 $this->expectExceptionMessage('A compound query has at least two arms.');
145
146 new Compound(new Select([new ResultColumn(new IntegerLiteral('1'))]), []);
147 }
148}
149