packages/sql-semantics-postgres/tests/Unit/Rules/Table/Command/RewriteRulesTest.php
1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Rules\Table\Command;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10
11#[CoversClass(\SqlSemantics\Platform\PostgreSql\Rules\Table\Command\RewriteRules::class)]
12#[Medium]
13final class RewriteRulesTest extends TestCase
14{
15 public function testDeriveReachesOldAndNewWithAQualifierInTheActions(): void
16 {
17 $semantics = new \SqlSemantics\Platform\PostgreSql\Semantics();
18 $context = [];
19 array_push($context, ...$semantics->inspect('CREATE TABLE t (a int NOT NULL, b int, c text)')->declarations());
20 $statement = $semantics->inspect('CREATE RULE r AS ON INSERT TO t DO ALSO SELECT new.a, b', $context);
21 self::assertSame([
22 0 => 'Column b does not exist.',
23 ], array_map(static fn ($problem): string => $problem->message(), $statement->facts->diagnostics));
24 }
25
26 public function testWriteWritesTheRule(): void
27 {
28 $semantics = new \SqlSemantics\Platform\PostgreSql\Semantics();
29 $statement = $semantics->inspect('CREATE RULE r AS ON SELECT TO t DO INSTEAD SELECT 1', []);
30 self::assertSame('CREATE RULE r AS ON SELECT TO t DO INSTEAD SELECT 1', $statement->toString());
31 }
32
33 public function testDeriveReportsARelationThatCannotHaveRules(): void
34 {
35 $semantics = new \SqlSemantics\Platform\PostgreSql\Semantics();
36 $context = [$semantics->inspect('CREATE MATERIALIZED VIEW m AS SELECT 1 AS a'), $semantics->inspect('CREATE FOREIGN TABLE f (a int) SERVER x')];
37 self::assertSame(['rules on materialized views are not supported'], array_map(static fn ($problem): string => $problem->message(), $semantics->inspect('CREATE RULE r AS ON INSERT TO m DO INSTEAD NOTHING', $context)->facts->diagnostics));
38 self::assertSame(['relation "f" cannot have rules'], array_map(static fn ($problem): string => $problem->message(), $semantics->inspect('CREATE RULE r AS ON INSERT TO f DO INSTEAD NOTHING', $context)->facts->diagnostics));
39 }
40}
41