packages/sql-semantics-postgres/tests/Unit/Statement/Expression/Operator/NegationTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Expression\Operator;
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\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\BinaryOperation;
21use SqlSemantics\Platform\PostgreSql\Statement\Expression\Operator\BooleanOperation;
22use SqlSemantics\Platform\PostgreSql\Statement\Expression\Operator\BooleanOperator;
23use SqlSemantics\Platform\PostgreSql\Statement\Expression\Operator\Negation;
24use SqlSemantics\Platform\PostgreSql\Statement\Literal\Constant;
25use SqlSemantics\Platform\PostgreSql\Statement\Literal\IntegerConstant;
26use SqlSemantics\Platform\PostgreSql\Statement\Literal\NullLiteral;
27use SqlSemantics\Platform\PostgreSql\Statement\Name\OperatorName;
28use SqlSemantics\Platform\PostgreSql\Statement\Type\Descriptor\Builtin;
29
30#[CoversClass(Negation::class)]
31#[Small]
32final class NegationTest extends TestCase
33{
34    public function testDeriveScalarIsBoolean(): void
35    {
36        $derivation = new Derivation((new Platform())->context(new LanguageProfile(GrammarRelease::PostgreSql172), null, [], true));
37        $comparison = new BinaryOperation(new OperatorName(new Name('=')), new Constant(new IntegerConstant('1')), new Constant(new IntegerConstant('2')));
38        $fact = $derivation->scalar(new Negation($comparison), $derivation->environment());
39        self::assertEquals(new Known(Builtin::Bool), $fact->type);
40        self::assertSame(Nullability::NotNull, $fact->nullability);
41    }
42
43    public function testRenderWritesNot(): void
44    {
45        $out = new Output(new Codec(GrammarRelease::PostgreSql172));
46        (new Negation(new Negation(new NullLiteral())))->render($out);
47        self::assertSame('NOT NOT NULL', (new Lexical())->join($out->pieces()));
48    }
49
50    public function testRejectsAConjunction(): void
51    {
52        $this->expectExceptionMessage('The operand of NOT needs parentheses to keep its place.');
53        new Negation(new BooleanOperation(BooleanOperator::And, new NullLiteral(), new NullLiteral()));
54    }
55}
56