packages/sql-semantics-mysql/tests/Unit/Statement/Dml/DefaultRequestTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\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\Type\Known;
15use SqlSemantics\Platform\MySql\Model\Statement\Type\Nullability;
16use SqlSemantics\Platform\MySql\Semantics;
17use SqlSemantics\Platform\MySql\Statement\Dml\DefaultRequest;
18use SqlSemantics\Platform\MySql\Statement\Dml\Insert\InsertRows;
19use SqlSemantics\Platform\MySql\Statement\Dml\Problem\WriteMisuse;
20use SqlSemantics\Platform\MySql\Statement\Dml\Problem\WriteRule;
21use SqlSemantics\Platform\MySql\Statement\Type\Integral;
22use SqlSemantics\Platform\MySql\Statement\Type\Kind\IntegralKind;
23
24#[CoversClass(DefaultRequest::class)]
25#[Medium]
26final class DefaultRequestTest extends TestCase
27{
28    public function testDeriveScalarTakesTheAssignedColumn(): void
29    {
30        $semantics = new Semantics();
31        $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))]);
32        $operation = $semantics->inspect('INSERT INTO t (b, a) VALUES (DEFAULT, DEFAULT)', [$t]);
33        self::assertInstanceOf(InsertRows::class, $operation->statement);
34        $fact = $operation->facts->scalar($operation->statement->rows[0]->values[1]);
35
36        self::assertEquals(new Known(new Integral(IntegralKind::Int)), $fact->type);
37        self::assertSame(Nullability::NotNull, $fact->nullability);
38        self::assertSame([], $operation->facts->diagnostics);
39    }
40
41    public function testDeriveScalarReportsDefaultOutsideAnAssignment(): void
42    {
43        $operation = (new Semantics())->inspect('VALUES ROW(DEFAULT)');
44
45        self::assertCount(1, $operation->facts->diagnostics);
46        self::assertInstanceOf(WriteMisuse::class, $operation->facts->diagnostics[0]);
47        self::assertSame(WriteRule::DefaultOutsideInsert, $operation->facts->diagnostics[0]->rule);
48    }
49
50    public function testRenderWritesTheKeyword(): void
51    {
52        self::assertSame('UPDATE t SET a = DEFAULT', (new Semantics())->inspect('update t set a = default')->toString());
53    }
54}
55