packages/sql-semantics-postgres/tests/Unit/Statement/Invocation/FrameBoundTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Invocation;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Small;
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\Platform;
16use SqlSemantics\Platform\PostgreSql\Rendering\Codec;
17use SqlSemantics\Platform\PostgreSql\Statement\Invocation\FrameBound;
18use SqlSemantics\Platform\PostgreSql\Statement\Invocation\FrameBoundKind;
19use SqlSemantics\Platform\PostgreSql\Statement\Literal\Constant;
20use SqlSemantics\Platform\PostgreSql\Statement\Literal\IntegerConstant;
21
22#[CoversClass(FrameBound::class)]
23#[Small]
24final class FrameBoundTest extends TestCase
25{
26    public function testDeriveClauseDerivesTheOffset(): void
27    {
28        $scalar = new Constant(new IntegerConstant('3'));
29        $derivation = new Derivation((new Platform())->context(new LanguageProfile(GrammarRelease::PostgreSql172), null, [], true));
30        (new FrameBound(FrameBoundKind::OffsetFollowing, $scalar))->deriveClause($derivation, $derivation->environment());
31        self::assertTrue($derivation->facts()->covers($scalar));
32    }
33
34    public function testRenderWritesTheOffsetBeforeTheKeyword(): void
35    {
36        $out = new Output(new Codec(GrammarRelease::PostgreSql172));
37        (new FrameBound(FrameBoundKind::OffsetPreceding, new Constant(new IntegerConstant('2'))))->render($out);
38        self::assertSame('2 PRECEDING', (new Lexical())->join($out->pieces()));
39        $second = new Output(new Codec(GrammarRelease::PostgreSql172));
40        (new FrameBound(FrameBoundKind::UnboundedFollowing))->render($second);
41        self::assertSame('UNBOUNDED FOLLOWING', (new Lexical())->join($second->pieces()));
42    }
43
44    public function testRejectsAnOffsetBoundWithoutAnOffset(): void
45    {
46        $this->expectExceptionMessage('A frame bound has an offset exactly when it is an offset bound.');
47        new FrameBound(FrameBoundKind::OffsetPreceding);
48    }
49
50    public function testRenderQuotesABareUnboundedColumn(): void
51    {
52        $query = (new \SqlSemantics\Platform\PostgreSql\Semantics())->analyze('SELECT count(*) OVER (ORDER BY 1 ROWS "unbounded" PRECEDING) FROM (SELECT 1 AS unbounded) AS s', []);
53        self::assertSame('SELECT count(*) OVER (ORDER BY 1 ROWS "unbounded" PRECEDING) FROM (SELECT 1 AS unbounded) AS s', $query->toString());
54    }
55}
56