packages/sql-semantics-postgres/tests/Unit/Statement/Routine/AtomicBodyTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Routine;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10use SqlSemantics\Platform\PostgreSql\Model\Construction\Derivation;
11use SqlSemantics\Platform\PostgreSql\Model\Contract\GrammarRelease;
12use SqlSemantics\Platform\PostgreSql\Model\Contract\LanguageProfile;
13use SqlSemantics\Platform\PostgreSql\Model\Rendering\Lexical;
14use SqlSemantics\Platform\PostgreSql\Model\Rendering\Output;
15use SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\Name;
16use SqlSemantics\Platform\PostgreSql\Platform;
17use SqlSemantics\Platform\PostgreSql\Rendering\Codec;
18use SqlSemantics\Platform\PostgreSql\Semantics;
19use SqlSemantics\Platform\PostgreSql\Statement\Literal\BooleanLiteral;
20use SqlSemantics\Platform\PostgreSql\Statement\Name\DottedName;
21use SqlSemantics\Platform\PostgreSql\Statement\Routine\AtomicBody;
22use SqlSemantics\Platform\PostgreSql\Statement\Routine\ReturnStatement;
23
24#[CoversClass(AtomicBody::class)]
25#[Medium]
26final class AtomicBodyTest extends TestCase
27{
28    public function testDeriveClauseDerivesEachStatement(): void
29    {
30        $derivation = new Derivation((new Platform())->context(new LanguageProfile(GrammarRelease::PostgreSql172), null, [], true));
31        $value = new BooleanLiteral(true);
32        (new AtomicBody([new ReturnStatement($value)]))->deriveClause($derivation, $derivation->environment());
33        self::assertTrue($derivation->facts()->covers($value));
34    }
35
36    public function testRenderEndsEachStatementWithASemicolon(): void
37    {
38        $out = new Output(new Codec(GrammarRelease::PostgreSql172));
39        (new AtomicBody([new ReturnStatement(new BooleanLiteral(true))]))->render($out);
40        self::assertSame('BEGIN ATOMIC RETURN TRUE; END', (new Lexical())->join($out->pieces()));
41    }
42
43    public function testDropsEmptyStatements(): void
44    {
45        $operation = (new Semantics())->analyze('CREATE FUNCTION f() RETURNS int4 BEGIN ATOMIC ; SELECT 1; ; END');
46        self::assertSame('CREATE FUNCTION f () RETURNS int4 BEGIN ATOMIC SELECT 1; END', $operation->toString());
47    }
48
49    public function testRejectsAnotherNode(): void
50    {
51        $this->expectExceptionMessage('A block holds statements and RETURN statements.');
52        new AtomicBody([new DottedName([new Name('a')])]);
53    }
54}
55