packages/sql-semantics-postgres/tests/Unit/Statement/Expression/Subquery/InListTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Expression\Subquery;
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\Query;
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\Subquery\InList;
21use SqlSemantics\Platform\PostgreSql\Statement\Expression\Subquery\ScalarSubquery;
22use SqlSemantics\Platform\PostgreSql\Statement\Literal\Constant;
23use SqlSemantics\Platform\PostgreSql\Statement\Literal\IntegerConstant;
24use SqlSemantics\Platform\PostgreSql\Statement\Literal\NullLiteral;
25use SqlSemantics\Platform\PostgreSql\Statement\Type\Descriptor\Builtin;
26
27#[CoversClass(InList::class)]
28#[Small]
29final class InListTest extends TestCase
30{
31    public function testDeriveScalarIsNullableWithANullItem(): void
32    {
33        $derivation = new Derivation((new Platform())->context(new LanguageProfile(GrammarRelease::PostgreSql172), null, [], true));
34        $fact = $derivation->scalar(new InList(new Constant(new IntegerConstant('1')), false, [new Constant(new IntegerConstant('2')), new NullLiteral()]), $derivation->environment());
35        self::assertEquals(new Known(Builtin::Bool), $fact->type);
36        self::assertSame(Nullability::Nullable, $fact->nullability);
37    }
38
39    public function testRenderWritesTheList(): void
40    {
41        $out = new Output(new Codec(GrammarRelease::PostgreSql172));
42        (new InList(new NullLiteral(), false, [new NullLiteral(), new NullLiteral()]))->render($out);
43        self::assertSame('NULL IN (NULL, NULL)', (new Lexical())->join($out->pieces()));
44    }
45
46    public function testRejectsASingleScalarSubquery(): void
47    {
48        $this->expectExceptionMessage('IN with one scalar subquery is read as IN (SELECT ...).');
49        new InList(new NullLiteral(), false, [new ScalarSubquery(self::createStub(Query::class))]);
50    }
51}
52