packages/sql-semantics-mysql/tests/Unit/Statement/Alter/DropTableTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Alter;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10use SqlSemantics\Platform\MySql\Model\Statement\Reference\Table\DeclaredTable;
11use SqlSemantics\Platform\MySql\Model\Statement\Reference\Table\MissingTable;
12use SqlSemantics\Platform\MySql\Semantics;
13use SqlSemantics\Platform\MySql\Statement\Alter\DropTable;
14use SqlSemantics\Platform\MySql\Statement\Alter\Problem\RepeatedTable;
15
16#[CoversClass(DropTable::class)]
17#[Medium]
18final class DropTableTest extends TestCase
19{
20    public function testDeriveStatementResolvesEveryTable(): void
21    {
22        $semantics = new Semantics();
23        $table = $semantics->inspect('CREATE TABLE t (a INT)');
24        $drop = $semantics->inspect('DROP TABLE t, u, t', [$table]);
25
26        self::assertInstanceOf(DropTable::class, $drop->statement);
27        self::assertInstanceOf(DeclaredTable::class, $drop->facts->relation($drop->statement->tables[0])->table);
28        self::assertInstanceOf(MissingTable::class, $drop->facts->relation($drop->statement->tables[1])->table);
29        self::assertInstanceOf(RepeatedTable::class, $drop->facts->diagnostics[1]);
30    }
31
32    public function testRenderWritesEveryPart(): void
33    {
34        self::assertSame('DROP TEMPORARY TABLE IF EXISTS t RESTRICT', (new Semantics())->inspect('drop temporary tables if exists t restrict')->toString());
35    }
36
37    public function testDeriveStatementRefusesAViewWithoutIfExists(): void
38    {
39        $semantics = new Semantics();
40        $table = $semantics->inspect('CREATE TABLE t (a INT)');
41        $view = $semantics->inspect('CREATE VIEW v AS SELECT a FROM t', [$table]);
42
43        self::assertSame(['v is a view: DROP TABLE reports it as an unknown table.'], array_map(static fn ($diagnostic): string => $diagnostic->message(), $semantics->inspect('DROP TABLE v', [$table, $view])->facts->diagnostics));
44        self::assertSame([], array_map(static fn ($diagnostic): string => $diagnostic->message(), $semantics->inspect('DROP TABLE IF EXISTS v', [$table, $view])->facts->diagnostics));
45    }
46}
47