packages/sql-semantics-mysql/tests/Unit/Rules/Dml/SourceRelationsTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Rules\Dml;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10use SqlSemantics\Platform\MySql\Model\Statement\Declaration\Column;
11use SqlSemantics\Platform\MySql\Model\Statement\Declaration\Table;
12use SqlSemantics\Platform\MySql\Model\Statement\Identifier\Name;
13use SqlSemantics\Platform\MySql\Model\Statement\Identifier\QualifiedName;
14use SqlSemantics\Platform\MySql\Model\Statement\Reference\Column\MissingColumn;
15use SqlSemantics\Platform\MySql\Model\Statement\Type\Nullability;
16use SqlSemantics\Platform\MySql\Rules\Dml\SourceRelations;
17use SqlSemantics\Platform\MySql\Semantics;
18use SqlSemantics\Platform\MySql\Statement\Dml\WriteTarget;
19use SqlSemantics\Platform\MySql\Statement\Type\Integral;
20use SqlSemantics\Platform\MySql\Statement\Type\Kind\IntegralKind;
21
22#[CoversClass(SourceRelations::class)]
23#[Medium]
24final class SourceRelationsTest extends TestCase
25{
26    public function testVisibleOffersNothingForAGroupedSource(): void
27    {
28        $semantics = new Semantics();
29        $t = new Table(new QualifiedName(new Name('t'), new Name('(current)')), $semantics->profile(), [new Column(new Name('a'), new Integral(IntegralKind::Int), Nullability::NotNull), new Column(new Name('b'), new Integral(IntegralKind::BigInt))]);
30        $u = new Table(new QualifiedName(new Name('u'), new Name('(current)')), $semantics->profile(), [new Column(new Name('x'), new Integral(IntegralKind::Int)), new Column(new Name('y'), new Integral(IntegralKind::Int))]);
31        $operation = $semantics->inspect('INSERT INTO t (a) SELECT x FROM u GROUP BY x ON DUPLICATE KEY UPDATE b = y', [$t, $u]);
32
33        self::assertInstanceOf(MissingColumn::class, $operation->facts->diagnostics[0]);
34    }
35
36    public function testMembersAnswersTheJoinedRelations(): void
37    {
38        $semantics = new Semantics();
39        $t = new Table(new QualifiedName(new Name('t'), new Name('(current)')), $semantics->profile(), [new Column(new Name('a'), new Integral(IntegralKind::Int), Nullability::NotNull), new Column(new Name('b'), new Integral(IntegralKind::BigInt))]);
40        $u = new Table(new QualifiedName(new Name('u'), new Name('(current)')), $semantics->profile(), [new Column(new Name('x'), new Integral(IntegralKind::Int)), new Column(new Name('y'), new Integral(IntegralKind::Int))]);
41        $operation = $semantics->inspect('INSERT INTO t (a) SELECT u.x FROM u JOIN (SELECT 1 AS z) AS d ON TRUE ON DUPLICATE KEY UPDATE b = z + u.y', [$t, $u]);
42
43        self::assertSame([], $operation->facts->diagnostics);
44        self::assertNull((new SourceRelations())->members(new WriteTarget(new QualifiedName(new Name('t')))));
45    }
46}
47