packages/sql-semantics-sqlite/tests/Unit/Rules/Mutation/MutationScopeTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Rules\Mutation;
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\Resolution\Environment;
12use SqlSemantics\Platform\Sqlite\Model\Statement\Identifier\Name;
13use SqlSemantics\Platform\Sqlite\Model\Statement\Identifier\QualifiedName;
14use SqlSemantics\Platform\Sqlite\Model\Statement\Reference\Column\MissingColumn;
15use SqlSemantics\Platform\Sqlite\Model\Statement\Reference\Column\ResolvedColumn;
16use SqlSemantics\Platform\Sqlite\Model\Statement\Reference\Table\DeclaredTable;
17use SqlSemantics\Platform\Sqlite\Model\Statement\Shape\OutputSlot;
18use SqlSemantics\Platform\Sqlite\Rules\Mutation\MutationScope;
19use SqlSemantics\Platform\Sqlite\Semantics;
20use SqlSemantics\Platform\Sqlite\Statement\Expression\ColumnUse;
21use SqlSemantics\Platform\Sqlite\Statement\Expression\Literal\IntegerLiteral;
22use SqlSemantics\Platform\Sqlite\Statement\Expression\RowExpression;
23use SqlSemantics\Platform\Sqlite\Statement\Mutation\Assignment;
24use SqlSemantics\Platform\Sqlite\Statement\Mutation\MutationTarget;
25use SqlSemantics\Platform\Sqlite\Statement\Mutation\RowAssignment;
26use SqlSemantics\Platform\Sqlite\Statement\Mutation\Update;
27use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\ArityMismatch;
28use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\ArityRule;
29use SqlSemantics\Platform\Sqlite\Statement\Query\ResultColumn;
30use SqlSemantics\Platform\Sqlite\Statement\Query\Star;
31use SqlSemantics\Platform\Sqlite\Statement\Query\TableStar;
32
33#[CoversClass(MutationScope::class)]
34#[Medium]
35final class MutationScopeTest extends TestCase
36{
37    public function testOpenBindsTheWithClauseAndMakesTheTargetVisible(): void
38    {
39        $semantics = new Semantics();
40        $t = $semantics->analyze('CREATE TABLE t (id INTEGER PRIMARY KEY, a INTEGER NOT NULL, b TEXT)');
41        $statement = $semantics->analyze('WITH w AS (SELECT 1 AS q) UPDATE t AS x SET a = 1', [$t])->statement;
42        $derivation = new Derivation($semantics->context([$t]));
43        $outer = $derivation->environment();
44
45        self::assertInstanceOf(Update::class, $statement);
46        [$base, $target] = (new MutationScope())->open($statement->target, $statement->with, $derivation, $outer);
47        self::assertSame($outer, $base->outer);
48        self::assertNotNull($base->commonTable(new Name('w')));
49        self::assertSame($statement->target, $target->relation);
50        self::assertSame('x', $target->alias?->value);
51        self::assertSame($statement->target->name, $target->name);
52        self::assertCount(3, $target->shape->slots);
53        self::assertCount(1, $target->implicit);
54        self::assertInstanceOf(DeclaredTable::class, $derivation->facts()->relation($statement->target)->table);
55        self::assertSame($outer, (new MutationScope())->open($statement->target, null, $derivation, $outer)[0]);
56    }
57
58    public function testNamesReportsColumnsAClosedTargetCertainlyLacks(): void
59    {
60        $semantics = new Semantics();
61        $t = $semantics->analyze('CREATE TABLE t (id INTEGER PRIMARY KEY, a INTEGER NOT NULL, b TEXT)');
62        $closed = new Derivation($semantics->context([$t]));
63        $open = new Derivation($semantics->context());
64        $scope = new MutationScope();
65        $known = $scope->open(new MutationTarget(new QualifiedName(new Name('t'))), null, $closed, $closed->environment())[1];
66        $unknown = $scope->open(new MutationTarget(new QualifiedName(new Name('t'))), null, $open, $open->environment())[1];
67        $scope->names([new Name('A'), new Name('rowid'), new Name('zz')], $known, $closed);
68        $scope->names([new Name('zz')], $unknown, $open);
69        $diagnostics = $closed->facts()->diagnostics;
70
71        self::assertCount(1, $diagnostics);
72        self::assertInstanceOf(MissingColumn::class, $diagnostics[0]);
73        self::assertSame('zz', $diagnostics[0]->name->value);
74        self::assertSame([], $open->facts()->diagnostics);
75    }
76
77    public function testAssignChecksTheColumnsAndTheWidthOfEachAssignment(): void
78    {
79        $semantics = new Semantics();
80        $t = $semantics->analyze('CREATE TABLE t (id INTEGER PRIMARY KEY, a INTEGER NOT NULL, b TEXT)');
81        $derivation = new Derivation($semantics->context([$t]));
82        $scope = new MutationScope();
83        $target = $scope->open(new MutationTarget(new QualifiedName(new Name('t'))), null, $derivation, $derivation->environment())[1];
84        $environment = new Environment($derivation->context, $derivation->environment(), [$target]);
85        $value = new ColumnUse(new Name('b'));
86        $scope->assign([
87            new Assignment(new Name('a'), $value),
88            new RowAssignment([new Name('a'), new Name('b')], new RowExpression([new IntegerLiteral('1'), new IntegerLiteral('2')])),
89            new RowAssignment([new Name('a')], new RowExpression([new IntegerLiteral('1'), new IntegerLiteral('2')])),
90            new RowAssignment([new Name('a'), new Name('zz')], new IntegerLiteral('1')),
91        ], $target, $derivation, $environment);
92        $facts = $derivation->facts();
93        $resolution = $facts->scalar($value)->resolution;
94
95        self::assertInstanceOf(ResolvedColumn::class, $resolution);
96        self::assertSame($target->relation, $resolution->relation);
97        self::assertCount(3, $facts->diagnostics);
98        self::assertInstanceOf(ArityMismatch::class, $facts->diagnostics[0]);
99        self::assertSame(ArityRule::RowAssignment, $facts->diagnostics[0]->rule);
100        self::assertSame([1, 2], [$facts->diagnostics[0]->expected, $facts->diagnostics[0]->actual]);
101        self::assertInstanceOf(MissingColumn::class, $facts->diagnostics[1]);
102        self::assertInstanceOf(ArityMismatch::class, $facts->diagnostics[2]);
103        self::assertSame([2, 1], [$facts->diagnostics[2]->expected, $facts->diagnostics[2]->actual]);
104    }
105
106    public function testReturningIsNullWithoutColumnsAndProjectsTheTargetOtherwise(): void
107    {
108        $semantics = new Semantics();
109        $t = $semantics->analyze('CREATE TABLE t (id INTEGER PRIMARY KEY, a INTEGER NOT NULL, b TEXT)');
110        $derivation = new Derivation($semantics->context([$t]));
111        $scope = new MutationScope();
112        $target = $scope->open(new MutationTarget(new QualifiedName(new Name('t'))), null, $derivation, $derivation->environment())[1];
113        $base = $derivation->environment();
114        $fact = $scope->returning([new Star(), new TableStar(new Name('t')), new ResultColumn(new ColumnUse(new Name('b')), new Name('q'))], $target, $derivation, $base);
115
116        self::assertNull($scope->returning([], $target, $derivation, $base));
117        self::assertNotNull($fact);
118        self::assertSame(['id', 'a', 'b', 'id', 'a', 'b', 'q'], array_map(static fn (OutputSlot $slot): ?string => $slot->name?->value, $fact->shape->slots));
119        self::assertSame($t->declarations()[0]->columns[2], $fact->shape->slots[6]->declaration());
120        self::assertTrue($fact->shape->complete());
121        self::assertSame([], $derivation->facts()->diagnostics);
122    }
123}
124