packages/sql-semantics-sqlite/tests/Unit/Statement/Schema/Table/ForeignKeyTest.php
1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Schema\Table;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10use SqlSemantics\Platform\Sqlite\Semantics;
11use SqlSemantics\Platform\Sqlite\Statement\Schema\CreateTable;
12use SqlSemantics\Platform\Sqlite\Statement\Schema\Problem\DecoratedColumnName;
13use SqlSemantics\Platform\Sqlite\Statement\Schema\Problem\UnknownColumn;
14use SqlSemantics\Platform\Sqlite\Statement\Schema\Table\ForeignKey;
15
16#[CoversClass(ForeignKey::class)]
17#[Medium]
18final class ForeignKeyTest extends TestCase
19{
20 public function testDeriveConstraintAcceptsChildColumnsOfTheTable(): void
21 {
22 $operation = (new Semantics())->inspect('CREATE TABLE c (a, b, FOREIGN KEY (a, B) REFERENCES parent)', []);
23
24 self::assertSame([], $operation->facts->diagnostics);
25 }
26
27 public function testDeriveConstraintReportsAChildColumnTheTableDoesNotHave(): void
28 {
29 $operation = (new Semantics())->inspect('CREATE TABLE c (a, FOREIGN KEY (rowid) REFERENCES parent)', []);
30
31 self::assertCount(1, $operation->facts->diagnostics);
32 self::assertInstanceOf(UnknownColumn::class, $operation->facts->diagnostics[0]);
33 self::assertSame('rowid', $operation->facts->diagnostics[0]->column->value);
34 }
35
36 public function testDeriveConstraintReportsDecoratedColumnsOnBothSides(): void
37 {
38 $operation = (new Semantics())->inspect('CREATE TABLE c (a, FOREIGN KEY (a DESC) REFERENCES parent (id ASC))', []);
39
40 self::assertCount(2, $operation->facts->diagnostics);
41 self::assertInstanceOf(DecoratedColumnName::class, $operation->facts->diagnostics[0]);
42 self::assertInstanceOf(DecoratedColumnName::class, $operation->facts->diagnostics[1]);
43 }
44
45 public function testRenderWritesTheColumnsTheParentAndTheDeferrability(): void
46 {
47 $operation = (new Semantics())->inspect('create table c (a, b, foreign key (a, b) references parent (x, y) on delete cascade deferrable initially deferred)');
48 $statement = $operation->statement;
49
50 self::assertInstanceOf(CreateTable::class, $statement);
51 $key = $statement->constraints[0]->items[0];
52 self::assertInstanceOf(ForeignKey::class, $key);
53 self::assertCount(2, $key->columns);
54 self::assertTrue($key->deferrability?->deferred());
55 self::assertSame('CREATE TABLE c (a, b, FOREIGN KEY (a, b) REFERENCES parent (x, y) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED)', $operation->toString());
56 }
57}
58