packages/sql-semantics-sqlite/src/Rules/Query/Aggregation.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\Sqlite\Rules\Query;
6
7use SqlSemantics\Platform\Sqlite\Model\Statement\Node;
8use SqlSemantics\Platform\Sqlite\Model\Validation\ValueGraph;
9use SqlSemantics\Platform\Sqlite\Rules\Typing\Functions;
10use SqlSemantics\Platform\Sqlite\Statement\Expression\FunctionCall;
11
12/**
13 * Finds the aggregate function calls among the parts of a selection.
14 *
15 * Rule: SQLITE-AGGREGATE-QUERY-001. A selection without GROUP BY that calls
16 * an aggregate function in its result columns, HAVING or ORDER BY returns
17 * one row even for an empty input; a column of the input read outside an
18 * aggregate is then NULL, so in such a selection every input column can be
19 * NULL. A call inside a nested query counts for the enclosing selection as
20 * well, which can only make more columns able to be NULL. Terminates: the
21 * structure is a finite tree walked once.
22 * Source: https://sqlite.org/lang_select.html#bare_columns_in_an_aggregate_query.
23 * Status: Implemented.
24 *
25 * @visibility SqlSemantics\Platform\Sqlite
26 */
27final class Aggregation
28{
29    /**
30     * Tells whether any of the nodes contains a call of a built-in aggregate function without a window.
31     *
32     * @param list<Node> $nodes
33     */
34    public function aggregates(array $nodes): bool
35    {
36        $graph = new ValueGraph(['SqlSemantics\\Platform\\Sqlite\\Model\\Statement\\', 'SqlSemantics\\Platform\\Sqlite\\Model\\Contract\\', 'SqlSemantics\\Platform\\Sqlite\\Statement\\']);
37        $functions = new Functions();
38        foreach ($nodes as $node) {
39            foreach ($graph->objects($node) as $object) {
40                if ($object instanceof FunctionCall && $object->over === null && $functions->aggregates($object->name->value, count($object->arguments))) {
41                    return true;
42                }
43            }
44        }
45
46        return false;
47    }
48}
49