packages/sql-semantics-mysql/tests/Unit/Statement/Relation/JsonTableTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Relation;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10use SqlSemantics\Platform\MySql\Model\Statement\Shape\Field;
11use SqlSemantics\Platform\MySql\Semantics;
12use SqlSemantics\Platform\MySql\Statement\Literal\NullLiteral;
13use SqlSemantics\Platform\MySql\Statement\Literal\StringLiteral;
14use SqlSemantics\Platform\MySql\Statement\Query\Problem\Misuse;
15use SqlSemantics\Platform\MySql\Statement\Query\Problem\MisuseRule;
16use SqlSemantics\Platform\MySql\Statement\Relation\JsonTable;
17
18#[CoversClass(JsonTable::class)]
19#[Medium]
20final class JsonTableTest extends TestCase
21{
22    public function testDeriveRelationAnswersTheColumnsOfTheDefinitions(): void
23    {
24        $operation = (new Semantics())->inspect("SELECT a, n FROM JSON_TABLE('[1]', '$[*]' COLUMNS (n FOR ORDINALITY, a INT PATH '$')) AS j", []);
25
26        self::assertSame(['a', 'n'], array_map(static fn (Field $field): ?string => $field->name?->value, $operation->fields()->items ?? []));
27        self::assertSame([], $operation->facts->diagnostics);
28    }
29
30    public function testDeriveRelationReportsAMissingAlias(): void
31    {
32        $operation = (new Semantics())->inspect("SELECT 1 FROM JSON_TABLE('[1]', '$[*]' COLUMNS (a INT PATH '$'))", []);
33
34        self::assertCount(1, $operation->facts->diagnostics);
35        self::assertInstanceOf(Misuse::class, $operation->facts->diagnostics[0]);
36        self::assertSame(MisuseRule::TableFunctionWithoutAlias, $operation->facts->diagnostics[0]->rule);
37    }
38
39    public function testRenderWritesTheTableFunction(): void
40    {
41        self::assertSame("SELECT a FROM t, JSON_TABLE(t.d, '$' COLUMNS (a INT PATH '$')) j", (new Semantics())->inspect("select a from t, json_table(t.d, '$' columns (a int path '$')) j")->toString());
42    }
43
44    public function testATableWithoutColumnsIsRejected(): void
45    {
46        $this->expectExceptionMessage('JSON_TABLE defines at least one column.');
47
48        new JsonTable(new NullLiteral(), new StringLiteral(['$']), []);
49    }
50}
51