packages/sql-semantics-postgres/tests/Unit/Statement/Table/View/CreateMaterializedViewTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Table\View;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10
11#[CoversClass(\SqlSemantics\Platform\PostgreSql\Statement\Table\View\CreateMaterializedView::class)]
12#[Medium]
13final class CreateMaterializedViewTest extends TestCase
14{
15    public function testDeriveStatementDeclaresTheViewWithTheNullFactsOfTheQuery(): void
16    {
17        $semantics = new \SqlSemantics\Platform\PostgreSql\Semantics();
18        $context = [];
19        array_push($context, ...$semantics->analyze('CREATE TABLE t (a int NOT NULL, b int, c text)')->declarations());
20        $statement = $semantics->analyze('CREATE MATERIALIZED VIEW m AS SELECT a, b FROM t', $context);
21        self::assertSame([
22          0 => 'a integer NotNull',
23          1 => 'b integer Nullable',
24        ], array_map(static fn ($column): string => $column->name->value . ' ' . $column->type->name() . ' ' . $column->nullability->name, $statement->declarations()[0]->columns));
25    }
26
27    public function testRenderWritesTheClauseAsWritten(): void
28    {
29        $semantics = new \SqlSemantics\Platform\PostgreSql\Semantics();
30        $statement = $semantics->analyze('CREATE MATERIALIZED VIEW IF NOT EXISTS m (x) USING heap WITH (fillfactor = 70) TABLESPACE s AS SELECT 1 WITH DATA', []);
31        self::assertSame('CREATE MATERIALIZED VIEW IF NOT EXISTS m (x) USING heap WITH (fillfactor = 70) TABLESPACE s AS SELECT 1 WITH DATA', $statement->toString());
32    }
33
34    public function testRejectsWithDataAfterAnOpenIsJsonTest(): void
35    {
36        $query = (new \SqlSemantics\Platform\PostgreSql\Semantics())->analyze('SELECT a FROM t ORDER BY b IS JSON')->statement;
37        self::assertInstanceOf(\SqlSemantics\Platform\PostgreSql\Statement\Query\Select::class, $query);
38        $this->expectExceptionMessage('A query ending in IS JSON without a uniqueness clause would take WITH DATA; group it.');
39        new \SqlSemantics\Platform\PostgreSql\Statement\Table\View\CreateMaterializedView(new \SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\QualifiedName(new \SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\Name('m')), $query, withData: true);
40    }
41}
42