packages/sql-semantics-postgres/tests/Unit/Statement/Invocation/Conditional/NullIfTest.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\NullIf;
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\Literal\StringConstant;
25use SqlSemantics\Platform\PostgreSql\Statement\Type\Descriptor\Builtin;
26
27#[CoversClass(NullIf::class)]
28#[Small]
29final class NullIfTest extends TestCase
30{
31 public function testOutputNameIsNullif(): void
32 {
33 self::assertSame('nullif', (new NullIf(new NullLiteral(), new NullLiteral()))->outputName()->value);
34 }
35
36 public function testDeriveScalarTakesTheTypeOfTheFirstOperand(): void
37 {
38 $derivation = new Derivation((new Platform())->context(new LanguageProfile(GrammarRelease::PostgreSql172), null, [], true));
39 $fact = $derivation->scalar(new NullIf(new Constant(new IntegerConstant('1')), new Constant(new StringConstant('2'))), $derivation->environment());
40 self::assertEquals(new ScalarFact(new Known(Builtin::Int4), Nullability::Nullable), $fact);
41 }
42
43 public function testDeriveScalarPromotesAStringFirstOperand(): void
44 {
45 $derivation = new Derivation((new Platform())->context(new LanguageProfile(GrammarRelease::PostgreSql172), null, [], true));
46 $fact = $derivation->scalar(new NullIf(new Constant(new StringConstant('1')), new Constant(new IntegerConstant('1'))), $derivation->environment());
47 self::assertEquals(new ScalarFact(new Known(Builtin::Int4), Nullability::Nullable), $fact);
48 }
49
50 public function testRenderWritesBothOperands(): void
51 {
52 $nullif = new NullIf(new Constant(new IntegerConstant('1')), new NullLiteral());
53 $out = new Output(new Codec(GrammarRelease::PostgreSql172));
54 $nullif->render($out);
55 self::assertSame('NULLIF(1, NULL)', (new Lexical())->join($out->pieces()));
56 }
57}
58