packages/sql-semantics-mysql/tests/Unit/Statement/Query/Clause/GroupingTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Query\Clause;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10use SqlSemantics\Platform\MySql\Semantics;
11use SqlSemantics\Platform\MySql\Statement\Query\Clause\Grouping;
12use SqlSemantics\Platform\MySql\Statement\Query\Clause\GroupingModifier;
13use SqlSemantics\Platform\MySql\Statement\Query\Direction;
14use SqlSemantics\Platform\MySql\Statement\Query\Select;
15
16#[CoversClass(Grouping::class)]
17#[Medium]
18final class GroupingTest extends TestCase
19{
20    public function testRenderWritesTheItemsAndTheModifier(): void
21    {
22        self::assertSame('SELECT a FROM t GROUP BY a, b WITH ROLLUP', (new Semantics())->analyze('select a from t group by a, b with rollup')->toString());
23        self::assertSame('SELECT a FROM t GROUP BY ROLLUP (a, b)', (new Semantics('mysql-9.1.0'))->analyze('select a from t group by rollup (a, b)')->toString());
24        self::assertSame('SELECT a FROM t GROUP BY CUBE (a)', (new Semantics('mysql-9.1.0'))->analyze('select a from t group by cube (a)')->toString());
25        self::assertSame('SELECT a FROM t GROUP BY a DESC WITH CUBE', (new Semantics('mysql-5.6.51'))->analyze('select a from t group by a desc with cube')->toString());
26    }
27
28    public function testItemsKeepTheirWrittenOrderAndDirection(): void
29    {
30        $operation = (new Semantics('mysql-5.7.44'))->analyze('SELECT a FROM t GROUP BY b DESC, a');
31
32        self::assertInstanceOf(Select::class, $operation->statement);
33        self::assertNotNull($operation->statement->groupBy);
34        self::assertSame(Direction::Descending, $operation->statement->groupBy->items[0]->direction);
35        self::assertNull($operation->statement->groupBy->items[1]->direction);
36        self::assertNull($operation->statement->groupBy->modifier);
37    }
38
39    public function testAnEmptyGroupingIsRejected(): void
40    {
41        $this->expectExceptionMessage('GROUP BY holds at least one grouping expression.');
42
43        new Grouping([], GroupingModifier::WithRollup);
44    }
45}
46