packages/sql-semantics-postgres/tests/Unit/Statement/Invocation/Json/Constructor/JsonArrayQueryTest.php
1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Invocation\Json\Constructor;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10use SqlSemantics\Platform\PostgreSql\Model\Statement\Fact\ScalarFact;
11use SqlSemantics\Platform\PostgreSql\Model\Statement\Type\Known;
12use SqlSemantics\Platform\PostgreSql\Model\Statement\Type\Nullability;
13use SqlSemantics\Platform\PostgreSql\Semantics;
14use SqlSemantics\Platform\PostgreSql\Statement\Invocation\Json\Constructor\JsonArrayQuery;
15use SqlSemantics\Platform\PostgreSql\Statement\Invocation\Problem\JsonProblem;
16use SqlSemantics\Platform\PostgreSql\Statement\Invocation\Problem\JsonProblemKind;
17use SqlSemantics\Platform\PostgreSql\Statement\Query\ExpressionTarget;
18use SqlSemantics\Platform\PostgreSql\Statement\Query\Select;
19use SqlSemantics\Platform\PostgreSql\Statement\Type\Descriptor\Builtin;
20
21#[CoversClass(JsonArrayQuery::class)]
22#[Medium]
23final class JsonArrayQueryTest extends TestCase
24{
25 public function testOutputNameIsJsonArray(): void
26 {
27 $operation = (new Semantics())->inspect('SELECT JSON_ARRAY(SELECT 1, 2 RETURNING text)', []);
28 $select = $operation->statement;
29 self::assertInstanceOf(Select::class, $select);
30 $target = $select->targets[0];
31 self::assertInstanceOf(ExpressionTarget::class, $target);
32 $node = $target->expression;
33 self::assertInstanceOf(JsonArrayQuery::class, $node);
34 self::assertSame('json_array', $node->outputName()->value);
35 }
36
37 public function testDeriveScalarReportsAQueryOfSeveralColumns(): void
38 {
39 $operation = (new Semantics())->inspect('SELECT JSON_ARRAY(SELECT 1, 2 RETURNING text)', []);
40 $select = $operation->statement;
41 self::assertInstanceOf(Select::class, $select);
42 $target = $select->targets[0];
43 self::assertInstanceOf(ExpressionTarget::class, $target);
44 $node = $target->expression;
45 self::assertInstanceOf(JsonArrayQuery::class, $node);
46 self::assertEquals(new ScalarFact(new Known(Builtin::Text), Nullability::NotNull), $operation->facts->scalar($node));
47 self::assertEquals([new JsonProblem(JsonProblemKind::SubqueryColumns)], $operation->facts->diagnostics);
48 }
49
50 public function testRenderWritesTheQueryWithoutParentheses(): void
51 {
52 $operation = (new Semantics())->inspect('SELECT JSON_ARRAY(SELECT 1, 2 RETURNING text)', []);
53 $select = $operation->statement;
54 self::assertInstanceOf(Select::class, $select);
55 $target = $select->targets[0];
56 self::assertInstanceOf(ExpressionTarget::class, $target);
57 $node = $target->expression;
58 self::assertInstanceOf(JsonArrayQuery::class, $node);
59 self::assertSame('SELECT JSON_ARRAY(SELECT 1, 2 RETURNING text)', $operation->toString());
60 }
61}
62