packages/sql-semantics-postgres/tests/Unit/Statement/Query/SortItemTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Query;
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\Model\Statement\Identifier\Name;
16use SqlSemantics\Platform\PostgreSql\Platform;
17use SqlSemantics\Platform\PostgreSql\Rendering\Codec;
18use SqlSemantics\Platform\PostgreSql\Statement\Literal\Constant;
19use SqlSemantics\Platform\PostgreSql\Statement\Literal\IntegerConstant;
20use SqlSemantics\Platform\PostgreSql\Statement\Name\OperatorName;
21use SqlSemantics\Platform\PostgreSql\Statement\Query\NullsOrder;
22use SqlSemantics\Platform\PostgreSql\Statement\Query\SortDirection;
23use SqlSemantics\Platform\PostgreSql\Statement\Query\SortItem;
24
25#[CoversClass(SortItem::class)]
26#[Small]
27final class SortItemTest extends TestCase
28{
29    public function testDeriveClauseDerivesTheSortKey(): void
30    {
31        $scalar = new Constant(new IntegerConstant('3'));
32        $derivation = new Derivation((new Platform())->context(new LanguageProfile(GrammarRelease::PostgreSql172), null, [], true));
33        (new SortItem($scalar, SortDirection::Descending))->deriveClause($derivation, $derivation->environment());
34        self::assertTrue($derivation->facts()->covers($scalar));
35    }
36
37    public function testRenderWritesDirectionAndNulls(): void
38    {
39        $out = new Output(new Codec(GrammarRelease::PostgreSql172));
40        (new SortItem(new Constant(new IntegerConstant('1')), SortDirection::Descending, null, NullsOrder::Last))->render($out);
41        self::assertSame('1 DESC NULLS LAST', (new Lexical())->join($out->pieces()));
42    }
43
44    public function testRenderWritesTheOrderingOperator(): void
45    {
46        $out = new Output(new Codec(GrammarRelease::PostgreSql172));
47        (new SortItem(new Constant(new IntegerConstant('1')), null, new OperatorName(new Name('<'), [new Name('pg_catalog')], true)))->render($out);
48        self::assertSame('1 USING OPERATOR (pg_catalog.<)', (new Lexical())->join($out->pieces()));
49    }
50
51    public function testRejectsADirectionNextToAnOperator(): void
52    {
53        $this->expectExceptionMessage('A sort key has a direction or an ordering operator, not both.');
54        new SortItem(new Constant(new IntegerConstant('1')), SortDirection::Ascending, new OperatorName(new Name('<')));
55    }
56}
57