packages/sql-semantics-sqlite/tests/Unit/Rules/Query/RelationNamesTest.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\Sqlite\Model\Construction\Derivation;
11use SqlSemantics\Platform\Sqlite\Model\Statement\Identifier\Name;
12use SqlSemantics\Platform\Sqlite\Model\Statement\Reference\Missing\MissingInput;
13use SqlSemantics\Platform\Sqlite\Model\Statement\Shape\Field;
14use SqlSemantics\Platform\Sqlite\Model\Statement\Shape\OutputSlot;
15use SqlSemantics\Platform\Sqlite\Rules\Query\RelationNames;
16use SqlSemantics\Platform\Sqlite\Semantics;
17use SqlSemantics\Platform\Sqlite\Statement\Query\Select;
18use SqlSemantics\Platform\Sqlite\Statement\Query\ValuesClause;
19
20#[CoversClass(RelationNames::class)]
21#[Medium]
22final class RelationNamesTest extends TestCase
23{
24    public function testShapeNamesTheColumnsAsSqliteDoesBeforeResolution(): void
25    {
26        $semantics = new Semantics();
27        $create = $semantics->inspect('CREATE TABLE t (a INTEGER NOT NULL, b TEXT)');
28        $query = $semantics->inspect('SELECT a COLLATE nocase, true, a, a, a, (a), a, t.b, 1 + 1, "zz", oid, A FROM t', [$create]);
29        self::assertInstanceOf(Select::class, $query->statement);
30        $shape = (new RelationNames())->shape($query->facts->output ?? self::fail('The query has an output.'), $query->statement, new Derivation($semantics->context()));
31
32        self::assertSame(['a', 'column2', 'a:1', 'a:2', 'a:3', 'a:4', null, 'b', '1 + 1', 'zz', 'oid', null], array_map(static fn (OutputSlot $slot): ?string => $slot->name?->value, $shape->slots));
33        self::assertSame($query->field(0)->slot, $shape->slots[0]->origin);
34        self::assertSame($query->field(0)->type, $shape->slots[0]->type);
35        self::assertTrue($shape->complete());
36    }
37
38    public function testShapeLetsAnAliasWinAndCountsItAmongTheDuplicates(): void
39    {
40        $semantics = new Semantics();
41        $query = $semantics->inspect('SELECT a AS a, a, a AS "a:1", b AS A FROM t');
42        self::assertInstanceOf(Select::class, $query->statement);
43        $shape = (new RelationNames())->shape($query->facts->output ?? self::fail('The query has an output.'), $query->statement, new Derivation($semantics->context()));
44
45        self::assertSame(['a', 'a:1', 'a:2', 'A:3'], array_map(static fn (OutputSlot $slot): ?string => $slot->name?->value, $shape->slots));
46    }
47
48    public function testShapeKeepsTheMissingInputsAndLeavesTheNamesAfterAnOpenStarUnnamed(): void
49    {
50        $semantics = new Semantics();
51        $query = $semantics->inspect('SELECT a, *, b FROM t');
52        self::assertInstanceOf(Select::class, $query->statement);
53        $shape = (new RelationNames())->shape($query->facts->output ?? self::fail('The query has an output.'), $query->statement, new Derivation($semantics->context()));
54
55        self::assertSame(['a', null], array_map(static fn (OutputSlot $slot): ?string => $slot->name?->value, $shape->slots));
56        self::assertSame([[], ['the declaration of relation t']], array_map(static fn (OutputSlot $slot): array => array_map(static fn (MissingInput $input): string => $input->describe(), $slot->unnamed), $shape->slots));
57        self::assertFalse($shape->complete());
58        self::assertSame('the declaration of relation t', $shape->missing[0]->describe());
59    }
60
61    public function testShapeKeepsAnUndecidedNameAndTheNamesAfterItDependent(): void
62    {
63        $semantics = new Semantics();
64        $query = $semantics->inspect('SELECT *, 2 AS two FROM (SELECT *, 1 AS one FROM u)');
65        self::assertInstanceOf(Select::class, $query->statement);
66        $shape = (new RelationNames())->shape($query->facts->output ?? self::fail('The query has an output.'), $query->statement, new Derivation($semantics->context()));
67
68        self::assertSame([null, null], array_map(static fn (OutputSlot $slot): ?string => $slot->name?->value, $shape->slots));
69        self::assertSame('the declaration of relation u', $shape->slots[0]->unnamed[0]->describe());
70        self::assertNotSame([], $shape->slots[1]->unnamed);
71    }
72
73    public function testShapeNamesTheColumnsAfterTheLeftmostArm(): void
74    {
75        $query = (new Semantics())->inspect('SELECT * FROM (SELECT 1+1, 2 AS b UNION SELECT 3, 4), (VALUES ("zz", 1, true, "q" COLLATE nocase))', []);
76
77        self::assertSame(['1+1', 'b', 'zz', 'column2', 'column3', 'q'], array_map(static fn (Field $field): ?string => $field->name?->value, $query->fields()->items ?? []));
78    }
79
80    public function testNamedPrefersTheAliasThenTheWrittenWordThenTheText(): void
81    {
82        $semantics = new Semantics();
83        $create = $semantics->inspect('CREATE TABLE t (a INTEGER NOT NULL, b TEXT)');
84        $query = $semantics->inspect('SELECT oid, a AS x, "zz", true, TRUE AS z, 1, * FROM t', [$create]);
85        $names = new RelationNames();
86        $select = $query->statement;
87
88        self::assertInstanceOf(Select::class, $select);
89        self::assertSame('oid', $names->named($query->field(0), $select, 0)?->value);
90        self::assertSame('x', $names->named($query->field(1), $select, 1)?->value);
91        self::assertSame('zz', $names->named($query->field(2), $select, 2)?->value);
92        self::assertSame('true', $names->named($query->field(3), $select, 3)?->value);
93        self::assertSame('z', $names->named($query->field(4), $select, 4)?->value);
94        self::assertSame('1', $names->named($query->field(5), $select, 5)?->value);
95        self::assertSame('a', $names->named($query->field(6), $select, 6)?->value);
96    }
97
98    public function testNamedReadsTheWordOfAValuesColumnOrItsPosition(): void
99    {
100        $query = (new Semantics())->inspect('VALUES (x, 1)');
101        $values = $query->statement;
102
103        self::assertInstanceOf(ValuesClause::class, $values);
104        self::assertSame('x', (new RelationNames())->named($query->field(0), $values, 0)?->value);
105        self::assertSame('column2', (new RelationNames())->named($query->field(1), $values, 1)?->value);
106    }
107
108    public function testListedRenamesTruthWordsAndRepeatedNames(): void
109    {
110        self::assertSame(['column1', 'a', 'A:1'], array_map(static fn (?Name $name): ?string => $name?->value, (new RelationNames())->listed([new Name('true'), new Name('a'), new Name('A')])));
111        self::assertSame([], (new RelationNames())->listed([]));
112    }
113
114    public function testUniqueAppendsACounterUntilTheFourthAttempt(): void
115    {
116        $names = new RelationNames();
117        $name = new Name('a');
118
119        self::assertSame($name, $names->unique($name, []));
120        self::assertSame($name, $names->unique($name, ['b' => true]));
121        self::assertSame('a:1', $names->unique($name, ['a' => true])?->value);
122        self::assertSame('a:3', $names->unique($name, ['a' => true, 'a:1' => true, 'a:2' => true])?->value);
123        self::assertSame('a:4', $names->unique($name, ['a' => true, 'a:1' => true, 'a:2' => true, 'a:3' => true])?->value);
124        self::assertNull($names->unique($name, ['a' => true, 'a:1' => true, 'a:2' => true, 'a:3' => true, 'a:4' => true]));
125        self::assertNull($names->unique(null, []));
126    }
127
128    public function testUniqueDropsAnExistingCounterAndComparesWithoutCase(): void
129    {
130        $names = new RelationNames();
131
132        self::assertSame('a:1', $names->unique(new Name('a:7'), ['a:7' => true])?->value);
133        self::assertSame('A:2', $names->unique(new Name('A'), ['a' => true, 'a:1' => true])?->value);
134        self::assertSame(':1', $names->unique(new Name(':9'), [':9' => true])?->value);
135    }
136}
137