packages/sql-semantics-sqlite/tests/Unit/Statement/Query/Ordering/SortTermTest.php
1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Query\Ordering;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Medium;
9use PHPUnit\Framework\TestCase;
10use SqlSemantics\Platform\Sqlite\Model\Statement\Identifier\Name;
11use SqlSemantics\Platform\Sqlite\Model\Statement\Identifier\QualifiedName;
12use SqlSemantics\Platform\Sqlite\Model\Statement\Operation;
13use SqlSemantics\Platform\Sqlite\Semantics;
14use SqlSemantics\Platform\Sqlite\Statement\Expression\ColumnUse;
15use SqlSemantics\Platform\Sqlite\Statement\Expression\Operator\Binary;
16use SqlSemantics\Platform\Sqlite\Statement\Query\Ordering\NullsOrder;
17use SqlSemantics\Platform\Sqlite\Statement\Query\Ordering\SortDirection;
18use SqlSemantics\Platform\Sqlite\Statement\Query\Ordering\SortTerm;
19use SqlSemantics\Platform\Sqlite\Statement\Query\ResultColumn;
20use SqlSemantics\Platform\Sqlite\Statement\Query\Select;
21use SqlSemantics\Platform\Sqlite\Statement\Relation\TableInput;
22
23#[CoversClass(SortTerm::class)]
24#[Medium]
25final class SortTermTest extends TestCase
26{
27 public function testRenderWritesTheDirectionAndTheNullPlacement(): void
28 {
29 $query = (new Semantics())->analyze('select a from t order by a + 1 asc nulls first, b desc, a nulls last, b');
30
31 self::assertInstanceOf(Select::class, $query->statement);
32 $terms = $query->statement->orderBy;
33 self::assertInstanceOf(Binary::class, $terms[0]->expression);
34 self::assertSame(SortDirection::Ascending, $terms[0]->direction);
35 self::assertSame(NullsOrder::First, $terms[0]->nulls);
36 self::assertSame(SortDirection::Descending, $terms[1]->direction);
37 self::assertNull($terms[1]->nulls);
38 self::assertNull($terms[2]->direction);
39 self::assertSame(NullsOrder::Last, $terms[2]->nulls);
40 self::assertNull($terms[3]->direction);
41 self::assertNull($terms[3]->nulls);
42 self::assertSame('SELECT a FROM t ORDER BY a + 1 ASC NULLS FIRST, b DESC, a NULLS LAST, b', $query->toString());
43 }
44
45 public function testRenderWritesANewlyBuiltTerm(): void
46 {
47 $semantics = new Semantics();
48 $term = new SortTerm(new ColumnUse(new Name('a')), SortDirection::Descending, NullsOrder::Last);
49 $operation = new Operation($semantics->context(), new Select([new ResultColumn(new ColumnUse(new Name('a')))], new TableInput(new QualifiedName(new Name('t'))), null, [], null, [], [$term]));
50
51 self::assertSame('SELECT a FROM t ORDER BY a DESC NULLS LAST', $operation->toString());
52 }
53
54 public function testRenderWritesTheOrderingOfAnAggregateArgument(): void
55 {
56 $query = (new Semantics())->analyze('select group_concat(a order by b desc, a) AS c1 from t');
57
58 self::assertSame('SELECT group_concat(a ORDER BY b DESC, a) AS c1 FROM t', $query->toString());
59 }
60}
61