packages/sql-semantics-sqlite/tests/Unit/Rules/Mutation/TriggerFactsTest.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\TestCase;
12use SqlSemantics\Platform\Sqlite\Model\Construction\Derivation;
13use SqlSemantics\Platform\Sqlite\Model\Statement\Fact\Diagnostic;
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\Reference\Table\DeclaredTable;
19use SqlSemantics\Platform\Sqlite\Rules\Mutation\TriggerFacts;
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\Delete;
24use SqlSemantics\Platform\Sqlite\Statement\Mutation\MutationTarget;
25use SqlSemantics\Platform\Sqlite\Statement\Mutation\Update;
26use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\Misuse;
27use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\MisuseRule;
28use SqlSemantics\Platform\Sqlite\Statement\Query\ResultColumn;
29use SqlSemantics\Platform\Sqlite\Statement\Query\Select;
30use SqlSemantics\Platform\Sqlite\Statement\Relation\IndexChoice;
31use SqlSemantics\Platform\Sqlite\Statement\Trigger\CreateTrigger;
32use SqlSemantics\Platform\Sqlite\Statement\Trigger\TriggerEvent;
33use SqlSemantics\Platform\Sqlite\Statement\Trigger\TriggerTable;
34
35#[CoversClass(TriggerFacts::class)]
36#[Medium]
37final class TriggerFactsTest extends TestCase
38{
39    public function testDeriveMakesTheRowsOfTheEventVisibleByQualifierOnly(): void
40    {
41        $semantics = new Semantics();
42        $t = $semantics->inspect('CREATE TABLE t (id INTEGER PRIMARY KEY, a INTEGER NOT NULL, b TEXT)');
43        $derivation = new Derivation($semantics->context([$t]));
44        $new = new ColumnUse(new Name('a'), new QualifiedName(new Name('new')));
45        $old = new ColumnUse(new Name('rowid'), new QualifiedName(new Name('old')));
46        $bare = new ColumnUse(new Name('a'));
47        $table = new TriggerTable(new QualifiedName(new Name('t')));
48        $trigger = new CreateTrigger(new QualifiedName(new Name('tr')), TriggerEvent::Update, $table, [new Select([new ResultColumn($new), new ResultColumn($old), new ResultColumn($bare)])]);
49        (new TriggerFacts())->derive($trigger, $derivation);
50        $facts = $derivation->facts();
51        $resolved = $facts->scalar($new)->resolution;
52        $implicit = $facts->scalar($old)->resolution;
53
54        self::assertInstanceOf(DeclaredTable::class, $facts->relation($table)->table);
55        self::assertInstanceOf(ResolvedColumn::class, $resolved);
56        self::assertSame($table, $resolved->relation);
57        self::assertSame(1, $resolved->depth);
58        self::assertSame($t->declarations()[0]->columns[1], $resolved->declaration());
59        self::assertInstanceOf(ResolvedColumn::class, $implicit);
60        self::assertSame($t->declarations()[0]->columns[0], $implicit->declaration());
61        self::assertInstanceOf(MissingColumn::class, $facts->scalar($bare)->resolution);
62        self::assertNull($facts->output);
63        self::assertSame([], $facts->declarations);
64    }
65
66    public function testDeriveHidesTheRowThatTheEventDoesNotProvide(): void
67    {
68        $semantics = new Semantics();
69        $t = $semantics->inspect('CREATE TABLE t (id INTEGER PRIMARY KEY, a INTEGER NOT NULL, b TEXT)');
70        $derivation = new Derivation($semantics->context([$t]));
71        $new = new ColumnUse(new Name('a'), new QualifiedName(new Name('new')));
72        $old = new ColumnUse(new Name('a'), new QualifiedName(new Name('old')));
73        $table = new TriggerTable(new QualifiedName(new Name('t')));
74        $delete = new CreateTrigger(new QualifiedName(new Name('tr')), TriggerEvent::Delete, $table, [new Select([new ResultColumn($new)])], null, [], $old);
75        (new TriggerFacts())->derive($delete, $derivation);
76        $facts = $derivation->facts();
77
78        self::assertInstanceOf(ResolvedColumn::class, $facts->scalar($old)->resolution);
79        self::assertInstanceOf(MissingColumn::class, $facts->scalar($new)->resolution);
80        self::assertSame('new', $facts->scalar($new)->resolution->qualifier?->name->value);
81        self::assertCount(1, $facts->diagnostics);
82    }
83
84    public function testDeriveReportsTriggerOnlyMisusesAndTheColumnsOfUpdateOf(): void
85    {
86        $semantics = new Semantics();
87        $t = $semantics->inspect('CREATE TABLE t (id INTEGER PRIMARY KEY, a INTEGER NOT NULL, b TEXT)');
88        $u = $semantics->inspect('CREATE TABLE u (a INTEGER NOT NULL, c TEXT)');
89        $derivation = new Derivation($semantics->context([$t, $u]));
90        $qualified = new Update(new MutationTarget(new QualifiedName(new Name('u'), new Name('main'))), [new Assignment(new Name('a'), new ColumnUse(new Name('a'), new QualifiedName(new Name('new'))))]);
91        $indexed = new Delete(new MutationTarget(new QualifiedName(new Name('u')), null, new IndexChoice()));
92        $trigger = new CreateTrigger(new QualifiedName(new Name('tr')), TriggerEvent::Update, new TriggerTable(new QualifiedName(new Name('t'))), [$qualified, $indexed], null, [new Name('a'), new Name('zz')]);
93        (new TriggerFacts())->derive($trigger, $derivation);
94        $facts = $derivation->facts();
95        $rules = array_map(static fn (object $diagnostic): string => $diagnostic instanceof Misuse ? $diagnostic->rule->name : $diagnostic::class, $facts->diagnostics);
96
97        self::assertSame([MissingColumn::class, MisuseRule::QualifiedTriggerTarget->name, MisuseRule::IndexedTriggerTarget->name], $rules);
98        self::assertInstanceOf(ResolvedColumn::class, $facts->scalar($qualified->assignments[0]->value)->resolution);
99        self::assertTrue($facts->covers($qualified->target));
100        self::assertTrue($facts->covers($indexed->target));
101    }
102
103    public function testDeriveReportsAParameterAnywhereInTheProgram(): void
104    {
105        $semantics = new Semantics();
106        $t = $semantics->inspect('CREATE TABLE t (id INTEGER PRIMARY KEY, a INTEGER NOT NULL, b TEXT)');
107        $statement = $semantics->inspect('CREATE TRIGGER tr INSERT ON t BEGIN SELECT 1; UPDATE t SET a = :x; END', [$t])->statement;
108        $derivation = new Derivation($semantics->context([$t]));
109
110        self::assertInstanceOf(CreateTrigger::class, $statement);
111        (new TriggerFacts())->derive($statement, $derivation);
112        $facts = $derivation->facts();
113        self::assertCount(1, $facts->diagnostics);
114        self::assertInstanceOf(Misuse::class, $facts->diagnostics[0]);
115        self::assertSame(MisuseRule::ParameterInTrigger, $facts->diagnostics[0]->rule);
116        self::assertInstanceOf(Select::class, $statement->steps[0]);
117        self::assertTrue($facts->covers($statement->steps[0]));
118    }
119
120    public function testDeriveReportsWritesOfGeneratedColumnsInTheProgramThatFailWhenItRuns(): void
121    {
122        $semantics = new Semantics();
123        $schema = 'CREATE TABLE t (a, b AS (a + 1)); CREATE TABLE s (x)';
124        $trigger = 'CREATE TRIGGER tr AFTER INSERT ON s BEGIN UPDATE t SET b = new.x; INSERT INTO t (b) VALUES (new.x); INSERT INTO t VALUES (new.x); END';
125        $operation = $semantics->inspect($trigger, [$semantics->inspect('CREATE TABLE t (a, b AS (a + 1))'), $semantics->inspect('CREATE TABLE s (x)')]);
126        $database = new PDO('sqlite::memory:');
127        $database->exec($schema);
128
129        self::assertSame(['cannot UPDATE generated column "b"', 'cannot INSERT into generated column "b"'], array_map(static fn (Diagnostic $diagnostic): string => $diagnostic->message(), $operation->facts->diagnostics));
130        self::assertNotFalse($database->exec($trigger));
131        $this->expectException(PDOException::class);
132        $this->expectExceptionMessage('cannot UPDATE generated column "b"');
133        $database->exec('INSERT INTO s VALUES (1)');
134    }
135}
136