packages/sql-semantics-sqlite/tests/Unit/Statement/Mutation/ConflictTargetTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Mutation;
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\Model\Statement\Reference\Column\ResolvedColumn;
12use SqlSemantics\Platform\Sqlite\Semantics;
13use SqlSemantics\Platform\Sqlite\Statement\Expression\Operator\Binary;
14use SqlSemantics\Platform\Sqlite\Statement\Mutation\ConflictTarget;
15use SqlSemantics\Platform\Sqlite\Statement\Mutation\InsertRows;
16
17#[CoversClass(ConflictTarget::class)]
18#[Medium]
19final class ConflictTargetTest extends TestCase
20{
21    public function testRenderWritesTheTermsAndThePredicate(): void
22    {
23        $query = (new Semantics())->inspect('insert into t values (1) on conflict (id collate nocase asc, a) where id > 0 do nothing');
24
25        self::assertSame('INSERT INTO t VALUES (1) ON CONFLICT (id COLLATE nocase ASC, a) WHERE id > 0 DO NOTHING', $query->toString());
26        self::assertInstanceOf(InsertRows::class, $query->statement);
27        self::assertNotNull($query->statement->upserts[0]->target);
28        self::assertCount(2, $query->statement->upserts[0]->target->terms);
29        self::assertNotNull($query->statement->upserts[0]->target->where);
30    }
31
32    public function testTermsAndPredicateSeeTheTargetTableOnly(): void
33    {
34        $semantics = new Semantics();
35        $t = $semantics->inspect('CREATE TABLE t (id INTEGER PRIMARY KEY, a INTEGER NOT NULL, b TEXT)');
36        $query = $semantics->inspect('INSERT INTO t VALUES (1, 2, 3) ON CONFLICT (id) WHERE excluded.id > 0 DO NOTHING', [$t]);
37
38        self::assertInstanceOf(InsertRows::class, $query->statement);
39        $target = $query->statement->upserts[0]->target;
40        self::assertNotNull($target);
41        $term = $query->facts->scalar($target->terms[0]->expression)->resolution;
42        self::assertInstanceOf(ResolvedColumn::class, $term);
43        self::assertSame($query->statement->into->target, $term->relation);
44        self::assertSame($t->declarations()[0]->columns[0], $term->declaration());
45        self::assertInstanceOf(Binary::class, $target->where);
46        self::assertInstanceOf(MissingColumn::class, $query->facts->scalar($target->where->left)->resolution);
47        self::assertInstanceOf(MissingColumn::class, $query->facts->diagnostics[0]);
48        self::assertSame('excluded', $query->facts->diagnostics[0]->qualifier?->name->value);
49    }
50
51    public function testRejectsAnEmptyTermList(): void
52    {
53        $this->expectExceptionMessage('A conflict target names at least one indexed column.');
54
55        new ConflictTarget([]);
56    }
57}
58