packages/sql-semantics-mysql/tests/Unit/Rules/ColumnResolverTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Rules;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10use SqlSemantics\Platform\MySql\Model\Resolution\Environment;
11use SqlSemantics\Platform\MySql\Model\Resolution\VisibleRelation;
12use SqlSemantics\Platform\MySql\Model\Statement\Declaration\Column;
13use SqlSemantics\Platform\MySql\Model\Statement\Declaration\Table;
14use SqlSemantics\Platform\MySql\Model\Statement\Identifier\Name;
15use SqlSemantics\Platform\MySql\Model\Statement\Identifier\QualifiedName;
16use SqlSemantics\Platform\MySql\Model\Statement\Reference\Column\AliasTarget;
17use SqlSemantics\Platform\MySql\Model\Statement\Reference\Column\ConditionalColumn;
18use SqlSemantics\Platform\MySql\Model\Statement\Reference\Column\MissingColumn;
19use SqlSemantics\Platform\MySql\Model\Statement\Reference\Column\ResolvedColumn;
20use SqlSemantics\Platform\MySql\Model\Statement\Reference\Missing\SessionState;
21use SqlSemantics\Platform\MySql\Model\Statement\Type\Invalid;
22use SqlSemantics\Platform\MySql\Model\Statement\Type\Nullability;
23use SqlSemantics\Platform\MySql\Rules\ColumnResolver;
24use SqlSemantics\Platform\MySql\Rules\Query\Having\GroupedRow;
25use SqlSemantics\Platform\MySql\Semantics;
26use SqlSemantics\Platform\MySql\Statement\Expression\Comparison;
27use SqlSemantics\Platform\MySql\Statement\Name\AmbiguousAlias;
28use SqlSemantics\Platform\MySql\Statement\Query\Select;
29use SqlSemantics\Platform\MySql\Statement\Type\Integral;
30use SqlSemantics\Platform\MySql\Statement\Type\Kind\IntegralKind;
31
32#[CoversClass(ColumnResolver::class)]
33#[Medium]
34final class ColumnResolverTest extends TestCase
35{
36    public function testFindPrefersAColumnOfTheFromClauseToAnAlias(): void
37    {
38        $semantics = new Semantics();
39        $table = new Table(new QualifiedName(new Name('t'), new Name('(current)')), $semantics->profile(), [new Column(new Name('a'), new Integral(IntegralKind::Int)), new Column(new Name('b'), new Integral(IntegralKind::BigInt))]);
40        $operation = $semantics->inspect('SELECT b AS a FROM t GROUP BY a HAVING a > 0', [$table]);
41        $select = $operation->statement;
42        self::assertInstanceOf(Select::class, $select);
43        $group = $select->groupBy;
44        self::assertNotNull($group);
45        $resolution = $operation->facts->scalar($group->items[0]->expression)->resolution;
46
47        self::assertInstanceOf(ResolvedColumn::class, $resolution);
48        self::assertSame($table->columns[0], $resolution->declaration());
49        self::assertSame([], $operation->facts->diagnostics);
50    }
51
52    public function testFindFallsBackToTheAliasOfASelectListItem(): void
53    {
54        $semantics = new Semantics();
55        $table = new Table(new QualifiedName(new Name('t'), new Name('(current)')), $semantics->profile(), [new Column(new Name('a'), new Integral(IntegralKind::Int))]);
56        $operation = $semantics->inspect('SELECT a AS x FROM t GROUP BY x ORDER BY x + 1', [$table]);
57        $select = $operation->statement;
58        self::assertInstanceOf(Select::class, $select);
59        $group = $select->groupBy;
60        self::assertNotNull($group);
61        $resolution = $operation->facts->scalar($group->items[0]->expression)->resolution;
62
63        self::assertInstanceOf(AliasTarget::class, $resolution);
64        self::assertSame($operation->field('x'), $resolution->field);
65        self::assertSame([], $operation->facts->diagnostics);
66    }
67
68    public function testFindReportsAnAliasOfSeveralDifferentItems(): void
69    {
70        $semantics = new Semantics();
71        $table = new Table(new QualifiedName(new Name('t'), new Name('(current)')), $semantics->profile(), [new Column(new Name('a'), new Integral(IntegralKind::Int)), new Column(new Name('b'), new Integral(IntegralKind::Int))]);
72        $operation = $semantics->inspect('SELECT a AS x, b AS x FROM t GROUP BY x', [$table]);
73
74        self::assertCount(1, $operation->facts->diagnostics);
75        self::assertInstanceOf(AmbiguousAlias::class, $operation->facts->diagnostics[0]);
76        self::assertSame('x', $operation->facts->diagnostics[0]->name->value);
77    }
78
79    public function testFindIsConditionalWhileAnUndeclaredRelationCouldOwnTheName(): void
80    {
81        $operation = (new Semantics())->inspect('SELECT 1 AS x FROM u GROUP BY x');
82        $select = $operation->statement;
83        self::assertInstanceOf(Select::class, $select);
84        $group = $select->groupBy;
85        self::assertNotNull($group);
86        $resolution = $operation->facts->scalar($group->items[0]->expression)->resolution;
87
88        self::assertInstanceOf(ConditionalColumn::class, $resolution);
89        self::assertSame([], $resolution->candidates);
90    }
91
92    public function testFindIgnoresAliasesForAQualifiedName(): void
93    {
94        $semantics = new Semantics();
95        $table = new Table(new QualifiedName(new Name('t'), new Name('(current)')), $semantics->profile(), [new Column(new Name('a'), new Integral(IntegralKind::Int))]);
96        $operation = $semantics->inspect('SELECT a AS x FROM t', [$table]);
97
98        self::assertInstanceOf(MissingColumn::class, (new ColumnResolver())->find(new Environment($operation->context, null, [], [], [$operation->field('x')]), new Name('x'), new QualifiedName(new Name('t'))));
99        self::assertInstanceOf(AliasTarget::class, (new ColumnResolver())->find(new Environment($operation->context, null, [], [], [$operation->field('x')]), new Name('X')));
100    }
101
102    public function testAliasTreatsItemsComputingTheSameExpressionAsOne(): void
103    {
104        $operation = (new Semantics())->inspect('SELECT 1 AS x, 1 AS x, 2 AS x', []);
105        $fields = $operation->fields()->items ?? [];
106
107        self::assertInstanceOf(AliasTarget::class, (new ColumnResolver())->alias(new Name('x'), [$fields[0], $fields[1]]));
108        $single = (new ColumnResolver())->alias(new Name('x'), [$fields[2]]);
109        self::assertInstanceOf(AliasTarget::class, $single);
110        self::assertSame($fields[2], $single->field);
111        $ambiguous = (new ColumnResolver())->alias(new Name('x'), [$fields[0], $fields[1], $fields[2]]);
112        self::assertInstanceOf(AmbiguousAlias::class, $ambiguous);
113        self::assertCount(3, $ambiguous->candidates);
114    }
115
116    public function testUnlistedAnswersTheOccurrencesThatMayGiveAHavingPositionTheName(): void
117    {
118        $semantics = new Semantics();
119        $star = $semantics->inspect('SELECT * FROM u HAVING c > 0');
120        $grouped = $semantics->inspect('SELECT 1 FROM u GROUP BY c HAVING c > 0');
121        $other = $semantics->inspect('SELECT 1 FROM u GROUP BY d HAVING c > 0');
122        $starSelect = $star->statement;
123        $groupedSelect = $grouped->statement;
124        self::assertInstanceOf(Select::class, $starSelect);
125        self::assertInstanceOf(Select::class, $groupedSelect);
126        self::assertInstanceOf(Comparison::class, $starSelect->having);
127        self::assertInstanceOf(Comparison::class, $groupedSelect->having);
128        $starred = $star->facts->scalar($starSelect->having->left)->resolution;
129        $group = $grouped->facts->scalar($groupedSelect->having->left)->resolution;
130
131        self::assertInstanceOf(ConditionalColumn::class, $starred);
132        self::assertSame([$starSelect->from], $starred->relations);
133        self::assertInstanceOf(ConditionalColumn::class, $group);
134        self::assertSame([$groupedSelect->from], $group->relations);
135        self::assertCount(1, $other->facts->diagnostics);
136        self::assertInstanceOf(MissingColumn::class, $other->facts->diagnostics[0]);
137        self::assertSame([], (new ColumnResolver())->unlisted(new GroupedRow([], [], true), new Environment($star->context), new Name('c')));
138    }
139
140    public function testFactAnswersTheFactsOfTheColumnOrTheProblem(): void
141    {
142        $semantics = new Semantics();
143        $operation = $semantics->inspect('SELECT a FROM t', [$semantics->inspect('CREATE TABLE t (a INT NOT NULL)')]);
144        $resolution = $operation->field('a')->resolution;
145        self::assertInstanceOf(ResolvedColumn::class, $resolution);
146        $environment = new Environment($operation->context, null, [], [], [$operation->field('a')]);
147
148        self::assertSame(Nullability::NotNull, (new ColumnResolver())->fact($environment, new Name('a'))->nullability);
149        self::assertInstanceOf(AliasTarget::class, (new ColumnResolver())->fact($environment, new Name('a'))->resolution);
150        self::assertInstanceOf(MissingColumn::class, (new ColumnResolver())->fact($environment, new Name('b'))->resolution);
151        self::assertInstanceOf(Invalid::class, (new ColumnResolver())->fact($environment, new Name('b'))->type);
152    }
153
154    public function testRowTellsWhetherATriggerRowIsVisible(): void
155    {
156        $semantics = new Semantics();
157        $operation = $semantics->inspect('SELECT new.a FROM t AS new', [$semantics->inspect('CREATE TABLE t (a INT)')]);
158        $resolution = $operation->field('a')->resolution;
159        self::assertInstanceOf(ResolvedColumn::class, $resolution);
160        $visible = new Environment($operation->context, null, [new VisibleRelation($resolution->relation, $operation->facts->relation($resolution->relation)->shape, new Name('NEW'))]);
161
162        self::assertTrue((new ColumnResolver())->row(new Environment($operation->context, $visible), new QualifiedName(new Name('new'))));
163        self::assertFalse((new ColumnResolver())->row($visible, new QualifiedName(new Name('OLD'))));
164        self::assertFalse((new ColumnResolver())->row($visible, new QualifiedName(new Name('NEW'), new Name('db'))));
165        self::assertFalse((new ColumnResolver())->row(new Environment($operation->context), new QualifiedName(new Name('NEW'))));
166    }
167
168    public function testFindIsConditionalWhileAnItemWithoutADecidedNameCouldHaveTheName(): void
169    {
170        $semantics = new Semantics();
171        $table = new Table(new QualifiedName(new Name('t'), new Name('(current)')), $semantics->profile(), [new Column(new Name('a'), new Integral(IntegralKind::Int))]);
172        $operation = $semantics->inspect("SELECT 'é' FROM t GROUP BY q", [$table]);
173        $select = $operation->statement;
174        self::assertInstanceOf(Select::class, $select);
175        $group = $select->groupBy;
176        self::assertNotNull($group);
177        $resolution = $operation->facts->scalar($group->items[0]->expression)->resolution;
178
179        self::assertInstanceOf(ConditionalColumn::class, $resolution);
180        self::assertEquals([new SessionState('character_set_client')], $resolution->missing);
181        self::assertSame([], $operation->facts->diagnostics);
182    }
183
184    public function testUnnamedAnswersTheInputsTheItemNamesDependOn(): void
185    {
186        $operation = (new Semantics())->inspect("SELECT 'é' AS x, 'ü'");
187
188        self::assertEquals([new SessionState('character_set_client')], (new ColumnResolver())->unnamed([$operation->field(0), $operation->field(1)]));
189    }
190
191    public function testUndecidedJoinsTheInputsOfOpenOccurrencesAndUnnamedItems(): void
192    {
193        $operation = (new Semantics())->inspect('SELECT a FROM u');
194        $input = $operation->inputRelation();
195        self::assertNotNull($input);
196        $resolution = (new ColumnResolver())->undecided(new Name('a'), [], [new VisibleRelation($input, $operation->facts->relation($input)->shape)], [new SessionState('character_set_client')]);
197
198        self::assertSame([$input], $resolution->relations);
199        self::assertCount(2, $resolution->missing);
200    }
201}
202