packages/sql-semantics-sqlite/tests/Unit/Rules/Mutation/InsertFactsTest.php
1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Rules\Mutation;
6
7use PDO;
8use PDOException;
9use PHPUnit\Framework\Attributes\CoversClass;
10use PHPUnit\Framework\Attributes\Medium;
11use PHPUnit\Framework\Attributes\TestWith;
12use PHPUnit\Framework\TestCase;
13use SqlSemantics\Platform\Sqlite\Model\Construction\Derivation;
14use SqlSemantics\Platform\Sqlite\Model\Statement\Identifier\Name;
15use SqlSemantics\Platform\Sqlite\Model\Statement\Identifier\QualifiedName;
16use SqlSemantics\Platform\Sqlite\Model\Statement\Reference\Column\MissingColumn;
17use SqlSemantics\Platform\Sqlite\Model\Statement\Reference\Column\ResolvedColumn;
18use SqlSemantics\Platform\Sqlite\Model\Statement\Shape\OutputSlot;
19use SqlSemantics\Platform\Sqlite\Rules\Mutation\InsertFacts;
20use SqlSemantics\Platform\Sqlite\Semantics;
21use SqlSemantics\Platform\Sqlite\Statement\Expression\ColumnUse;
22use SqlSemantics\Platform\Sqlite\Statement\Mutation\Assignment;
23use SqlSemantics\Platform\Sqlite\Statement\Mutation\ConflictTarget;
24use SqlSemantics\Platform\Sqlite\Statement\Mutation\InsertInto;
25use SqlSemantics\Platform\Sqlite\Statement\Mutation\InsertRows;
26use SqlSemantics\Platform\Sqlite\Statement\Mutation\InsertSelect;
27use SqlSemantics\Platform\Sqlite\Statement\Mutation\MutationTarget;
28use SqlSemantics\Platform\Sqlite\Statement\Mutation\Upsert;
29use SqlSemantics\Platform\Sqlite\Statement\Query\Ordering\SortTerm;
30use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\ArityMismatch;
31use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\ArityRule;
32use SqlSemantics\Platform\Sqlite\Statement\Query\ResultColumn;
33use SqlSemantics\Platform\Sqlite\Statement\Query\Star;
34
35#[CoversClass(InsertFacts::class)]
36#[Medium]
37final class InsertFactsTest extends TestCase
38{
39 public function testDeriveCountsTheSourceColumnsAgainstTheTarget(): void
40 {
41 $semantics = new Semantics();
42 $t = $semantics->inspect('CREATE TABLE t (id INTEGER PRIMARY KEY, a INTEGER NOT NULL, b TEXT)');
43 $rows = $semantics->inspect('INSERT INTO t VALUES (1, 2)', [$t])->statement;
44 $listed = $semantics->inspect('INSERT INTO t (a) VALUES (1, 2)', [$t])->statement;
45 $derivation = new Derivation($semantics->context([$t]));
46 $facts = new InsertFacts();
47
48 self::assertInstanceOf(InsertRows::class, $rows);
49 self::assertInstanceOf(InsertRows::class, $listed);
50 self::assertNull($facts->derive($rows->into, $rows->rows, [], [], $derivation, $derivation->environment()));
51 self::assertNull($facts->derive($listed->into, $listed->rows, [], [], $derivation, $derivation->environment()));
52 $diagnostics = $derivation->facts()->diagnostics;
53 self::assertCount(2, $diagnostics);
54 self::assertInstanceOf(ArityMismatch::class, $diagnostics[0]);
55 self::assertSame(ArityRule::InsertedValues, $diagnostics[0]->rule);
56 self::assertSame([3, 2], [$diagnostics[0]->expected, $diagnostics[0]->actual]);
57 self::assertInstanceOf(ArityMismatch::class, $diagnostics[1]);
58 self::assertSame([1, 2], [$diagnostics[1]->expected, $diagnostics[1]->actual]);
59 self::assertTrue($derivation->facts()->covers($rows->rows));
60 }
61
62 #[TestWith(['INSERT INTO t VALUES (1, 2)', 2, 'table t has 1 columns but 2 values were supplied'])]
63 #[TestWith(['INSERT INTO t SELECT * FROM t', 3, 'table t has 1 columns but 3 values were supplied'])]
64 public function testDeriveCountsTheColumnsThatAreNotGeneratedWhenNoListIsWritten(string $sql, int $actual, string $message): void
65 {
66 $semantics = new Semantics();
67 $t = $semantics->inspect('CREATE TABLE t (a, b AS (a + 1), c GENERATED ALWAYS AS (a * 2) STORED)');
68 $operation = $semantics->inspect($sql, [$t]);
69 $database = new PDO('sqlite::memory:');
70 $database->exec('CREATE TABLE t (a, b AS (a + 1), c GENERATED ALWAYS AS (a * 2) STORED)');
71
72 self::assertSame([], $semantics->inspect('INSERT INTO t VALUES (1)', [$t])->facts->diagnostics);
73 self::assertCount(1, $operation->facts->diagnostics);
74 self::assertInstanceOf(ArityMismatch::class, $operation->facts->diagnostics[0]);
75 self::assertSame([ArityRule::InsertedValues, 1, $actual], [$operation->facts->diagnostics[0]->rule, $operation->facts->diagnostics[0]->expected, $operation->facts->diagnostics[0]->actual]);
76 self::assertNotFalse($database->exec('INSERT INTO t VALUES (1)'));
77 $this->expectException(PDOException::class);
78 $this->expectExceptionMessage($message);
79 $database->exec($sql);
80 }
81
82 public function testDeriveSkipsTheCountWhenEitherSideIsOpen(): void
83 {
84 $semantics = new Semantics();
85 $t = $semantics->inspect('CREATE TABLE t (id INTEGER PRIMARY KEY, a INTEGER NOT NULL, b TEXT)');
86 $open = $semantics->inspect('INSERT INTO t SELECT * FROM u', [$t], );
87 $undeclared = $semantics->inspect('INSERT INTO u VALUES (1)', [$t], );
88 $derivation = new Derivation($semantics->context([$t], false));
89 $facts = new InsertFacts();
90
91 self::assertInstanceOf(InsertSelect::class, $open->statement);
92 self::assertInstanceOf(InsertRows::class, $undeclared->statement);
93 $facts->derive($open->statement->into, $open->statement->query, [], [], $derivation, $derivation->environment());
94 $facts->derive($undeclared->statement->into, $undeclared->statement->rows, [], [], $derivation, $derivation->environment());
95 self::assertSame([], $derivation->facts()->diagnostics);
96 }
97
98 public function testDeriveLetsUpsertsSeeTheTargetAndExcludedInTheRightPlaces(): void
99 {
100 $semantics = new Semantics();
101 $t = $semantics->inspect('CREATE TABLE t (id INTEGER PRIMARY KEY, a INTEGER NOT NULL, b TEXT)');
102 $derivation = new Derivation($semantics->context([$t]));
103 $into = new InsertInto(new MutationTarget(new QualifiedName(new Name('t'))), [new Name('a')]);
104 $term = new ColumnUse(new Name('id'));
105 $wrong = new ColumnUse(new Name('id'), new QualifiedName(new Name('excluded')));
106 $value = new ColumnUse(new Name('a'), new QualifiedName(new Name('excluded')));
107 $predicate = new ColumnUse(new Name('b'));
108 $upsert = new Upsert(new ConflictTarget([new SortTerm($term)], $wrong), [new Assignment(new Name('a'), $value), new Assignment(new Name('zz'), new ColumnUse(new Name('b')))], $predicate);
109 (new InsertFacts())->derive($into, null, [$upsert], [], $derivation, $derivation->environment());
110 $facts = $derivation->facts();
111 $resolved = $facts->scalar($value)->resolution;
112
113 self::assertInstanceOf(ResolvedColumn::class, $facts->scalar($term)->resolution);
114 self::assertInstanceOf(MissingColumn::class, $facts->scalar($wrong)->resolution);
115 self::assertInstanceOf(ResolvedColumn::class, $resolved);
116 self::assertSame($into->target, $resolved->relation);
117 self::assertSame($t->declarations()[0]->columns[1], $resolved->declaration());
118 self::assertInstanceOf(ResolvedColumn::class, $facts->scalar($predicate)->resolution);
119 self::assertSame(['excluded.id', 'zz'], array_map(static fn (object $diagnostic): string => $diagnostic instanceof MissingColumn ? ($diagnostic->qualifier === null ? '' : $diagnostic->qualifier->name->value . '.') . $diagnostic->name->value : '', $facts->diagnostics));
120 }
121
122 public function testDeriveBindsTheWithClauseAndReturnsTheTargetRow(): void
123 {
124 $semantics = new Semantics();
125 $t = $semantics->inspect('CREATE TABLE t (id INTEGER PRIMARY KEY, a INTEGER NOT NULL, b TEXT)');
126 $statement = $semantics->inspect('WITH w AS (SELECT 1 AS q) INSERT INTO t (a) SELECT q FROM w', [$t])->statement;
127 $derivation = new Derivation($semantics->context([$t]));
128 $returning = new ResultColumn(new ColumnUse(new Name('b')));
129
130 self::assertInstanceOf(InsertSelect::class, $statement);
131 $fact = (new InsertFacts())->derive($statement->into, $statement->query, [], [new Star(), $returning], $derivation, $derivation->environment());
132 self::assertNotNull($fact);
133 self::assertSame(['id', 'a', 'b', 'b'], array_map(static fn (OutputSlot $slot): ?string => $slot->name?->value, $fact->shape->slots));
134 self::assertSame($t->declarations()[0]->columns[2], $fact->shape->slots[3]->declaration());
135 self::assertSame([], $derivation->facts()->diagnostics);
136 self::assertNull($derivation->facts()->output);
137 }
138}
139