packages/sql-semantics-postgres/tests/Unit/Statement/Utility/Maintenance/ExplainTest.php
1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Utility\Maintenance;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10use SqlSemantics\Platform\PostgreSql\Model\Contract\GrammarRelease;
11use SqlSemantics\Platform\PostgreSql\Model\Contract\LanguageProfile;
12use SqlSemantics\Platform\PostgreSql\Model\Statement\Declaration\Column;
13use SqlSemantics\Platform\PostgreSql\Model\Statement\Declaration\Table;
14use SqlSemantics\Platform\PostgreSql\Model\Statement\Fact\Diagnostic;
15use SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\Name;
16use SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\QualifiedName;
17use SqlSemantics\Platform\PostgreSql\Semantics;
18use SqlSemantics\Platform\PostgreSql\Statement\Type\Descriptor\Builtin;
19use SqlSemantics\Platform\PostgreSql\Statement\Utility\Maintenance\Explain;
20
21#[CoversClass(Explain::class)]
22#[Medium]
23final class ExplainTest extends TestCase
24{
25 public function testDeriveStatementPublishesThePlanRowInsteadOfTheRowsOfTheStatement(): void
26 {
27 $operation = (new Semantics())->inspect('EXPLAIN SELECT 1 AS a, 2 AS b');
28 self::assertSame([1, 'QUERY PLAN'], [count($operation->shape()->slots ?? []), $operation->field(0)->name?->value]);
29 }
30
31 public function testDeriveStatementDerivesTheExplainedStatement(): void
32 {
33 $table = new Table(new QualifiedName(new Name('t')), new LanguageProfile(GrammarRelease::PostgreSql172), [new Column(new Name('a'), Builtin::Int4)]);
34 self::assertSame(
35 ['Column b does not exist.'],
36 array_map(static fn (Diagnostic $diagnostic): string => $diagnostic->message(), (new Semantics())->inspect('EXPLAIN ANALYZE UPDATE t SET a = b', [$table])->facts->diagnostics),
37 );
38 }
39
40 public function testDeriveStatementReportsUnknownOptions(): void
41 {
42 self::assertSame(
43 ['unrecognized EXPLAIN option "fast"', 'costs requires a Boolean value'],
44 array_map(static fn (Diagnostic $diagnostic): string => $diagnostic->message(), (new Semantics())->inspect('EXPLAIN (fast, costs 5) SELECT 1')->facts->diagnostics),
45 );
46 }
47
48 public function testRenderWritesEachSyntax(): void
49 {
50 $semantics = new Semantics();
51 self::assertSame(
52 ['EXPLAIN ANALYSE VERBOSE SELECT 1', 'EXPLAIN VERBOSE VALUES (1)', 'EXPLAIN (ANALYZE, FORMAT json) DELETE FROM t', 'EXPLAIN ("format" json, format text) EXECUTE p'],
53 [$semantics->inspect('explain analyse verbose select 1')->toString(), $semantics->inspect('EXPLAIN VERBOSE VALUES (1)')->toString(), $semantics->inspect('EXPLAIN (ANALYZE, FORMAT JSON) DELETE FROM t')->toString(), $semantics->inspect('EXPLAIN ("format" json, format text) EXECUTE p')->toString()],
54 );
55 }
56}
57