packages/sql-semantics-mysql/tests/Unit/Rules/Query/DerivedShapesTest.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\MySql\Model\Construction\Derivation;
11use SqlSemantics\Platform\MySql\Model\Statement\Fact\QueryFact;
12use SqlSemantics\Platform\MySql\Model\Statement\Identifier\Name;
13use SqlSemantics\Platform\MySql\Model\Statement\Shape\Field;
14use SqlSemantics\Platform\MySql\Model\Statement\Shape\OutputSlot;
15use SqlSemantics\Platform\MySql\Model\Statement\Type\Known;
16use SqlSemantics\Platform\MySql\Model\Statement\Type\Nullability;
17use SqlSemantics\Platform\MySql\Rules\Query\DerivedShapes;
18use SqlSemantics\Platform\MySql\Semantics;
19use SqlSemantics\Platform\MySql\Statement\Query\Problem\Misuse;
20use SqlSemantics\Platform\MySql\Statement\Query\Problem\MisuseRule;
21use SqlSemantics\Platform\MySql\Statement\Query\Problem\NameConversion;
22use SqlSemantics\Platform\MySql\Statement\Type\Integral;
23use SqlSemantics\Platform\MySql\Statement\Type\Kind\IntegralKind;
24
25#[CoversClass(DerivedShapes::class)]
26#[Medium]
27final class DerivedShapesTest extends TestCase
28{
29 public function testShapeTakesTheSlotsOfTheQuery(): void
30 {
31 $semantics = new Semantics();
32 $derivation = new Derivation($semantics->context());
33 $fact = new QueryFact([new Field(0, new OutputSlot(new Name('a'), new Known(new Integral(IntegralKind::Int)), Nullability::NotNull)), new Field(1, new OutputSlot(null, new Known(new Integral(IntegralKind::Int)), Nullability::NotNull, null, null, [new NameConversion('latin2')]))], $semantics->context()->columnNames);
34 $plain = (new DerivedShapes())->shape($fact, [], $derivation);
35 $listed = (new DerivedShapes())->shape($fact, [new Name('x'), new Name('y')], $derivation);
36
37 self::assertCount(2, $plain->slots);
38 self::assertTrue($plain->complete());
39 self::assertEquals([new NameConversion('latin2')], $plain->slots[1]->unnamed);
40 self::assertSame(['x', 'y'], array_map(static fn (OutputSlot $slot): ?string => $slot->name?->value, $listed->slots));
41 self::assertTrue($listed->complete());
42 self::assertSame([], $derivation->facts()->diagnostics);
43 }
44
45 public function testUniqueReportsADuplicateName(): void
46 {
47 $semantics = new Semantics();
48 $derivation = new Derivation($semantics->context());
49 (new DerivedShapes())->unique([new OutputSlot(new Name('a'), new Known(new Integral(IntegralKind::Int)), Nullability::NotNull), new OutputSlot(new Name('A'), new Known(new Integral(IntegralKind::Int)), Nullability::NotNull)], $derivation);
50
51 self::assertCount(1, $derivation->facts()->diagnostics);
52 self::assertInstanceOf(Misuse::class, $derivation->facts()->diagnostics[0]);
53 self::assertSame(MisuseRule::DuplicateColumn, $derivation->facts()->diagnostics[0]->rule);
54 }
55}
56