packages/sql-semantics-sqlite/tests/Unit/Statement/Expression/CaseBranchTest.php
1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Expression;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10use SqlSemantics\Platform\Sqlite\Model\Statement\Operation;
11use SqlSemantics\Platform\Sqlite\Semantics;
12use SqlSemantics\Platform\Sqlite\Statement\Expression\CaseBranch;
13use SqlSemantics\Platform\Sqlite\Statement\Expression\CaseExpression;
14use SqlSemantics\Platform\Sqlite\Statement\Expression\ColumnUse;
15use SqlSemantics\Platform\Sqlite\Statement\Expression\Literal\IntegerLiteral;
16use SqlSemantics\Platform\Sqlite\Statement\Expression\Literal\NullLiteral;
17use SqlSemantics\Platform\Sqlite\Statement\Expression\Literal\TextLiteral;
18use SqlSemantics\Platform\Sqlite\Statement\Query\ResultColumn;
19use SqlSemantics\Platform\Sqlite\Statement\Query\Select;
20
21#[CoversClass(CaseBranch::class)]
22#[Medium]
23final class CaseBranchTest extends TestCase
24{
25 public function testRenderKeepsTheConditionAndTheResultInOrder(): void
26 {
27 $operation = (new Semantics())->analyze('select case when a > 1 then \'x\' when a then 2 end AS c1 from t');
28 $statement = $operation->statement;
29
30 self::assertInstanceOf(Select::class, $statement);
31 self::assertInstanceOf(ResultColumn::class, $statement->columns[0]);
32 self::assertInstanceOf(CaseExpression::class, $statement->columns[0]->expression);
33 $branch = $statement->columns[0]->expression->branches[1];
34 self::assertInstanceOf(ColumnUse::class, $branch->when);
35 self::assertInstanceOf(IntegerLiteral::class, $branch->then);
36 self::assertSame('a', $branch->when->name->value);
37 self::assertSame('2', $branch->then->digits);
38 self::assertSame('SELECT CASE WHEN a > 1 THEN \'x\' WHEN a THEN 2 END AS c1 FROM t', $operation->toString());
39 }
40
41 public function testRenderWritesANewlyBuiltBranch(): void
42 {
43 $semantics = new Semantics();
44 $branch = new CaseBranch(new IntegerLiteral('1'), new TextLiteral('one'));
45 $operation = new Operation($semantics->context(), new Select([new ResultColumn(new CaseExpression(null, [$branch, new CaseBranch(new IntegerLiteral('2'), new NullLiteral())]))]));
46
47 self::assertSame("SELECT CASE WHEN 1 THEN 'one' WHEN 2 THEN NULL END", $operation->toString());
48 }
49}
50