packages/sql-semantics-mysql/tests/Unit/Statement/Alter/AlterTableTest.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\Fact\Diagnostic;
11use SqlSemantics\Platform\MySql\Model\Statement\Reference\Table\DeclaredTable;
12use SqlSemantics\Platform\MySql\Model\Statement\Shape\OutputSlot;
13use SqlSemantics\Platform\MySql\Semantics;
14use SqlSemantics\Platform\MySql\Statement\Alter\AlterTable;
15
16#[CoversClass(AlterTable::class)]
17#[Medium]
18final class AlterTableTest extends TestCase
19{
20 public function testDeriveStatementReportsTheColumnProblems(): void
21 {
22 $semantics = new Semantics();
23 $table = $semantics->inspect('CREATE TABLE t (a INT, b INT)');
24 $alter = $semantics->inspect('ALTER TABLE t DROP c, RENAME COLUMN a TO b', [$table]);
25
26 self::assertSame(['Column c does not exist in the table.', 'Column b would be defined more than once.'], array_map(static fn (Diagnostic $diagnostic): string => $diagnostic->message(), $alter->facts->diagnostics));
27 }
28
29 public function testDeriveRelationAnswersTheColumnsAfterTheChange(): void
30 {
31 $semantics = new Semantics();
32 $table = $semantics->inspect('CREATE TABLE t (a INT, b INT)');
33 $alter = $semantics->inspect('ALTER TABLE t DROP a, ADD c BIGINT FIRST, RENAME COLUMN b TO d', [$table]);
34 $fact = $alter->facts->relation($alter->statement);
35
36 self::assertSame(['c', 'd'], array_map(static fn (OutputSlot $slot): ?string => $slot->name?->value, $fact->shape->slots));
37 self::assertInstanceOf(DeclaredTable::class, $fact->table);
38 self::assertSame($table->declarations()[0]->columns[1], $fact->shape->slots[1]->declaration());
39 }
40
41 public function testRenderWritesTheActionsInOrder(): void
42 {
43 self::assertSame('ALTER IGNORE TABLE db.t ADD COLUMN a INT, LOCK = DEFAULT PARTITION BY KEY (a)', (new Semantics('mysql-5.6.51'))->inspect('alter ignore table db.t add a int, lock default partition by key (a)')->toString());
44 self::assertSame('ALTER TABLE t ALGORITHM = COPY, COALESCE PARTITION 2', (new Semantics())->inspect('ALTER TABLE t ALGORITHM COPY, COALESCE PARTITION 2')->toString());
45 }
46
47 public function testDeriveStatementRefusesAView(): void
48 {
49 $semantics = new Semantics();
50 $table = $semantics->inspect('CREATE TABLE t (a INT)');
51 $view = $semantics->inspect('CREATE VIEW v AS SELECT a FROM t', [$table]);
52
53 self::assertSame(['v is not BASE TABLE.'], array_map(static fn ($diagnostic): string => $diagnostic->message(), $semantics->inspect('ALTER TABLE v ADD COLUMN b INT', [$table, $view])->facts->diagnostics));
54 }
55}
56