packages/sql-semantics-postgres/tests/Unit/Statement/Table/Element/LikeClauseTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Table\Element;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10
11#[CoversClass(\SqlSemantics\Platform\PostgreSql\Statement\Table\Element\LikeClause::class)]
12#[Medium]
13final class LikeClauseTest extends TestCase
14{
15    public function testDeriveClauseResolvesTheSourceTable(): 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 TABLE n (LIKE t)', $context);
21        $n1 = $statement->statement;
22        self::assertInstanceOf(\SqlSemantics\Platform\PostgreSql\Statement\Table\CreateTable::class, $n1);
23        $n2 = $n1->definition;
24        self::assertInstanceOf(\SqlSemantics\Platform\PostgreSql\Statement\Table\Element\ListedColumns::class, $n2);
25        $n3 = $n2->elements[0];
26        self::assertInstanceOf(\SqlSemantics\Platform\PostgreSql\Statement\Table\Element\LikeClause::class, $n3);
27        $n4 = $statement->facts->relation($n3)->table;
28        self::assertInstanceOf(\SqlSemantics\Platform\PostgreSql\Model\Statement\Reference\Table\DeclaredTable::class, $n4);
29        self::assertSame(true, $n4->table === $context[0]);
30    }
31
32    public function testRenderWritesTheClauseAsWritten(): void
33    {
34        $semantics = new \SqlSemantics\Platform\PostgreSql\Semantics();
35        $statement = $semantics->inspect('CREATE TABLE n (LIKE s.t INCLUDING ALL EXCLUDING STATISTICS)', []);
36        self::assertSame('CREATE TABLE n (LIKE s.t INCLUDING ALL EXCLUDING STATISTICS)', $statement->toString());
37    }
38
39    public function testDeriveClauseReportsASequence(): void
40    {
41        $semantics = new \SqlSemantics\Platform\PostgreSql\Semantics();
42        $context = [$semantics->inspect('CREATE SEQUENCE s'), $semantics->inspect('CREATE VIEW v AS SELECT 1 AS a')];
43        self::assertSame(['relation "s" is invalid in LIKE clause'], array_map(static fn ($problem): string => $problem->message(), $semantics->inspect('CREATE TABLE c (LIKE s)', $context)->facts->diagnostics));
44        self::assertSame([], array_map(static fn ($problem): string => $problem->message(), $semantics->inspect('CREATE TABLE c (LIKE v)', $context)->facts->diagnostics));
45    }
46}
47