packages/sql-semantics-postgres/tests/Unit/Statement/Constraint/Table/ForeignKeyTest.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\ForeignKey::class)]
12#[Medium]
13final class ForeignKeyTest extends TestCase
14{
15 public function testKindIsForeignKey(): void
16 {
17 $semantics = new \SqlSemantics\Platform\PostgreSql\Semantics();
18 $statement = $semantics->inspect('CREATE TABLE t (a int, FOREIGN KEY (a) REFERENCES u)', []);
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\ForeignKey::class, $n3);
25 self::assertSame(\SqlSemantics\Platform\PostgreSql\Statement\Constraint\ConstraintKind::ForeignKey, $n3->kind());
26 }
27
28 public function testDeriveClauseChecksBothSides(): void
29 {
30 $semantics = new \SqlSemantics\Platform\PostgreSql\Semantics();
31 $context = [];
32 array_push($context, ...$semantics->inspect('CREATE TABLE p (id int PRIMARY KEY)')->declarations());
33 $statement = $semantics->inspect('CREATE TABLE t (a int, FOREIGN KEY (zz) REFERENCES p (nope) NO INHERIT)', $context);
34 self::assertSame([
35 0 => 'column "zz" named in key does not exist',
36 1 => 'column "nope" referenced in foreign key constraint does not exist',
37 2 => 'FOREIGN KEY constraints cannot be marked NO INHERIT',
38 ], array_map(static fn ($problem): string => $problem->message(), $statement->facts->diagnostics));
39 }
40
41 public function testRenderWritesTheClauseAsWritten(): void
42 {
43 $semantics = new \SqlSemantics\Platform\PostgreSql\Semantics();
44 $statement = $semantics->inspect('CREATE TABLE t (a int, CONSTRAINT f FOREIGN KEY (a) REFERENCES p (id) MATCH SIMPLE ON UPDATE CASCADE ON DELETE SET NULL NOT VALID)', []);
45 self::assertSame('CREATE TABLE t (a INT, CONSTRAINT f FOREIGN KEY (a) REFERENCES p (id) MATCH SIMPLE ON UPDATE CASCADE ON DELETE SET NULL NOT VALID)', $statement->toString());
46 }
47}
48