packages/sql-semantics-sqlite/src/Rules/Typing/CallChecks.php
1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\Sqlite\Rules\Typing;
6
7use SqlSemantics\Platform\Sqlite\Model\Construction\Derivation;
8use SqlSemantics\Platform\Sqlite\Statement\Expression\FunctionCall;
9use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\CallMisuse;
10use SqlSemantics\Platform\Sqlite\Statement\Query\Problem\CallMisuseRule;
11use SqlSemantics\Platform\Sqlite\Statement\Query\SetQuantifier;
12
13/**
14 * Reports the clauses of a call that the kind of the called built-in function does not take.
15 *
16 * Rule: SQLITE-CALL-CLAUSE-001. A window-only function must be called with
17 * OVER; a scalar function may not be called with OVER, FILTER or an argument
18 * ordering; a call with OVER takes no DISTINCT and no argument ordering; a
19 * window-only function takes no FILTER; a DISTINCT aggregate takes exactly
20 * one argument. The kind comes from SQLITE-FUNCTION-RESULT-001 for the
21 * written number of arguments; a name outside the table or a wrong number
22 * of arguments is checked elsewhere and nothing is reported here.
23 * Terminates: a fixed number of tests on one call.
24 * Source: https://sqlite.org/lang_aggfunc.html, https://sqlite.org/windowfunctions.html.
25 * Status: Implemented.
26 *
27 * @visibility SqlSemantics\Platform\Sqlite
28 */
29final class CallChecks
30{
31 /**
32 * Reports every rule the call breaks.
33 */
34 public function report(FunctionCall $call, Derivation $derivation): void
35 {
36 $row = (new Functions())->row($call->name->value, count($call->arguments));
37 if ($row === null) {
38 return;
39 }
40 foreach ($this->broken($call, $row[4]) as $rule) {
41 $derivation->report(new CallMisuse($rule, $call->name));
42 }
43 }
44
45 /**
46 * Answers the rules a call of a function of the kind breaks, in a fixed order.
47 *
48 * @param string $kind The kind code: s scalar, a aggregate, w window only
49 * @return list<CallMisuseRule>
50 */
51 public function broken(FunctionCall $call, string $kind): array
52 {
53 $windowed = $call->over !== null;
54 $distinct = $call->quantifier === SetQuantifier::Distinct;
55 $tests = [
56 [CallMisuseRule::WindowWithoutOver, $kind === 'w' && !$windowed],
57 [CallMisuseRule::ScalarAsWindow, $kind === 's' && $windowed],
58 [CallMisuseRule::FilterWithoutAggregate, $kind === 's' && $call->filter !== null],
59 [CallMisuseRule::FilterOnWindowOnly, $kind === 'w' && $windowed && $call->filter !== null],
60 [CallMisuseRule::OrderByWithoutAggregate, ($kind === 's' || $windowed) && $call->order !== []],
61 [CallMisuseRule::DistinctInWindow, $kind !== 's' && $windowed && $distinct],
62 [CallMisuseRule::DistinctArguments, $kind === 'a' && !$windowed && $distinct && count($call->arguments) !== 1],
63 ];
64 $broken = [];
65 foreach ($tests as [$rule, $holds]) {
66 if ($holds) {
67 $broken[] = $rule;
68 }
69 }
70
71 return $broken;
72 }
73}
74