packages/sql-semantics-sqlite/tests/Unit/Statement/Mutation/InsertRowsTest.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\Construction\Derivation;
11use SqlSemantics\Platform\Sqlite\Model\Statement\Identifier\Name;
12use SqlSemantics\Platform\Sqlite\Model\Statement\Identifier\QualifiedName;
13use SqlSemantics\Platform\Sqlite\Model\Statement\Reference\Column\MissingColumn;
14use SqlSemantics\Platform\Sqlite\Model\Statement\Reference\Column\ResolvedColumn;
15use SqlSemantics\Platform\Sqlite\Model\Statement\Shape\Field;
16use SqlSemantics\Platform\Sqlite\Semantics;
17use SqlSemantics\Platform\Sqlite\Statement\Expression\Literal\IntegerLiteral;
18use SqlSemantics\Platform\Sqlite\Statement\Mutation\Assignment;
19use SqlSemantics\Platform\Sqlite\Statement\Mutation\ConflictTarget;
20use SqlSemantics\Platform\Sqlite\Statement\Mutation\InsertInto;
21use SqlSemantics\Platform\Sqlite\Statement\Mutation\InsertRows;
22use SqlSemantics\Platform\Sqlite\Statement\Mutation\MutationTarget;
23use SqlSemantics\Platform\Sqlite\Statement\Mutation\Upsert;
24use SqlSemantics\Platform\Sqlite\Statement\Query\Ordering\SortTerm;
25use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\ArityMismatch;
26use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\ArityRule;
27use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\Misuse;
28use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\MisuseRule;
29use SqlSemantics\Platform\Sqlite\Statement\Query\ValueRow;
30use SqlSemantics\Platform\Sqlite\Statement\Query\ValuesClause;
31
32#[CoversClass(InsertRows::class)]
33#[Medium]
34final class InsertRowsTest extends TestCase
35{
36    public function testDeriveStatementCountsTheValuesAgainstTheColumns(): void
37    {
38        $semantics = new Semantics();
39        $t = $semantics->inspect('CREATE TABLE t (id INTEGER PRIMARY KEY, a INTEGER NOT NULL, b TEXT)');
40        $short = $semantics->inspect('INSERT INTO t VALUES (1)', [$t]);
41        $listed = $semantics->inspect('INSERT INTO t (a, b) VALUES (1, 2)', [$t]);
42        $open = $semantics->inspect('INSERT INTO t VALUES (1)');
43
44        self::assertInstanceOf(ArityMismatch::class, $short->facts->diagnostics[0]);
45        self::assertSame(ArityRule::InsertedValues, $short->facts->diagnostics[0]->rule);
46        self::assertSame(3, $short->facts->diagnostics[0]->expected);
47        self::assertSame(1, $short->facts->diagnostics[0]->actual);
48        self::assertSame('1 values for 3 columns.', $short->facts->diagnostics[0]->message());
49        self::assertSame([], $listed->facts->diagnostics);
50        self::assertSame([], $open->facts->diagnostics);
51        self::assertNull($short->shape());
52    }
53
54    public function testDeriveStatementReportsAColumnTheTableLacks(): void
55    {
56        $semantics = new Semantics();
57        $t = $semantics->inspect('CREATE TABLE t (id INTEGER PRIMARY KEY, a INTEGER NOT NULL, b TEXT)');
58        $query = $semantics->inspect('INSERT INTO t (zz, rowid) VALUES (1, 2)', [$t]);
59
60        self::assertCount(1, $query->facts->diagnostics);
61        self::assertInstanceOf(MissingColumn::class, $query->facts->diagnostics[0]);
62        self::assertSame('zz', $query->facts->diagnostics[0]->name->value);
63    }
64
65    public function testDeriveWithinLetsDoUpdateSeeTheTableAndExcluded(): void
66    {
67        $semantics = new Semantics();
68        $t = $semantics->inspect('CREATE TABLE t (id INTEGER PRIMARY KEY, a INTEGER NOT NULL, b TEXT)');
69        $query = $semantics->inspect('INSERT INTO t VALUES (1, 2, 3) ON CONFLICT (id) DO UPDATE SET a = excluded.a, b = b WHERE a > 1 RETURNING *', [$t]);
70        $missing = $semantics->inspect('INSERT INTO t VALUES (1, 2, 3) ON CONFLICT (id) DO UPDATE SET a = excluded.zz', [$t]);
71
72        self::assertInstanceOf(InsertRows::class, $query->statement);
73        self::assertInstanceOf(Assignment::class, $query->statement->upserts[0]->assignments[0]);
74        self::assertInstanceOf(Assignment::class, $query->statement->upserts[0]->assignments[1]);
75        $excluded = $query->facts->scalar($query->statement->upserts[0]->assignments[0]->value)->resolution;
76        $bare = $query->facts->scalar($query->statement->upserts[0]->assignments[1]->value)->resolution;
77        self::assertInstanceOf(ResolvedColumn::class, $excluded);
78        self::assertInstanceOf(ResolvedColumn::class, $bare);
79        self::assertSame($query->statement->into->target, $excluded->relation);
80        self::assertSame($t->declarations()[0]->columns[1], $excluded->declaration());
81        self::assertSame($t->declarations()[0]->columns[2], $bare->declaration());
82        self::assertSame(['id', 'a', 'b'], array_map(static fn (Field $field): ?string => $field->name?->value, $query->fields()->items ?? []));
83        self::assertSame([], $query->facts->diagnostics);
84        self::assertInstanceOf(MissingColumn::class, $missing->facts->diagnostics[0]);
85        self::assertSame('excluded', $missing->facts->diagnostics[0]->qualifier?->name->value);
86    }
87
88    public function testDeriveWithinAnswersNullWithoutReturning(): void
89    {
90        $semantics = new Semantics();
91        $t = $semantics->inspect('CREATE TABLE t (id INTEGER PRIMARY KEY, a INTEGER NOT NULL, b TEXT)');
92        $statement = $semantics->inspect('INSERT INTO t VALUES (1, 2, 3)', [$t])->statement;
93        $returning = $semantics->inspect('INSERT INTO t VALUES (1, 2, 3) RETURNING b', [$t])->statement;
94        $derivation = new Derivation($semantics->context([$t]));
95
96        self::assertInstanceOf(InsertRows::class, $statement);
97        self::assertInstanceOf(InsertRows::class, $returning);
98        self::assertNull($statement->deriveWithin($derivation, $derivation->environment()));
99        self::assertSame('b', $returning->deriveWithin($derivation, $derivation->environment())?->shape->slots[0]->name?->value);
100        self::assertTrue($derivation->facts()->covers($statement->rows));
101    }
102
103    public function testDeriveStatementReportsRaiseOutsideATrigger(): void
104    {
105        $query = (new Semantics())->inspect('INSERT INTO t VALUES (RAISE(IGNORE))');
106
107        self::assertInstanceOf(Misuse::class, $query->facts->diagnostics[0]);
108        self::assertSame(MisuseRule::RaiseOutsideTrigger, $query->facts->diagnostics[0]->rule);
109    }
110
111    public function testRenderWritesIntoRowsUpsertsAndReturning(): void
112    {
113        $query = (new Semantics())->inspect('insert into t (id, a) values (1, 2), (3, 4) on conflict (id) do update set a = excluded.a on conflict do nothing returning id');
114
115        self::assertSame('INSERT INTO t (id, a) VALUES (1, 2), (3, 4) ON CONFLICT (id) DO UPDATE SET a = excluded.a ON CONFLICT DO NOTHING RETURNING id', $query->toString());
116        self::assertInstanceOf(InsertRows::class, $query->statement);
117        self::assertCount(2, $query->statement->rows->rows);
118        self::assertCount(2, $query->statement->upserts);
119        self::assertCount(1, $query->statement->returning);
120    }
121
122    public function testRejectsANonLastUpsertWithoutAConflictTarget(): void
123    {
124        $into = new InsertInto(new MutationTarget(new QualifiedName(new Name('t'))));
125        $rows = new ValuesClause([new ValueRow([new IntegerLiteral('1')])]);
126        $target = new ConflictTarget([new SortTerm(new IntegerLiteral('1'))]);
127
128        $this->expectExceptionMessage('Only the last ON CONFLICT clause may omit the conflict target.');
129
130        new InsertRows($into, $rows, [new Upsert(), new Upsert($target)]);
131    }
132}
133