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

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Invocation\Text;
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\Fact\ScalarFact;
16use SqlSemantics\Platform\PostgreSql\Model\Statement\Type\Known;
17use SqlSemantics\Platform\PostgreSql\Model\Statement\Type\Nullability;
18use SqlSemantics\Platform\PostgreSql\Platform;
19use SqlSemantics\Platform\PostgreSql\Rendering\Codec;
20use SqlSemantics\Platform\PostgreSql\Statement\Expression\Operator\Negation;
21use SqlSemantics\Platform\PostgreSql\Statement\Invocation\Text\Position;
22use SqlSemantics\Platform\PostgreSql\Statement\Literal\BooleanLiteral;
23use SqlSemantics\Platform\PostgreSql\Statement\Literal\Constant;
24use SqlSemantics\Platform\PostgreSql\Statement\Literal\NullLiteral;
25use SqlSemantics\Platform\PostgreSql\Statement\Literal\StringConstant;
26use SqlSemantics\Platform\PostgreSql\Statement\Type\Descriptor\Builtin;
27
28#[CoversClass(Position::class)]
29#[Small]
30final class PositionTest extends TestCase
31{
32    public function testRejectsAnOperandThatIsNotRestricted(): void
33    {
34        $this->expectExceptionMessage('The operands of POSITION are restricted expressions; group an operand that is not.');
35        new Position(new Negation(new BooleanLiteral(true)), new NullLiteral());
36    }
37
38    public function testOutputNameIsPosition(): void
39    {
40        self::assertSame('position', (new Position(new NullLiteral(), new NullLiteral()))->outputName()->value);
41    }
42
43    public function testDeriveScalarIsInteger(): void
44    {
45        $derivation = new Derivation((new Platform())->context(new LanguageProfile(GrammarRelease::PostgreSql172), null, [], true));
46        $fact = $derivation->scalar(new Position(new Constant(new StringConstant('b')), new Constant(new StringConstant('abc'))), $derivation->environment());
47        self::assertEquals(new ScalarFact(new Known(Builtin::Int4), Nullability::NotNull), $fact);
48    }
49
50    public function testRenderWritesTheSubstringFirst(): void
51    {
52        $position = new Position(new Constant(new StringConstant('b')), new Constant(new StringConstant('abc')));
53        $out = new Output(new Codec(GrammarRelease::PostgreSql172));
54        $position->render($out);
55        self::assertSame('POSITION(\'b\' IN \'abc\')', (new Lexical())->join($out->pieces()));
56    }
57}
58