packages/sql-semantics-postgres/tests/Unit/Statement/Invocation/Conditional/CoalesceTest.php
1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Invocation\Conditional;
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\Invocation\Conditional\Coalesce;
21use SqlSemantics\Platform\PostgreSql\Statement\Literal\Constant;
22use SqlSemantics\Platform\PostgreSql\Statement\Literal\IntegerConstant;
23use SqlSemantics\Platform\PostgreSql\Statement\Literal\NullLiteral;
24use SqlSemantics\Platform\PostgreSql\Statement\Type\Descriptor\Builtin;
25
26#[CoversClass(Coalesce::class)]
27#[Small]
28final class CoalesceTest extends TestCase
29{
30 public function testRejectsNoValue(): void
31 {
32 $this->expectExceptionMessage('COALESCE takes at least one value.');
33 new Coalesce([]);
34 }
35
36 public function testOutputNameIsCoalesce(): void
37 {
38 self::assertSame('coalesce', (new Coalesce([new NullLiteral()]))->outputName()->value);
39 }
40
41 public function testDeriveScalarIsNotNullWhenAValueIsNotNull(): void
42 {
43 $derivation = new Derivation((new Platform())->context(new LanguageProfile(GrammarRelease::PostgreSql172), null, [], true));
44 $fact = $derivation->scalar(new Coalesce([new NullLiteral(), new Constant(new IntegerConstant('1'))]), $derivation->environment());
45 self::assertEquals(new ScalarFact(new Known(Builtin::Int4), Nullability::NotNull), $fact);
46 }
47
48 public function testRenderWritesTheValues(): void
49 {
50 $coalesce = new Coalesce([new NullLiteral(), new Constant(new IntegerConstant('1'))]);
51 $out = new Output(new Codec(GrammarRelease::PostgreSql172));
52 $coalesce->render($out);
53 self::assertSame('COALESCE(NULL, 1)', (new Lexical())->join($out->pieces()));
54 }
55}
56