packages/sql-semantics-sqlite/tests/Unit/Statement/Expression/Operator/BinaryTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Expression\Operator;
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\ResolvedColumn;
12use SqlSemantics\Platform\Sqlite\Model\Statement\Shape\Field;
13use SqlSemantics\Platform\Sqlite\Model\Statement\Type\Choice;
14use SqlSemantics\Platform\Sqlite\Model\Statement\Type\Known;
15use SqlSemantics\Platform\Sqlite\Model\Statement\Type\Nullability;
16use SqlSemantics\Platform\Sqlite\Model\Statement\Type\NullOnly;
17use SqlSemantics\Platform\Sqlite\Semantics;
18use SqlSemantics\Platform\Sqlite\Statement\Expression\Literal\IntegerLiteral;
19use SqlSemantics\Platform\Sqlite\Statement\Expression\Literal\NullLiteral;
20use SqlSemantics\Platform\Sqlite\Statement\Expression\Operator\Binary;
21use SqlSemantics\Platform\Sqlite\Statement\Expression\Operator\BinaryOperator;
22use SqlSemantics\Platform\Sqlite\Statement\Expression\Operator\Unary;
23use SqlSemantics\Platform\Sqlite\Statement\Expression\Operator\UnaryOperator;
24use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\ArityMismatch;
25use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\ArityRule;
26use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\Misuse;
27use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\MisuseRule;
28use SqlSemantics\Platform\Sqlite\Statement\Query\ResultColumn;
29use SqlSemantics\Platform\Sqlite\Statement\Query\Select;
30use SqlSemantics\Platform\Sqlite\Statement\Type\Storage;
31
32#[CoversClass(Binary::class)]
33#[Medium]
34final class BinaryTest extends TestCase
35{
36    public function testDeriveScalarComparisonsAreIntegerAndNullWhenAnOperandCanBe(): void
37    {
38        $semantics = new Semantics();
39        $query = $semantics->inspect('SELECT a = b, a < 1, a & 1, a << b, a == 1, 1 = NULL FROM t', [$semantics->inspect('CREATE TABLE t (a INTEGER NOT NULL, b TEXT)')]);
40
41        self::assertInstanceOf(Known::class, $query->field(0)->type);
42        self::assertSame(Storage::Integer, $query->field(0)->type->descriptor);
43        self::assertSame(Nullability::Nullable, $query->field(0)->nullability);
44        self::assertSame(Nullability::NotNull, $query->field(1)->nullability);
45        self::assertSame(Nullability::NotNull, $query->field(2)->nullability);
46        self::assertSame(Nullability::Nullable, $query->field(3)->nullability);
47        self::assertSame(Nullability::NotNull, $query->field(4)->nullability);
48        self::assertInstanceOf(NullOnly::class, $query->field(5)->type);
49    }
50
51    public function testDeriveScalarIsFamilyIsNeverNull(): void
52    {
53        $semantics = new Semantics();
54        $query = $semantics->inspect('SELECT b IS NULL, b IS NOT NULL, b IS DISTINCT FROM NULL, NULL IS NOT DISTINCT FROM NULL FROM t', [$semantics->inspect('CREATE TABLE t (a INTEGER NOT NULL, b TEXT)')]);
55        $nullability = array_map(static fn (Field $field): Nullability => $field->nullability, $query->fields()->items ?? []);
56
57        self::assertSame([Nullability::NotNull, Nullability::NotNull, Nullability::NotNull, Nullability::NotNull], $nullability);
58        self::assertInstanceOf(Known::class, $query->field(3)->type);
59        self::assertSame(Storage::Integer, $query->field(3)->type->descriptor);
60    }
61
62    public function testDeriveScalarLogicalOperatorsAreIntegerAndCanBeNullWhenAnOperandCan(): void
63    {
64        $semantics = new Semantics();
65        $query = $semantics->inspect('SELECT a AND 1, a OR b, 1 AND NULL FROM t', [$semantics->inspect('CREATE TABLE t (a INTEGER NOT NULL, b TEXT)')]);
66
67        self::assertInstanceOf(Known::class, $query->field(0)->type);
68        self::assertSame(Storage::Integer, $query->field(0)->type->descriptor);
69        self::assertSame(Nullability::NotNull, $query->field(0)->nullability);
70        self::assertSame(Nullability::Nullable, $query->field(1)->nullability);
71        self::assertInstanceOf(Known::class, $query->field(2)->type);
72        self::assertSame(Storage::Integer, $query->field(2)->type->descriptor);
73        self::assertSame(Nullability::Nullable, $query->field(2)->nullability);
74    }
75
76    public function testDeriveScalarArithmeticIsIntegerOrRealUnlessAnOperandIsCertainlyReal(): void
77    {
78        $semantics = new Semantics();
79        $query = $semantics->inspect('SELECT a + b, a - 1, a * 1, a + 1.5, 9223372036854775808 + 1, NULL + 1 FROM t', [$semantics->inspect('CREATE TABLE t (a INTEGER NOT NULL, b TEXT)')]);
80
81        self::assertInstanceOf(Choice::class, $query->field(0)->type);
82        self::assertSame([Storage::Integer, Storage::Real], $query->field(0)->type->alternatives);
83        self::assertSame(Nullability::Nullable, $query->field(0)->nullability);
84        self::assertInstanceOf(Choice::class, $query->field(1)->type);
85        self::assertSame(Nullability::NotNull, $query->field(1)->nullability);
86        self::assertInstanceOf(Choice::class, $query->field(2)->type);
87        self::assertInstanceOf(Known::class, $query->field(3)->type);
88        self::assertSame(Storage::Real, $query->field(3)->type->descriptor);
89        self::assertInstanceOf(Known::class, $query->field(4)->type);
90        self::assertSame(Storage::Real, $query->field(4)->type->descriptor);
91        self::assertInstanceOf(NullOnly::class, $query->field(5)->type);
92        self::assertSame(Nullability::Nullable, $query->field(5)->nullability);
93    }
94
95    public function testDeriveScalarDivisionAndRemainderCanAlwaysBeNull(): void
96    {
97        $semantics = new Semantics();
98        $query = $semantics->inspect('SELECT a / 2, a % 2, 1.5 / 2, NULL / 2 FROM t', [$semantics->inspect('CREATE TABLE t (a INTEGER NOT NULL, b TEXT)')]);
99
100        self::assertInstanceOf(Choice::class, $query->field(0)->type);
101        self::assertSame([Storage::Integer, Storage::Real], $query->field(0)->type->alternatives);
102        self::assertSame(Nullability::Nullable, $query->field(0)->nullability);
103        self::assertInstanceOf(Choice::class, $query->field(1)->type);
104        self::assertSame(Nullability::Nullable, $query->field(1)->nullability);
105        self::assertInstanceOf(Known::class, $query->field(2)->type);
106        self::assertSame(Storage::Real, $query->field(2)->type->descriptor);
107        self::assertSame(Nullability::Nullable, $query->field(2)->nullability);
108        self::assertInstanceOf(NullOnly::class, $query->field(3)->type);
109    }
110
111    public function testDeriveScalarConcatenationIsTextUnlessAnOperandIsNull(): void
112    {
113        $semantics = new Semantics();
114        $query = $semantics->inspect("SELECT a || b, 'a' || 1, 1 || NULL FROM t", [$semantics->inspect('CREATE TABLE t (a INTEGER NOT NULL, b TEXT)')]);
115
116        self::assertInstanceOf(Known::class, $query->field(0)->type);
117        self::assertSame(Storage::Text, $query->field(0)->type->descriptor);
118        self::assertSame(Nullability::Nullable, $query->field(0)->nullability);
119        self::assertSame(Nullability::NotNull, $query->field(1)->nullability);
120        self::assertInstanceOf(NullOnly::class, $query->field(2)->type);
121    }
122
123    public function testDeriveScalarJsonExtractionYieldsNullableTextOrAValue(): void
124    {
125        $semantics = new Semantics();
126        $query = $semantics->inspect("SELECT b -> 'x', b ->> 'x', NULL ->> 'x', 'a' -> NULL FROM t", [$semantics->inspect('CREATE TABLE t (a INTEGER NOT NULL, b TEXT)')]);
127
128        self::assertInstanceOf(Known::class, $query->field(0)->type);
129        self::assertSame(Storage::Text, $query->field(0)->type->descriptor);
130        self::assertSame(Nullability::Nullable, $query->field(0)->nullability);
131        self::assertInstanceOf(Choice::class, $query->field(1)->type);
132        self::assertSame([Storage::Integer, Storage::Real, Storage::Text], $query->field(1)->type->alternatives);
133        self::assertSame(Nullability::Nullable, $query->field(1)->nullability);
134        self::assertInstanceOf(NullOnly::class, $query->field(2)->type);
135        self::assertInstanceOf(NullOnly::class, $query->field(3)->type);
136    }
137
138    public function testDeriveScalarRecordsTheFactsOfBothOperands(): void
139    {
140        $semantics = new Semantics();
141        $query = $semantics->inspect('SELECT a + b FROM t', [$semantics->inspect('CREATE TABLE t (a INTEGER NOT NULL, b TEXT)')]);
142        $sum = $query->field(0)->expression;
143
144        self::assertInstanceOf(Binary::class, $sum);
145        self::assertSame(BinaryOperator::Add, $sum->operator);
146        self::assertInstanceOf(ResolvedColumn::class, $query->facts->scalar($sum->left)->resolution);
147        self::assertSame(Nullability::NotNull, $query->facts->scalar($sum->left)->nullability);
148        self::assertSame(Nullability::Nullable, $query->facts->scalar($sum->right)->nullability);
149        self::assertNull($query->facts->scalar($sum)->resolution);
150    }
151
152    public function testDeriveScalarDependsOnAnUnboundParameter(): void
153    {
154        $query = (new Semantics())->inspect('SELECT ? + 1');
155
156        self::assertInstanceOf(Choice::class, $query->field(0)->type);
157        self::assertSame(Nullability::Dependent, $query->field(0)->nullability);
158    }
159
160    public function testDeriveScalarAdmitsRowsOfOneWidthInComparisons(): void
161    {
162        $query = (new Semantics())->inspect('SELECT (1, 2) < (1, 3), (1, 2) IS (1, 2), (SELECT 1, 2) = (1, 2)', []);
163
164        self::assertSame([], $query->facts->diagnostics);
165        self::assertInstanceOf(Known::class, $query->field(0)->type);
166        self::assertSame(Storage::Integer, $query->field(0)->type->descriptor);
167        self::assertSame(Nullability::NotNull, $query->field(1)->nullability);
168    }
169
170    public function testDeriveScalarReportsARowValueBesideASingleValue(): void
171    {
172        $query = (new Semantics())->inspect('SELECT (1, 2) = 3', []);
173
174        self::assertCount(1, $query->facts->diagnostics);
175        self::assertInstanceOf(Misuse::class, $query->facts->diagnostics[0]);
176        self::assertSame(MisuseRule::TooManyValueColumns, $query->facts->diagnostics[0]->rule);
177        self::assertSame('row value misused', $query->facts->diagnostics[0]->message());
178    }
179
180    public function testDeriveScalarReportsRowsOfDifferentWidths(): void
181    {
182        $query = (new Semantics())->inspect('SELECT (1, 2) = (1, 2, 3)', []);
183
184        self::assertCount(1, $query->facts->diagnostics);
185        self::assertInstanceOf(ArityMismatch::class, $query->facts->diagnostics[0]);
186        self::assertSame(ArityRule::RowComparison, $query->facts->diagnostics[0]->rule);
187        self::assertSame(2, $query->facts->diagnostics[0]->expected);
188        self::assertSame(3, $query->facts->diagnostics[0]->actual);
189    }
190
191    public function testDeriveScalarReportsARowValueOperandOfAnyOtherOperator(): void
192    {
193        $semantics = new Semantics();
194        $sum = $semantics->inspect('SELECT (1, 2) + 1', []);
195        $conjunction = $semantics->inspect('SELECT (1, 2) AND 1', []);
196
197        self::assertCount(1, $sum->facts->diagnostics);
198        self::assertInstanceOf(Misuse::class, $sum->facts->diagnostics[0]);
199        self::assertSame(MisuseRule::TooManyValueColumns, $sum->facts->diagnostics[0]->rule);
200        self::assertCount(1, $conjunction->facts->diagnostics);
201        self::assertInstanceOf(Misuse::class, $conjunction->facts->diagnostics[0]);
202    }
203
204    public function testRenderWritesWordedOperatorsAsKeywordsAndOthersAsSymbols(): void
205    {
206        $query = (new Semantics())->inspect('select a is not distinct from b AS c1, a<>1 AS c2, a->>\'x\' AS c3, a and b or 1 AS c4 from t');
207
208        self::assertSame('SELECT a IS NOT DISTINCT FROM b AS c1, a <> 1 AS c2, a ->> \'x\' AS c3, a AND b OR 1 AS c4 FROM t', $query->toString());
209    }
210
211    public function testRenderKeepsTheWrittenAssociation(): void
212    {
213        $semantics = new Semantics();
214        $tight = $semantics->inspect('SELECT 1 + 2 * 3');
215        $grouped = $semantics->inspect('SELECT (1 + 2) * 3');
216        $expression = $tight->field(0)->expression;
217
218        self::assertInstanceOf(Binary::class, $expression);
219        self::assertSame(BinaryOperator::Add, $expression->operator);
220        self::assertInstanceOf(Binary::class, $expression->right);
221        self::assertSame('SELECT 1 + 2 * 3', $tight->toString());
222        self::assertSame('SELECT (1 + 2) * 3', $grouped->toString());
223    }
224
225    public function testRenderWritesANewlyBuiltOperation(): void
226    {
227        $semantics = new Semantics();
228        $product = new Binary(BinaryOperator::Multiply, new IntegerLiteral('2'), new IntegerLiteral('3'));
229        $operation = new Operation($semantics->context(), new Select([new ResultColumn(new Binary(BinaryOperator::Add, new IntegerLiteral('1'), $product))]));
230
231        self::assertSame('SELECT 1 + 2 * 3', $operation->toString());
232        self::assertInstanceOf(Choice::class, $operation->field(0)->type);
233    }
234
235    public function testRefusesALeftOperandThatEndsInAWeakerOperator(): void
236    {
237        $sum = new Binary(BinaryOperator::Add, new IntegerLiteral('1'), new IntegerLiteral('2'));
238
239        $this->expectExceptionMessage('The left operand needs parentheses to keep its place.');
240
241        new Binary(BinaryOperator::Multiply, $sum, new IntegerLiteral('3'));
242    }
243
244    public function testRefusesARightOperandThatStartsWithAnOperatorThatIsNotTighter(): void
245    {
246        $sum = new Binary(BinaryOperator::Add, new IntegerLiteral('1'), new IntegerLiteral('2'));
247
248        $this->expectExceptionMessage('The right operand needs parentheses to keep its place.');
249
250        new Binary(BinaryOperator::Add, new IntegerLiteral('3'), $sum);
251    }
252
253    public function testRefusesIsFollowedByAPrefixNot(): void
254    {
255        $this->expectExceptionMessage('IS followed by a prefix NOT is read as IS NOT.');
256
257        new Binary(BinaryOperator::Is, new IntegerLiteral('1'), new Unary(UnaryOperator::Not, new NullLiteral()));
258    }
259}
260