packages/sql-semantics-postgres/tests/Unit/Rules/Table/ForeignKeysTest.php
1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Rules\Table;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10
11#[CoversClass(\SqlSemantics\Platform\PostgreSql\Rules\Table\ForeignKeys::class)]
12#[Medium]
13final class ForeignKeysTest extends TestCase
14{
15 public function testActionsRefusesTwoClausesForOneEvent(): void
16 {
17 $this->expectExceptionMessage('A foreign key has at most one ON UPDATE and one ON DELETE clause.');
18 (new \SqlSemantics\Platform\PostgreSql\Rules\Table\ForeignKeys())->actions([new \SqlSemantics\Platform\PostgreSql\Statement\Constraint\Reference\ReferentialAction(\SqlSemantics\Platform\PostgreSql\Statement\Constraint\Reference\ReferenceEvent::Delete, \SqlSemantics\Platform\PostgreSql\Statement\Constraint\Reference\ReferenceAction::Cascade), new \SqlSemantics\Platform\PostgreSql\Statement\Constraint\Reference\ReferentialAction(\SqlSemantics\Platform\PostgreSql\Statement\Constraint\Reference\ReferenceEvent::Delete, \SqlSemantics\Platform\PostgreSql\Statement\Constraint\Reference\ReferenceAction::Restrict)]);
19 }
20
21 public function testDeriveResolvesTheReferencedTable(): void
22 {
23 $semantics = new \SqlSemantics\Platform\PostgreSql\Semantics();
24 $context = [];
25 array_push($context, ...$semantics->inspect('CREATE TABLE t (a int NOT NULL, b int, c text)')->declarations());
26 $statement = $semantics->inspect('CREATE TABLE n (x int REFERENCES t (zz) MATCH PARTIAL)', $context);
27 self::assertSame([
28 0 => 'column "zz" referenced in foreign key constraint does not exist',
29 1 => 'MATCH PARTIAL not yet implemented',
30 ], array_map(static fn ($problem): string => $problem->message(), $statement->facts->diagnostics));
31 }
32
33 public function testWriteTargetWritesTheReferencedSide(): void
34 {
35 $semantics = new \SqlSemantics\Platform\PostgreSql\Semantics();
36 $statement = $semantics->inspect('CREATE TABLE n (x int REFERENCES t (a) MATCH FULL ON UPDATE SET DEFAULT ON DELETE NO ACTION)', []);
37 self::assertSame('CREATE TABLE n (x INT REFERENCES t (a) MATCH FULL ON UPDATE SET DEFAULT ON DELETE NO ACTION)', $statement->toString());
38 }
39
40 public function testDeriveReportsAReferencedView(): void
41 {
42 $semantics = new \SqlSemantics\Platform\PostgreSql\Semantics();
43 $context = [$semantics->inspect('CREATE VIEW v AS SELECT 1 AS a')];
44 self::assertSame(['referenced relation "v" is not a table'], array_map(static fn ($problem): string => $problem->message(), $semantics->inspect('CREATE TABLE c (a int REFERENCES v (zz))', $context)->facts->diagnostics));
45 }
46}
47