packages/sql-semantics-sqlite/tests/Unit/Statement/Schema/Table/TableUniqueTest.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\Model\Statement\Reference\Column\MissingColumn;
11use SqlSemantics\Platform\Sqlite\Semantics;
12use SqlSemantics\Platform\Sqlite\Statement\Mutation\ConflictResolution;
13use SqlSemantics\Platform\Sqlite\Statement\Schema\CreateTable;
14use SqlSemantics\Platform\Sqlite\Statement\Schema\Problem\PrimaryKeyProblem;
15use SqlSemantics\Platform\Sqlite\Statement\Schema\Table\TableUnique;
16
17#[CoversClass(TableUnique::class)]
18#[Medium]
19final class TableUniqueTest extends TestCase
20{
21    public function testDeriveConstraintResolvesTheKeyColumns(): void
22    {
23        $operation = (new Semantics())->inspect('CREATE TABLE t (a, b, UNIQUE (a, b COLLATE nocase))', []);
24        $statement = $operation->statement;
25
26        self::assertInstanceOf(CreateTable::class, $statement);
27        $unique = $statement->constraints[0]->items[0];
28        self::assertInstanceOf(TableUnique::class, $unique);
29        self::assertTrue($operation->facts->covers($unique->terms[1]->expression));
30        self::assertSame([], $operation->facts->diagnostics);
31    }
32
33    public function testDeriveConstraintReportsAMissingColumnAndAnExpressionTerm(): void
34    {
35        $operation = (new Semantics())->inspect('CREATE TABLE t (a, UNIQUE (zz, a + 1))', []);
36
37        self::assertCount(2, $operation->facts->diagnostics);
38        self::assertInstanceOf(MissingColumn::class, $operation->facts->diagnostics[0]);
39        self::assertInstanceOf(PrimaryKeyProblem::class, $operation->facts->diagnostics[1]);
40    }
41
42    public function testRenderKeepsTheTermsAndTheConflictResolution(): void
43    {
44        $operation = (new Semantics())->inspect('create table t (a, b, unique (a asc, b) on conflict ignore)');
45        $statement = $operation->statement;
46
47        self::assertInstanceOf(CreateTable::class, $statement);
48        $unique = $statement->constraints[0]->items[0];
49        self::assertInstanceOf(TableUnique::class, $unique);
50        self::assertSame(ConflictResolution::Ignore, $unique->conflict);
51        self::assertSame('CREATE TABLE t (a, b, UNIQUE (a ASC, b) ON CONFLICT IGNORE)', $operation->toString());
52    }
53
54    public function testRefusesAStringLiteralTermThatNamesAColumn(): void
55    {
56        $this->expectExceptionMessage('A string literal written as a key term names a column: write it as a LiteralColumn.');
57
58        new TableUnique([new \SqlSemantics\Platform\Sqlite\Statement\Query\Ordering\SortTerm(new \SqlSemantics\Platform\Sqlite\Statement\Expression\Grouped(new \SqlSemantics\Platform\Sqlite\Statement\Expression\Literal\TextLiteral('a')))]);
59    }
60}
61