packages/sql-semantics-postgres/tests/Unit/Statement/Constraint/Table/TableUniqueTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Constraint\Table;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10
11#[CoversClass(\SqlSemantics\Platform\PostgreSql\Statement\Constraint\Table\TableUnique::class)]
12#[Medium]
13final class TableUniqueTest extends TestCase
14{
15    public function testKindIsUnique(): void
16    {
17        $semantics = new \SqlSemantics\Platform\PostgreSql\Semantics();
18        $statement = $semantics->inspect('CREATE TABLE t (a int, UNIQUE (a))', []);
19        $n1 = $statement->statement;
20        self::assertInstanceOf(\SqlSemantics\Platform\PostgreSql\Statement\Table\CreateTable::class, $n1);
21        $n2 = $n1->definition;
22        self::assertInstanceOf(\SqlSemantics\Platform\PostgreSql\Statement\Table\Element\ListedColumns::class, $n2);
23        $n3 = $n2->elements[1];
24        self::assertInstanceOf(\SqlSemantics\Platform\PostgreSql\Statement\Constraint\Table\TableUnique::class, $n3);
25        self::assertSame(\SqlSemantics\Platform\PostgreSql\Statement\Constraint\ConstraintKind::Unique, $n3->kind());
26    }
27
28    public function testDeriveClauseReportsAMissingKeyColumnAndAnAttribute(): void
29    {
30        $semantics = new \SqlSemantics\Platform\PostgreSql\Semantics();
31        $statement = $semantics->inspect('CREATE TABLE t (a int, UNIQUE (zz) NO INHERIT)', []);
32        self::assertSame([
33          0 => 'column "zz" named in key does not exist',
34          1 => 'UNIQUE constraints cannot be marked NO INHERIT',
35        ], array_map(static fn ($problem): string => $problem->message(), $statement->facts->diagnostics));
36    }
37
38    public function testRenderWritesTheClauseAsWritten(): void
39    {
40        $semantics = new \SqlSemantics\Platform\PostgreSql\Semantics();
41        $statement = $semantics->inspect('CREATE TABLE t (a int, b int, UNIQUE NULLS NOT DISTINCT (a) INCLUDE (b) WITH (fillfactor = 70) USING INDEX TABLESPACE s DEFERRABLE)', []);
42        self::assertSame('CREATE TABLE t (a INT, b INT, UNIQUE NULLS NOT DISTINCT (a) INCLUDE (b) WITH (fillfactor = 70) USING INDEX TABLESPACE s DEFERRABLE)', $statement->toString());
43    }
44}
45