packages/sql-semantics-mysql/tests/Unit/Rules/Query/CommonTablesTest.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\MySql\Model\Construction\Derivation;
11use SqlSemantics\Platform\MySql\Model\Resolution\CommonBinding;
12use SqlSemantics\Platform\MySql\Model\Statement\Fact\QueryFact;
13use SqlSemantics\Platform\MySql\Model\Statement\Identifier\Name;
14use SqlSemantics\Platform\MySql\Model\Statement\Reference\Missing\SessionState;
15use SqlSemantics\Platform\MySql\Model\Statement\Reference\Table\MissingTable;
16use SqlSemantics\Platform\MySql\Model\Statement\Shape\Field;
17use SqlSemantics\Platform\MySql\Model\Statement\Shape\OutputSlot;
18use SqlSemantics\Platform\MySql\Model\Statement\Shape\RowShape;
19use SqlSemantics\Platform\MySql\Model\Statement\Type\Known;
20use SqlSemantics\Platform\MySql\Model\Statement\Type\Nullability;
21use SqlSemantics\Platform\MySql\Rules\Query\CommonTables;
22use SqlSemantics\Platform\MySql\Semantics;
23use SqlSemantics\Platform\MySql\Statement\Literal\NumberLiteral;
24use SqlSemantics\Platform\MySql\Statement\Query\ParenthesizedQuery;
25use SqlSemantics\Platform\MySql\Statement\Query\Problem\RecursiveReference;
26use SqlSemantics\Platform\MySql\Statement\Query\Select;
27use SqlSemantics\Platform\MySql\Statement\Query\SelectExpression;
28use SqlSemantics\Platform\MySql\Statement\Query\Set\SetOperation;
29use SqlSemantics\Platform\MySql\Statement\Query\With\CommonTableExpression;
30use SqlSemantics\Platform\MySql\Statement\Relation\Dual;
31use SqlSemantics\Platform\MySql\Statement\Type\Integral;
32use SqlSemantics\Platform\MySql\Statement\Type\Kind\IntegralKind;
33
34#[CoversClass(CommonTables::class)]
35#[Medium]
36final class CommonTablesTest extends TestCase
37{
38    public function testBindSeesEarlierTablesOnly(): void
39    {
40        $operation = (new Semantics())->inspect('WITH a AS (SELECT 1 AS x), b AS (SELECT x FROM a) SELECT x FROM b', []);
41        $forward = (new Semantics())->inspect('WITH b AS (SELECT x FROM a), a AS (SELECT 1 AS x) SELECT 1', []);
42
43        self::assertSame([], $operation->facts->diagnostics);
44        self::assertInstanceOf(Known::class, $operation->field('x')->type);
45        self::assertInstanceOf(MissingTable::class, $forward->facts->diagnostics[0]);
46    }
47
48    public function testExtendedAddsTablesWithoutAQueryLevel(): void
49    {
50        $semantics = new Semantics();
51        $derivation = new Derivation($semantics->context());
52        $outer = $derivation->environment();
53        $extended = (new CommonTables())->extended($outer, [new CommonBinding(new Name('c'), new Dual(), new RowShape([]))]);
54
55        self::assertSame($outer->outer, $extended->outer);
56        self::assertNotNull($extended->commonTable(new Name('c')));
57    }
58
59    public function testPendingFindsTheRecursiveTableARightOperandRefersTo(): void
60    {
61        $semantics = new Semantics();
62        $derivation = new Derivation($semantics->context());
63        $pending = new CommonBinding(new Name('c'), new Dual(), new RowShape([], [new RecursiveReference(new Name('c'))]));
64        $scope = (new CommonTables())->extended($derivation->environment(), [$pending]);
65        $refers = $semantics->inspect('SELECT 1 FROM c')->statement;
66        $other = $semantics->inspect('SELECT 1 FROM d')->statement;
67
68        self::assertInstanceOf(Select::class, $refers);
69        self::assertInstanceOf(Select::class, $other);
70        self::assertSame($pending, (new CommonTables())->pending($scope, $refers, $derivation));
71        self::assertNull((new CommonTables())->pending($scope, $other, $derivation));
72    }
73
74    public function testAnchoredBindsTheColumnsOfTheNonrecursivePart(): void
75    {
76        $semantics = new Semantics();
77        $derivation = new Derivation($semantics->context());
78        $pending = new CommonBinding(new Name('c'), new Dual(), new RowShape([], [new RecursiveReference(new Name('c'))]));
79        $scope = (new CommonTables())->extended($derivation->environment(), [$pending]);
80        $anchor = new QueryFact([new Field(0, new OutputSlot(new Name('n'), new Known(new Integral(IntegralKind::BigInt)), Nullability::NotNull))], $semantics->context()->columnNames);
81        $binding = (new CommonTables())->anchored($scope, $pending, $anchor, $derivation)->commonTable(new Name('c'));
82
83        self::assertNotNull($binding);
84        self::assertSame('n', $binding->shape->slots[0]->name?->value);
85        self::assertSame(Nullability::Nullable, $binding->shape->slots[0]->nullability);
86        self::assertTrue($binding->shape->complete());
87    }
88
89    public function testShapeRenamesTheColumnsByTheColumnList(): void
90    {
91        $semantics = new Semantics();
92        $derivation = new Derivation($semantics->context());
93        $table = new CommonTableExpression(new Name('c'), [new Name('x')], new Select([], [new SelectExpression(new NumberLiteral('1'))]));
94        $anchor = new QueryFact([new Field(0, new OutputSlot(new Name('n'), new Known(new Integral(IntegralKind::BigInt)), Nullability::NotNull))], $semantics->context()->columnNames);
95        $shape = (new CommonTables())->shape(new CommonBinding(new Name('c'), $table, new RowShape([])), $anchor, $derivation);
96
97        self::assertSame('x', $shape->slots[0]->name?->value);
98    }
99
100    public function testNullableMakesEveryColumnNullable(): void
101    {
102        $semantics = new Semantics();
103        $anchor = new QueryFact([new Field(0, new OutputSlot(new Name('n'), new Known(new Integral(IntegralKind::BigInt)), Nullability::NotNull))], $semantics->context()->columnNames);
104
105        self::assertSame(Nullability::Nullable, (new CommonTables())->nullable($anchor)->fields()?->at(0)->nullability);
106    }
107
108    public function testOperandsAnswersTheChainInWrittenOrder(): void
109    {
110        $query = (new Semantics())->inspect('(SELECT 1 UNION SELECT 2 UNION SELECT 3)')->statement;
111
112        self::assertInstanceOf(ParenthesizedQuery::class, $query);
113        self::assertCount(3, (new CommonTables())->operands($query));
114        self::assertInstanceOf(SetOperation::class, $query->query);
115        self::assertSame([$query->query->right], array_slice((new CommonTables())->operands($query->query), 2));
116        self::assertSame([$query->query->right], (new CommonTables())->operands($query->query->right));
117    }
118
119    public function testRefersFindsAnUnqualifiedReference(): void
120    {
121        $semantics = new Semantics();
122        $derivation = new Derivation($semantics->context());
123        $query = $semantics->inspect('SELECT 1 FROM db.c, (SELECT 1 FROM c) AS d')->statement;
124        $qualified = $semantics->inspect('SELECT 1 FROM db.c')->statement;
125
126        self::assertInstanceOf(Select::class, $query);
127        self::assertInstanceOf(Select::class, $qualified);
128        self::assertTrue((new CommonTables())->refers($query, new Name('c'), $derivation));
129        self::assertFalse((new CommonTables())->refers($qualified, new Name('c'), $derivation));
130    }
131
132    public function testOperandsWalksALeadingUnion(): void
133    {
134        $query = (new Semantics('mysql-5.6.51'))->inspect('SELECT 1 UNION SELECT 2 LIMIT 1 UNION SELECT 3')->statement;
135
136        self::assertInstanceOf(SetOperation::class, $query);
137        self::assertCount(3, (new CommonTables())->operands($query));
138    }
139
140    public function testShapeKeepsTheInputsAnUnnamedColumnDependsOn(): void
141    {
142        $operation = (new Semantics())->inspect("WITH RECURSIVE c AS (SELECT 'é' UNION ALL SELECT x FROM c) SELECT 1");
143
144        self::assertSame([], $operation->facts->diagnostics);
145    }
146
147    public function testNullableKeepsTheInputsAnUnnamedColumnDependsOn(): void
148    {
149        $operation = (new Semantics())->inspect("WITH RECURSIVE c AS (SELECT 'é' UNION ALL SELECT 1 FROM c) SELECT * FROM c");
150
151        self::assertEquals([new SessionState('character_set_client')], $operation->field(0)->slot->unnamed);
152    }
153}
154