packages/sql-semantics-mysql/tests/Unit/Statement/Table/CreateTableLikeTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Table;
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\Semantics;
12use SqlSemantics\Platform\MySql\Statement\Table\CreateTableLike;
13
14#[CoversClass(CreateTableLike::class)]
15#[Medium]
16final class CreateTableLikeTest extends TestCase
17{
18    public function testDeriveStatementCopiesTheSourceDeclaration(): void
19    {
20        $semantics = new Semantics();
21        $source = $semantics->inspect('CREATE TABLE s (a INT NOT NULL, b INT INVISIBLE)');
22        $copy = $semantics->inspect('CREATE TABLE c LIKE s', [$source]);
23        $table = $copy->declarations()[0];
24
25        self::assertInstanceOf(DeclaredTable::class, $copy->facts->relation($copy->statement)->table);
26        self::assertSame(['a', 'b'], [$table->columns[0]->name->value, $table->implicit[0]->column->name->value]);
27        self::assertNotSame($source->declarations()[0]->columns[0], $table->columns[0]);
28    }
29
30    public function testDeriveStatementLeavesAnUndeclaredSourceIncomplete(): void
31    {
32        $create = (new Semantics())->inspect('CREATE TABLE c LIKE s');
33
34        self::assertFalse($create->declarations()[0]->complete);
35    }
36
37    public function testRenderWritesLikeWithoutParentheses(): void
38    {
39        self::assertSame('CREATE TABLE IF NOT EXISTS c LIKE db.s', (new Semantics())->inspect('CREATE TABLE IF NOT EXISTS c (LIKE db.s)')->toString());
40    }
41
42    public function testDeriveStatementRefusesAViewSource(): void
43    {
44        $semantics = new Semantics();
45        $table = $semantics->inspect('CREATE TABLE t (a INT)');
46        $view = $semantics->inspect('CREATE VIEW v AS SELECT a FROM t', [$table]);
47
48        self::assertSame(['v is not BASE TABLE.'], array_map(static fn ($diagnostic): string => $diagnostic->message(), $semantics->inspect('CREATE TABLE c LIKE v', [$table, $view])->facts->diagnostics));
49    }
50}
51