packages/sql-semantics-postgres/tests/Unit/Statement/Table/Alter/AlterTableTest.php
1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Table\Alter;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10
11#[CoversClass(\SqlSemantics\Platform\PostgreSql\Statement\Table\Alter\AlterTable::class)]
12#[Medium]
13final class AlterTableTest extends TestCase
14{
15 public function testDeriveStatementDerivesTheActionsAgainstTheTable(): void
16 {
17 $semantics = new \SqlSemantics\Platform\PostgreSql\Semantics();
18 $context = [];
19 array_push($context, ...$semantics->inspect('CREATE TABLE t (a int NOT NULL, b int, c text)')->declarations());
20 $statement = $semantics->inspect('ALTER TABLE t ADD d int CHECK (d > a), ALTER zz DROP NOT NULL', $context);
21 self::assertSame([
22 0 => 'column "zz" does not exist',
23 ], array_map(static fn ($problem): string => $problem->message(), $statement->facts->diagnostics));
24 }
25
26 public function testDeriveRelationResolvesTheTable(): void
27 {
28 $semantics = new \SqlSemantics\Platform\PostgreSql\Semantics();
29 $context = [];
30 array_push($context, ...$semantics->inspect('CREATE TABLE t (a int NOT NULL, b int, c text)')->declarations());
31 $statement = $semantics->inspect('ALTER TABLE t DROP b', $context);
32 $n1 = $statement->statement;
33 self::assertInstanceOf(\SqlSemantics\Platform\PostgreSql\Statement\Table\Alter\AlterTable::class, $n1);
34 $n2 = $statement->facts->relation($n1)->table;
35 self::assertInstanceOf(\SqlSemantics\Platform\PostgreSql\Model\Statement\Reference\Table\DeclaredTable::class, $n2);
36 self::assertSame(true, $n2->table === $context[0]);
37 }
38
39 public function testRenderWritesTheClauseAsWritten(): void
40 {
41 $semantics = new \SqlSemantics\Platform\PostgreSql\Semantics();
42 $statement = $semantics->inspect('ALTER TABLE IF EXISTS ONLY s.t ADD COLUMN d int, DROP COLUMN e', []);
43 self::assertSame('ALTER TABLE IF EXISTS ONLY s.t ADD d INT, DROP e', $statement->toString());
44 }
45
46 public function testRefusesOnlyForAnIndex(): void
47 {
48 $this->expectExceptionMessage('ONLY is written for tables and foreign tables.');
49 new \SqlSemantics\Platform\PostgreSql\Statement\Table\Alter\AlterTable(\SqlSemantics\Platform\PostgreSql\Statement\Table\Alter\AlterTarget::Index, new \SqlSemantics\Platform\PostgreSql\Statement\Name\RelationReference(new \SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\QualifiedName(new \SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\Name('i')), true), [new \SqlSemantics\Platform\PostgreSql\Statement\Table\Alter\TableAction(\SqlSemantics\Platform\PostgreSql\Statement\Table\Alter\TableActionKind::SetLogged)]);
50 }
51}
52