packages/sql-semantics-sqlite/tests/Unit/Statement/Expression/Window/WindowDefinitionTest.php
1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Expression\Window;
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\Operation;
12use SqlSemantics\Platform\Sqlite\Semantics;
13use SqlSemantics\Platform\Sqlite\Statement\Expression\FunctionCall;
14use SqlSemantics\Platform\Sqlite\Statement\Expression\Literal\IntegerLiteral;
15use SqlSemantics\Platform\Sqlite\Statement\Expression\Window\WindowDefinition;
16use SqlSemantics\Platform\Sqlite\Statement\Expression\Window\WindowSpec;
17use SqlSemantics\Platform\Sqlite\Statement\Query\ResultColumn;
18use SqlSemantics\Platform\Sqlite\Statement\Query\Select;
19
20#[CoversClass(WindowDefinition::class)]
21#[Medium]
22final class WindowDefinitionTest extends TestCase
23{
24 public function testReadsTheNameAndTheSpecification(): void
25 {
26 $semantics = new Semantics();
27 $create = $semantics->analyze('CREATE TABLE t (a INTEGER NOT NULL, b TEXT)');
28 $operation = $semantics->analyze('SELECT rank() OVER w FROM t WINDOW w AS (ORDER BY a), v AS (w PARTITION BY b)', [$create]);
29 $statement = $operation->statement;
30
31 self::assertInstanceOf(Select::class, $statement);
32 self::assertCount(2, $statement->windows);
33 self::assertSame('w', $statement->windows[0]->name->value);
34 self::assertCount(1, $statement->windows[0]->window->order);
35 self::assertSame('v', $statement->windows[1]->name->value);
36 self::assertSame('w', $statement->windows[1]->window->base?->value);
37 self::assertCount(1, $statement->windows[1]->window->partition);
38 self::assertTrue($operation->facts->covers($statement->windows[0]->window->order[0]->expression));
39 self::assertSame([], $operation->facts->diagnostics);
40 }
41
42 public function testRenderWritesTheNameAndTheParenthesizedSpecification(): void
43 {
44 $operation = (new Semantics())->analyze('select rank() over w AS c1 from t window w as (order by a), v as (), u as (w partition by b rows unbounded preceding)');
45
46 self::assertSame('SELECT rank() OVER w AS c1 FROM t WINDOW w AS (ORDER BY a), v AS (), u AS (w PARTITION BY b ROWS UNBOUNDED PRECEDING)', $operation->toString());
47 }
48
49 public function testRenderWritesANewlyBuiltDefinition(): void
50 {
51 $semantics = new Semantics();
52 $definition = new WindowDefinition(new Name('w'), new WindowSpec(new Name('v'), [new IntegerLiteral('1')]));
53 $operation = new Operation($semantics->context(), new Select([new ResultColumn(new FunctionCall(new Name('rank'), [], false, null, [], null, new Name('w')))], null, null, [], null, [$definition]));
54
55 self::assertSame('SELECT rank() OVER w WINDOW w AS (v PARTITION BY 1)', $operation->toString());
56 }
57}
58