packages/sql-semantics-mysql/tests/Unit/Statement/Query/Set/SetOperationTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Query\Set;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10use SqlSemantics\Platform\MySql\Model\Statement\Declaration\Column;
11use SqlSemantics\Platform\MySql\Model\Statement\Declaration\Table;
12use SqlSemantics\Platform\MySql\Model\Statement\Identifier\Name;
13use SqlSemantics\Platform\MySql\Model\Statement\Identifier\QualifiedName;
14use SqlSemantics\Platform\MySql\Model\Statement\Shape\Field;
15use SqlSemantics\Platform\MySql\Model\Statement\Type\Known;
16use SqlSemantics\Platform\MySql\Model\Statement\Type\Nullability;
17use SqlSemantics\Platform\MySql\Semantics;
18use SqlSemantics\Platform\MySql\Statement\Literal\NumberLiteral;
19use SqlSemantics\Platform\MySql\Statement\Name\ColumnUse;
20use SqlSemantics\Platform\MySql\Statement\Query\Clause\RowLimit;
21use SqlSemantics\Platform\MySql\Statement\Query\Locking\LockingClause;
22use SqlSemantics\Platform\MySql\Statement\Query\Locking\LockStrength;
23use SqlSemantics\Platform\MySql\Statement\Query\OrderItem;
24use SqlSemantics\Platform\MySql\Statement\Query\ParenthesizedQuery;
25use SqlSemantics\Platform\MySql\Statement\Query\Problem\CountedList;
26use SqlSemantics\Platform\MySql\Statement\Query\Problem\CountMismatch;
27use SqlSemantics\Platform\MySql\Statement\Query\QueryExpression;
28use SqlSemantics\Platform\MySql\Statement\Query\QueryStatement;
29use SqlSemantics\Platform\MySql\Statement\Query\Select;
30use SqlSemantics\Platform\MySql\Statement\Query\SelectExpression;
31use SqlSemantics\Platform\MySql\Statement\Query\Set\SetOperation;
32use SqlSemantics\Platform\MySql\Statement\Query\Set\SetOperator;
33use SqlSemantics\Platform\MySql\Statement\Query\Set\SetQuantifier;
34use SqlSemantics\Platform\MySql\Statement\Type\Integral;
35use SqlSemantics\Platform\MySql\Statement\Type\Kind\IntegralKind;
36
37#[CoversClass(SetOperation::class)]
38#[Medium]
39final class SetOperationTest extends TestCase
40{
41    public function testDeriveStatementRecordsTheRowsAsTheOutput(): void
42    {
43        $semantics = new Semantics();
44        $t = new Table(new QualifiedName(new Name('t'), new Name('(current)')), $semantics->profile(), [
45            new Column(new Name('a'), new Integral(IntegralKind::Int), Nullability::NotNull),
46            new Column(new Name('b'), new Integral(IntegralKind::BigInt), Nullability::Nullable),
47        ]);
48        $u = new Table(new QualifiedName(new Name('u'), new Name('(current)')), $semantics->profile(), [
49            new Column(new Name('a'), new Integral(IntegralKind::Int), Nullability::NotNull),
50            new Column(new Name('c'), new Integral(IntegralKind::Int), Nullability::NotNull),
51        ]);
52        $operation = $semantics->inspect('SELECT a, b FROM t UNION ALL SELECT a, c FROM u', [$t, $u]);
53
54        self::assertInstanceOf(SetOperation::class, $operation->statement);
55        self::assertSame($operation->facts->query($operation->statement), $operation->facts->output);
56        self::assertSame(SetQuantifier::All, $operation->statement->quantifier);
57        self::assertSame([], $operation->facts->diagnostics);
58    }
59
60    public function testDeriveQueryNamesTheColumnsAfterTheFirstOperandAndCombinesNullability(): void
61    {
62        $semantics = new Semantics();
63        $t = new Table(new QualifiedName(new Name('t'), new Name('(current)')), $semantics->profile(), [
64            new Column(new Name('a'), new Integral(IntegralKind::Int), Nullability::NotNull),
65            new Column(new Name('b'), new Integral(IntegralKind::BigInt), Nullability::Nullable),
66        ]);
67        $u = new Table(new QualifiedName(new Name('u'), new Name('(current)')), $semantics->profile(), [
68            new Column(new Name('a'), new Integral(IntegralKind::Int), Nullability::NotNull),
69            new Column(new Name('c'), new Integral(IntegralKind::Int), Nullability::NotNull),
70        ]);
71        $union = $semantics->inspect('SELECT a, b FROM t UNION SELECT a, c FROM u', [$t, $u]);
72        $intersect = $semantics->inspect('SELECT a, b FROM t INTERSECT SELECT a, c FROM u', [$t, $u]);
73        $except = $semantics->inspect('SELECT a, c FROM u EXCEPT SELECT a, b FROM t', [$t, $u]);
74
75        self::assertSame(['a', 'b'], array_map(static fn (Field $field): ?string => $field->name?->value, $union->fields()->items ?? []));
76        self::assertSame(Nullability::Nullable, $union->field('b')->nullability);
77        self::assertSame(Nullability::NotNull, $intersect->field('b')->nullability);
78        self::assertSame(Nullability::NotNull, $except->field('c')->nullability);
79        self::assertInstanceOf(Known::class, $union->field('a')->type);
80        self::assertNull($union->field('a')->column());
81    }
82
83    public function testDeriveQueryReportsOperandsOfDifferentLengths(): void
84    {
85        $operation = (new Semantics())->inspect('SELECT 1 UNION SELECT 1, 2');
86
87        self::assertCount(1, $operation->facts->diagnostics);
88        self::assertInstanceOf(CountMismatch::class, $operation->facts->diagnostics[0]);
89        self::assertSame(CountedList::SetOperands, $operation->facts->diagnostics[0]->list);
90    }
91
92    public function testDeriveQueryLeavesTheOutputOpenOverAnUndeclaredFirstOperand(): void
93    {
94        $operation = (new Semantics())->inspect('SELECT * FROM t UNION SELECT 1');
95
96        self::assertNull($operation->fields());
97        self::assertNotNull($operation->shape());
98        self::assertFalse($operation->shape()->complete());
99    }
100
101    public function testRenderWritesTheOperandsLeftDeepAndKeepsParentheses(): void
102    {
103        $semantics = new Semantics();
104
105        self::assertSame('SELECT 1 UNION SELECT 2 EXCEPT DISTINCT SELECT 3', $semantics->inspect('select 1 union select 2 except distinct select 3')->toString());
106        self::assertSame('SELECT 1 UNION SELECT 2 INTERSECT SELECT 3', $semantics->inspect('SELECT 1 UNION SELECT 2 INTERSECT SELECT 3')->toString());
107        self::assertSame('SELECT 1 INTERSECT (SELECT 2 UNION SELECT 3)', $semantics->inspect('SELECT 1 INTERSECT (SELECT 2 UNION SELECT 3)')->toString());
108        self::assertInstanceOf(SetOperation::class, $semantics->inspect('SELECT 1 UNION SELECT 2 INTERSECT SELECT 3')->statement);
109    }
110
111    public function testANestedOperationOnTheRightIsRejected(): void
112    {
113        $one = new Select([], [new SelectExpression(new NumberLiteral('1'))]);
114        $two = new Select([], [new SelectExpression(new NumberLiteral('2'))]);
115        $three = new Select([], [new SelectExpression(new NumberLiteral('3'))]);
116
117        $this->expectExceptionMessage('A set operation on the right of another is written in parentheses unless it binds more tightly.');
118
119        new SetOperation($one, SetOperator::Union, null, new SetOperation($two, SetOperator::Except, null, $three));
120    }
121
122    public function testALooserOperationOnTheLeftOfIntersectIsRejected(): void
123    {
124        $one = new Select([], [new SelectExpression(new NumberLiteral('1'))]);
125        $two = new Select([], [new SelectExpression(new NumberLiteral('2'))]);
126        $three = new Select([], [new SelectExpression(new NumberLiteral('3'))]);
127
128        $this->expectExceptionMessage('A looser set operation on the left of INTERSECT is written in parentheses.');
129
130        new SetOperation(new SetOperation($one, SetOperator::Union, null, $two), SetOperator::Intersect, null, $three);
131    }
132
133    public function testALastOperandWithItsOwnOrderingIsRejected(): void
134    {
135        $one = new Select([], [new SelectExpression(new NumberLiteral('1'))]);
136        $two = new Select([], [new SelectExpression(new ColumnUse(new Name('a')))], null, null, null, null, [], null, [new OrderItem(new ColumnUse(new Name('a')))]);
137
138        $this->expectExceptionMessage('The last operand of a set operation has no ORDER BY, LIMIT, INTO or locking clause of its own unless it is written in parentheses.');
139
140        new SetOperation($one, SetOperator::Union, null, $two);
141    }
142
143    public function testAQueryExpressionOnTheRightIsRejected(): void
144    {
145        $one = new Select([], [new SelectExpression(new NumberLiteral('1'))]);
146        $two = new Select([], [new SelectExpression(new NumberLiteral('2'))]);
147
148        $this->expectExceptionMessage('A query with a WITH clause or with ordering of its own is written in parentheses as a set operand.');
149
150        new SetOperation($one, SetOperator::Union, null, new QueryExpression(null, new ParenthesizedQuery($two), [], new RowLimit(new NumberLiteral('1'))));
151    }
152
153    public function testAQueryStatementAsAnOperandIsRejected(): void
154    {
155        $one = new Select([], [new SelectExpression(new NumberLiteral('1'))]);
156        $two = new Select([], [new SelectExpression(new NumberLiteral('2'))]);
157
158        $this->expectExceptionMessage('A query with INTO or locking clauses is written in parentheses as a set operand.');
159
160        new SetOperation(new QueryStatement(new ParenthesizedQuery($one), [new LockingClause(LockStrength::Update)]), SetOperator::Union, null, $two);
161    }
162}
163