packages/sql-semantics-postgres/tests/Unit/Statement/Object/SetSchemaTest.php
1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Object;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10use SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\Name;
11use SqlSemantics\Platform\PostgreSql\Semantics;
12use SqlSemantics\Platform\PostgreSql\Statement\Name\ObjectKind;
13use SqlSemantics\Platform\PostgreSql\Statement\Object\Reference\UnqualifiedName;
14use SqlSemantics\Platform\PostgreSql\Statement\Object\SetSchema;
15
16#[CoversClass(SetSchema::class)]
17#[Medium]
18final class SetSchemaTest extends TestCase
19{
20 public function testDeriveStatementResolvesAMovedTable(): void
21 {
22 $operation = (new Semantics())->inspect('ALTER TABLE IF EXISTS t SET SCHEMA s', []);
23 self::assertSame([], $operation->facts->diagnostics);
24 $statement = $operation->statement;
25 self::assertInstanceOf(SetSchema::class, $statement);
26 self::assertNull($operation->facts->relation($statement->object)->table);
27 }
28
29 public function testRenderWritesTheSchema(): void
30 {
31 $operation = (new Semantics())->inspect('ALTER OPERATOR CLASS c USING btree SET SCHEMA "S"');
32 self::assertSame('ALTER OPERATOR CLASS c USING btree SET SCHEMA "S"', $operation->toString());
33 }
34
35 public function testRejectsAWrongForm(): void
36 {
37 $this->expectExceptionMessage('SET SCHEMA names the object as the grammar names objects of its kind.');
38 new SetSchema(ObjectKind::Schema, new UnqualifiedName(new Name('s')), new Name('t'));
39 }
40
41 public function testRejectsIfExistsOfAnotherKind(): void
42 {
43 $this->expectExceptionMessage('SET SCHEMA accepts IF EXISTS for relations only.');
44 new SetSchema(ObjectKind::Extension, new UnqualifiedName(new Name('e')), new Name('t'), true);
45 }
46
47 public function testDeriveStatementReportsAnotherKind(): void
48 {
49 $semantics = new Semantics();
50 $context = [$semantics->inspect('CREATE TABLE t (a int)')];
51 self::assertSame(['"t" is not a foreign table'], array_map(static fn ($problem): string => $problem->message(), $semantics->inspect('ALTER FOREIGN TABLE t SET SCHEMA x', $context)->facts->diagnostics));
52 self::assertSame([], array_map(static fn ($problem): string => $problem->message(), $semantics->inspect('ALTER TABLE t SET SCHEMA x', $context)->facts->diagnostics));
53 }
54}
55