packages/sql-semantics-sqlite/tests/Unit/Statement/Relation/JoinChainTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Relation;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10use SqlSemantics\Platform\Sqlite\Model\Statement\Identifier\Name;
11use SqlSemantics\Platform\Sqlite\Model\Statement\Identifier\QualifiedName;
12use SqlSemantics\Platform\Sqlite\Model\Statement\Operation;
13use SqlSemantics\Platform\Sqlite\Model\Statement\Shape\Field;
14use SqlSemantics\Platform\Sqlite\Model\Statement\Type\Choice;
15use SqlSemantics\Platform\Sqlite\Model\Statement\Type\Nullability;
16use SqlSemantics\Platform\Sqlite\Semantics;
17use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\Misuse;
18use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\MisuseRule;
19use SqlSemantics\Platform\Sqlite\Statement\Query\Select;
20use SqlSemantics\Platform\Sqlite\Statement\Query\Star;
21use SqlSemantics\Platform\Sqlite\Statement\Relation\JoinChain;
22use SqlSemantics\Platform\Sqlite\Statement\Relation\JoinOn;
23use SqlSemantics\Platform\Sqlite\Statement\Relation\JoinOperator;
24use SqlSemantics\Platform\Sqlite\Statement\Relation\JoinStep;
25use SqlSemantics\Platform\Sqlite\Statement\Relation\JoinUsing;
26use SqlSemantics\Platform\Sqlite\Statement\Relation\TableInput;
27
28#[CoversClass(JoinChain::class)]
29#[Medium]
30final class JoinChainTest extends TestCase
31{
32    public function testDeriveRelationShowsAMergedColumnOnce(): void
33    {
34        $semantics = new Semantics();
35        $t = $semantics->inspect('CREATE TABLE t (id INTEGER PRIMARY KEY, a INTEGER NOT NULL, b TEXT)');
36        $u = $semantics->inspect('CREATE TABLE u (a INTEGER NOT NULL, c TEXT)');
37        $using = $semantics->inspect('SELECT * FROM t JOIN u USING (a)', [$t, $u]);
38        $natural = $semantics->inspect('SELECT * FROM t NATURAL JOIN u', [$t, $u]);
39        $fields = $using->fields();
40
41        self::assertInstanceOf(Select::class, $using->statement);
42        self::assertInstanceOf(JoinChain::class, $using->statement->from);
43        self::assertNotNull($fields);
44        self::assertSame(['id', 'a', 'b', 'c'], array_map(static fn (Field $field): ?string => $field->name?->value, $fields->items));
45        self::assertSame(['id', 'a', 'b', 'c'], array_map(static fn (Field $field): ?string => $field->name?->value, $natural->fields()->items ?? []));
46        self::assertSame($t->declarations()[0]->columns[1], $using->field('a')->column());
47        self::assertNull($using->facts->relation($using->statement->from)->table);
48        self::assertCount(4, $using->facts->relation($using->statement->from)->shape->slots);
49        self::assertSame([], $using->facts->diagnostics);
50    }
51
52    public function testDeriveRelationMakesTheExtendedSideNullable(): void
53    {
54        $semantics = new Semantics();
55        $t = $semantics->inspect('CREATE TABLE t (id INTEGER PRIMARY KEY, a INTEGER NOT NULL, b TEXT)');
56        $u = $semantics->inspect('CREATE TABLE u (a INTEGER NOT NULL, c TEXT)');
57        $query = $semantics->inspect('SELECT * FROM t LEFT JOIN u ON t.a = u.a', [$t, $u]);
58        $fields = $query->fields();
59
60        self::assertNotNull($fields);
61        self::assertSame(['id', 'a', 'b', 'a', 'c'], array_map(static fn (Field $field): ?string => $field->name?->value, $fields->items));
62        self::assertSame(Nullability::NotNull, $query->field(1)->nullability);
63        self::assertSame(Nullability::Nullable, $query->field(3)->nullability);
64        self::assertSame($u->declarations()[0]->columns[0], $query->field(3)->column());
65    }
66
67    public function testDeriveRelationCoalescesTheMergedColumnOfARightOrFullJoin(): void
68    {
69        $semantics = new Semantics();
70        $t = $semantics->inspect('CREATE TABLE t (id INTEGER PRIMARY KEY, a INTEGER NOT NULL, b TEXT)');
71        $u = $semantics->inspect('CREATE TABLE u (a INTEGER NOT NULL, c TEXT)');
72        $right = $semantics->inspect('SELECT * FROM t RIGHT JOIN u USING (a)', [$t, $u]);
73        $full = $semantics->inspect('SELECT * FROM t FULL OUTER JOIN u USING (a)', [$t, $u]);
74
75        self::assertSame(['id', 'a', 'b', 'c'], array_map(static fn (Field $field): ?string => $field->name?->value, $right->fields()->items ?? []));
76        self::assertInstanceOf(Choice::class, $right->field('a')->type);
77        self::assertSame(Nullability::Nullable, $right->field('id')->nullability);
78        self::assertSame(Nullability::Nullable, $right->field('b')->nullability);
79        self::assertSame(Nullability::Nullable, $right->field('c')->nullability);
80        self::assertSame($t->declarations()[0]->columns[1], $right->field('a')->column());
81        self::assertInstanceOf(Choice::class, $full->field('a')->type);
82        self::assertSame(Nullability::Nullable, $full->field('c')->nullability);
83    }
84
85    public function testDeriveRelationReportsAConstraintWrittenWithoutAJoin(): void
86    {
87        $semantics = new Semantics();
88        $t = $semantics->inspect('CREATE TABLE t (id INTEGER PRIMARY KEY, a INTEGER NOT NULL, b TEXT)');
89        $on = $semantics->inspect('SELECT * FROM t ON 1', [$t]);
90        $using = $semantics->inspect('SELECT * FROM t USING (a)', [$t]);
91
92        self::assertInstanceOf(Select::class, $on->statement);
93        self::assertInstanceOf(JoinChain::class, $on->statement->from);
94        self::assertInstanceOf(JoinOn::class, $on->statement->from->constraint);
95        self::assertSame([], $on->statement->from->steps);
96        self::assertInstanceOf(Misuse::class, $on->facts->diagnostics[0]);
97        self::assertSame(MisuseRule::OnWithoutJoin, $on->facts->diagnostics[0]->rule);
98        self::assertInstanceOf(Misuse::class, $using->facts->diagnostics[0]);
99        self::assertSame(MisuseRule::UsingWithoutJoin, $using->facts->diagnostics[0]->rule);
100        self::assertCount(3, $on->fields()->items ?? []);
101    }
102
103    public function testDeriveRelationReportsAnUnknownJoinTypeAndANaturalJoinWithAConstraint(): void
104    {
105        $semantics = new Semantics();
106        $t = $semantics->inspect('CREATE TABLE t (id INTEGER PRIMARY KEY, a INTEGER NOT NULL, b TEXT)');
107        $u = $semantics->inspect('CREATE TABLE u (a INTEGER NOT NULL, c TEXT)');
108        $unknown = $semantics->inspect('SELECT * FROM t INNER LEFT JOIN u', [$t, $u]);
109        $named = $semantics->inspect('SELECT * FROM t LEFT WRONG JOIN u', [$t, $u]);
110        $natural = $semantics->inspect('SELECT * FROM t NATURAL JOIN u ON 1', [$t, $u]);
111
112        self::assertInstanceOf(Misuse::class, $unknown->facts->diagnostics[0]);
113        self::assertSame(MisuseRule::UnknownJoinType, $unknown->facts->diagnostics[0]->rule);
114        self::assertCount(5, $unknown->fields()->items ?? []);
115        self::assertInstanceOf(Misuse::class, $named->facts->diagnostics[0]);
116        self::assertSame(MisuseRule::UnknownJoinType, $named->facts->diagnostics[0]->rule);
117        self::assertInstanceOf(Misuse::class, $natural->facts->diagnostics[0]);
118        self::assertSame(MisuseRule::NaturalJoinWithConstraint, $natural->facts->diagnostics[0]->rule);
119        self::assertCount(1, $natural->facts->diagnostics);
120    }
121
122    public function testDeriveRelationListsCommaSeparatedTablesSideBySide(): void
123    {
124        $semantics = new Semantics();
125        $t = $semantics->inspect('CREATE TABLE t (id INTEGER PRIMARY KEY, a INTEGER NOT NULL, b TEXT)');
126        $u = $semantics->inspect('CREATE TABLE u (a INTEGER NOT NULL, c TEXT)');
127        $query = $semantics->inspect('SELECT * FROM t, u', [$t, $u]);
128
129        self::assertInstanceOf(Select::class, $query->statement);
130        self::assertInstanceOf(JoinChain::class, $query->statement->from);
131        self::assertTrue($query->statement->from->steps[0]->operator->comma);
132        self::assertSame(['id', 'a', 'b', 'a', 'c'], array_map(static fn (Field $field): ?string => $field->name?->value, $query->fields()->items ?? []));
133        self::assertSame([], $query->facts->diagnostics);
134    }
135
136    public function testDeriveRelationLeavesTheShapeOpenForUndeclaredTables(): void
137    {
138        $query = (new Semantics())->inspect('SELECT * FROM t JOIN u USING (a)');
139        $shape = $query->shape();
140
141        self::assertNull($query->fields());
142        self::assertNotNull($shape);
143        self::assertSame([], $shape->slots);
144        self::assertSame(['the declaration of relation t', 'the declaration of relation u'], array_map(static fn (object $missing): string => $missing->describe(), $shape->missing));
145        self::assertSame([], $query->facts->diagnostics);
146    }
147
148    public function testRenderWritesTheFirstTermItsConstraintAndEachStep(): void
149    {
150        $semantics = new Semantics();
151        $t = new TableInput(new QualifiedName(new Name('t')));
152        $u = new TableInput(new QualifiedName(new Name('u')));
153        $built = new Operation($semantics->context(), new Select([new Star()], new JoinChain($t, [new JoinStep(new JoinOperator(true), $u, new JoinUsing([new Name('a')]))])));
154
155        self::assertSame('SELECT * FROM t, u USING (a)', $built->toString());
156        self::assertSame('SELECT * FROM t LEFT OUTER JOIN u ON t.a = u.a CROSS JOIN t t2', $semantics->inspect('select * from t left outer join u on t.a = u.a cross join t t2')->toString());
157        self::assertSame('SELECT * FROM t ON 1', $semantics->inspect('SELECT * FROM t ON 1')->toString());
158    }
159
160    public function testRejectsASingleTermWithoutAConstraint(): void
161    {
162        $this->expectExceptionMessage('A single term without a constraint is no join chain.');
163
164        new JoinChain(new TableInput(new QualifiedName(new Name('t'))), []);
165    }
166
167    public function testRejectsAChainAsTheFirstTerm(): void
168    {
169        $t = new TableInput(new QualifiedName(new Name('t')));
170        $chain = new JoinChain($t, [new JoinStep(new JoinOperator(), new TableInput(new QualifiedName(new Name('u'))))]);
171
172        $this->expectExceptionMessage('A join chain used as a term is written in parentheses.');
173
174        new JoinChain($chain, []);
175    }
176}
177