packages/sql-semantics-sqlite/tests/Unit/Statement/Expression/FunctionCallTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Statement\Expression;
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\Model\Statement\Reference\Missing\UndeclaredRoutine;
14use SqlSemantics\Platform\Sqlite\Model\Statement\Type\Choice;
15use SqlSemantics\Platform\Sqlite\Model\Statement\Type\Dependent;
16use SqlSemantics\Platform\Sqlite\Model\Statement\Type\Invalid;
17use SqlSemantics\Platform\Sqlite\Model\Statement\Type\Known;
18use SqlSemantics\Platform\Sqlite\Model\Statement\Type\Nullability;
19use SqlSemantics\Platform\Sqlite\Semantics;
20use SqlSemantics\Platform\Sqlite\Statement\Expression\FunctionCall;
21use SqlSemantics\Platform\Sqlite\Statement\Expression\Literal\IntegerLiteral;
22use SqlSemantics\Platform\Sqlite\Statement\Expression\Window\Frame;
23use SqlSemantics\Platform\Sqlite\Statement\Expression\Window\FrameBound;
24use SqlSemantics\Platform\Sqlite\Statement\Expression\Window\FrameBoundKind;
25use SqlSemantics\Platform\Sqlite\Statement\Expression\Window\FrameUnit;
26use SqlSemantics\Platform\Sqlite\Statement\Expression\Window\WindowSpec;
27use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\CallMisuse;
28use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\CallMisuseRule;
29use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\WrongArgumentCount;
30use SqlSemantics\Platform\Sqlite\Statement\Query\ResultColumn;
31use SqlSemantics\Platform\Sqlite\Statement\Query\Select;
32use SqlSemantics\Platform\Sqlite\Statement\Query\SetQuantifier;
33use SqlSemantics\Platform\Sqlite\Statement\Type\Storage;
34
35#[CoversClass(FunctionCall::class)]
36#[Medium]
37final class FunctionCallTest extends TestCase
38{
39    public function testDeriveScalarReadsThePartsOfAnAggregateCall(): void
40    {
41        $semantics = new Semantics();
42        $create = $semantics->inspect('CREATE TABLE t (a INTEGER NOT NULL, b TEXT)');
43        $operation = $semantics->inspect('SELECT count(DISTINCT a ORDER BY b) FILTER (WHERE a > 0), count(*) FROM t', [$create]);
44        $statement = $operation->statement;
45
46        self::assertInstanceOf(Select::class, $statement);
47        self::assertInstanceOf(ResultColumn::class, $statement->columns[0]);
48        self::assertInstanceOf(ResultColumn::class, $statement->columns[1]);
49        self::assertInstanceOf(FunctionCall::class, $statement->columns[0]->expression);
50        self::assertInstanceOf(FunctionCall::class, $statement->columns[1]->expression);
51        $call = $statement->columns[0]->expression;
52        self::assertSame('count', $call->name->value);
53        self::assertSame(SetQuantifier::Distinct, $call->quantifier);
54        self::assertCount(1, $call->arguments);
55        self::assertCount(1, $call->order);
56        self::assertNotNull($call->filter);
57        self::assertFalse($call->star);
58        self::assertNull($call->over);
59        self::assertTrue($statement->columns[1]->expression->star);
60        self::assertEquals(new Known(Storage::Integer), $operation->field(0)->type);
61        self::assertSame(Nullability::NotNull, $operation->field(0)->nullability);
62        self::assertSame([], $operation->facts->diagnostics);
63    }
64
65    public function testDeriveScalarGivesTheDocumentedResultOfBuiltInFunctions(): void
66    {
67        $semantics = new Semantics();
68        $create = $semantics->inspect('CREATE TABLE t (a INTEGER NOT NULL, b TEXT)');
69        $operation = $semantics->inspect('SELECT abs(a), length(b), total(a), coalesce(b, 1), upper(b), typeof(b), max(a), sum(a) FROM t', [$create]);
70
71        self::assertEquals(new Choice([Storage::Integer, Storage::Real]), $operation->field(0)->type);
72        self::assertSame(Nullability::Nullable, $operation->field(0)->nullability);
73        self::assertEquals(new Known(Storage::Integer), $operation->field(1)->type);
74        self::assertSame(Nullability::Nullable, $operation->field(1)->nullability);
75        self::assertEquals(new Known(Storage::Real), $operation->field(2)->type);
76        self::assertSame(Nullability::NotNull, $operation->field(2)->nullability);
77        self::assertEquals(new Choice([Storage::Integer, Storage::Text, Storage::Blob]), $operation->field(3)->type);
78        self::assertSame(Nullability::NotNull, $operation->field(3)->nullability);
79        self::assertEquals(new Known(Storage::Text), $operation->field(4)->type);
80        self::assertSame(Nullability::NotNull, $operation->field(5)->nullability);
81        self::assertSame(Nullability::Nullable, $operation->field(6)->nullability);
82        self::assertEquals(new Choice([Storage::Integer, Storage::Real]), $operation->field(7)->type);
83        self::assertSame([], $operation->facts->diagnostics);
84    }
85
86    public function testDeriveScalarReportsAWrongArgumentCount(): void
87    {
88        $operation = (new Semantics())->inspect('SELECT abs(1, 2), abs()', []);
89        $statement = $operation->statement;
90
91        self::assertInstanceOf(Select::class, $statement);
92        self::assertInstanceOf(ResultColumn::class, $statement->columns[0]);
93        $fact = $operation->facts->scalar($statement->columns[0]->expression);
94        self::assertInstanceOf(Invalid::class, $fact->type);
95        self::assertEquals(new WrongArgumentCount(new Name('abs'), 2), $fact->type->cause);
96        self::assertSame(Nullability::Dependent, $fact->nullability);
97        self::assertEquals([new WrongArgumentCount(new Name('abs'), 2), new WrongArgumentCount(new Name('abs'), 0)], $operation->facts->diagnostics);
98        self::assertSame('wrong number of arguments to function abs()', $operation->facts->diagnostics[1]->message());
99    }
100
101    public function testDeriveScalarDependsOnAnUndeclaredRoutine(): void
102    {
103        $operation = (new Semantics())->inspect('SELECT foo(1)', []);
104
105        self::assertEquals(new Dependent([new UndeclaredRoutine(new QualifiedName(new Name('foo')))]), $operation->field(0)->type);
106        self::assertSame(Nullability::Dependent, $operation->field(0)->nullability);
107        self::assertSame([], $operation->facts->diagnostics);
108    }
109
110    public function testDeriveScalarReportsAWindowFunctionWithoutOver(): void
111    {
112        $operation = (new Semantics())->inspect('SELECT row_number()', []);
113
114        self::assertEquals([new CallMisuse(CallMisuseRule::WindowWithoutOver, new Name('row_number'))], $operation->facts->diagnostics);
115        self::assertSame('misuse of window function row_number()', $operation->facts->diagnostics[0]->message());
116    }
117
118    public function testDeriveScalarReportsAScalarFunctionUsedAsAWindow(): void
119    {
120        $operation = (new Semantics())->inspect('SELECT abs(1) OVER ()', []);
121
122        self::assertEquals([new CallMisuse(CallMisuseRule::ScalarAsWindow, new Name('abs'))], $operation->facts->diagnostics);
123        self::assertSame('abs() may not be used as a window function', $operation->facts->diagnostics[0]->message());
124    }
125
126    public function testDeriveScalarReportsAFilterOnAScalarFunction(): void
127    {
128        $operation = (new Semantics())->inspect('SELECT abs(1) FILTER (WHERE 1)', []);
129
130        self::assertEquals([new CallMisuse(CallMisuseRule::FilterWithoutAggregate, new Name('abs'))], $operation->facts->diagnostics);
131        self::assertSame('FILTER may not be used with non-aggregate abs()', $operation->facts->diagnostics[0]->message());
132    }
133
134    public function testDeriveScalarReportsAFilterOnAWindowOnlyFunction(): void
135    {
136        $semantics = new Semantics();
137        $create = $semantics->inspect('CREATE TABLE t (a INTEGER NOT NULL, b TEXT)');
138        $operation = $semantics->inspect('SELECT rank() FILTER (WHERE 1) OVER () FROM t', [$create]);
139
140        self::assertEquals([new CallMisuse(CallMisuseRule::FilterOnWindowOnly, new Name('rank'))], $operation->facts->diagnostics);
141        self::assertSame('FILTER clause may only be used with aggregate window functions', $operation->facts->diagnostics[0]->message());
142    }
143
144    public function testDeriveScalarReportsAnOrderingInsideAScalarCall(): void
145    {
146        $operation = (new Semantics())->inspect('SELECT abs(1 ORDER BY 1)', []);
147
148        self::assertEquals([new CallMisuse(CallMisuseRule::OrderByWithoutAggregate, new Name('abs'))], $operation->facts->diagnostics);
149    }
150
151    public function testDeriveScalarReportsDistinctInAWindow(): void
152    {
153        $semantics = new Semantics();
154        $create = $semantics->inspect('CREATE TABLE t (a INTEGER NOT NULL, b TEXT)');
155        $operation = $semantics->inspect('SELECT sum(DISTINCT a) OVER () FROM t', [$create]);
156
157        self::assertEquals([new CallMisuse(CallMisuseRule::DistinctInWindow, new Name('sum'))], $operation->facts->diagnostics);
158        self::assertSame('DISTINCT is not supported for window functions', $operation->facts->diagnostics[0]->message());
159    }
160
161    public function testDeriveScalarReportsDistinctWithSeveralArguments(): void
162    {
163        $semantics = new Semantics();
164        $create = $semantics->inspect('CREATE TABLE t (a INTEGER NOT NULL, b TEXT)');
165        $operation = $semantics->inspect("SELECT group_concat(DISTINCT a, ',') FROM t", [$create]);
166
167        self::assertEquals([new CallMisuse(CallMisuseRule::DistinctArguments, new Name('group_concat'))], $operation->facts->diagnostics);
168        self::assertSame('DISTINCT aggregates must have exactly one argument', $operation->facts->diagnostics[0]->message());
169        self::assertEquals(new Known(Storage::Text), $operation->field(0)->type);
170    }
171
172    public function testDeriveScalarAcceptsAggregatesUsedAsWindowsAndNamedWindows(): void
173    {
174        $semantics = new Semantics();
175        $create = $semantics->inspect('CREATE TABLE t (a INTEGER NOT NULL, b TEXT)');
176        $operation = $semantics->inspect('SELECT sum(a) FILTER (WHERE a > 0) OVER (PARTITION BY b), rank() OVER w, lag(a, 1, 0) OVER (ORDER BY a) FROM t WINDOW w AS (ORDER BY a)', [$create]);
177        $statement = $operation->statement;
178
179        self::assertInstanceOf(Select::class, $statement);
180        self::assertInstanceOf(ResultColumn::class, $statement->columns[1]);
181        self::assertInstanceOf(FunctionCall::class, $statement->columns[1]->expression);
182        self::assertInstanceOf(Name::class, $statement->columns[1]->expression->over);
183        self::assertSame('w', $statement->columns[1]->expression->over->value);
184        self::assertSame([], $operation->facts->diagnostics);
185        self::assertEquals(new Known(Storage::Integer), $operation->field(1)->type);
186        self::assertSame(Nullability::NotNull, $operation->field(1)->nullability);
187        self::assertSame(Nullability::Nullable, $operation->field(2)->nullability);
188    }
189
190    public function testRenderWritesEveryPartInOrder(): void
191    {
192        $operation = (new Semantics())->inspect('select count(*) AS c1, count(distinct a order by b desc) filter (where a > 0) AS c2, group_concat(b, \',\') over (partition by a) AS c3, rank() over w AS c4, foo() AS c5 from t window w as ()');
193
194        self::assertSame('SELECT count(*) AS c1, count(DISTINCT a ORDER BY b DESC) FILTER (WHERE a > 0) AS c2, group_concat(b, \',\') OVER (PARTITION BY a) AS c3, rank() OVER w AS c4, foo() AS c5 FROM t WINDOW w AS ()', $operation->toString());
195    }
196
197    public function testRenderWritesANewlyBuiltCall(): void
198    {
199        $semantics = new Semantics();
200        $frame = new Frame(FrameUnit::Rows, new FrameBound(FrameBoundKind::UnboundedPreceding), new FrameBound(FrameBoundKind::CurrentRow));
201        $operation = new Operation($semantics->context(), new Select([new ResultColumn(new FunctionCall(new Name('sum'), [new IntegerLiteral('1')], false, null, [], null, new WindowSpec(null, [], [], $frame))), new ResultColumn(new FunctionCall(new Name('count'), [], true))]));
202
203        self::assertSame('SELECT sum(1) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW), count(*)', $operation->toString());
204        self::assertSame([], $operation->facts->diagnostics);
205    }
206}
207