packages/sql-semantics-mysql/src/Rules/Query/Having/ResultReferences.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Rules\Query\Having;
6
7use SqlSemantics\Platform\MySql\Model\Resolution\Environment;
8use SqlSemantics\Platform\MySql\Model\Resolution\LookupLevel;
9use SqlSemantics\Platform\MySql\Model\Statement\Identifier\Name;
10use SqlSemantics\Platform\MySql\Model\Statement\Identifier\QualifiedName;
11use SqlSemantics\Platform\MySql\Model\Statement\Reference\Column\AliasTarget;
12use SqlSemantics\Platform\MySql\Model\Statement\Reference\Column\AmbiguousColumn;
13use SqlSemantics\Platform\MySql\Model\Statement\Reference\Column\ConditionalColumn;
14use SqlSemantics\Platform\MySql\Model\Statement\Reference\Column\Resolution;
15use SqlSemantics\Platform\MySql\Model\Statement\Reference\Column\ResolvedColumn;
16use SqlSemantics\Platform\MySql\Model\Statement\Reference\Missing\MissingInput;
17use SqlSemantics\Platform\MySql\Model\Statement\Shape\Field;
18use SqlSemantics\Platform\MySql\Statement\Name\ColumnUse;
19
20/**
21 * Resolves a name against the GROUP BY columns and the select list of a grouped row.
22 *
23 * Rule: MYSQL-HAVING-REFERENCE-001, after resolve_ref_in_select_and_group,
24 * find_field_in_group_list (sql/item.cc) and find_item_in_list
25 * (sql/sql_base.cc). A name in HAVING outside set functions, and a name of a
26 * nested query that reaches the HAVING position outwards, is searched first
27 * among the GROUP BY items that are columns and then in the select list; a
28 * GROUP BY column wins over a select list item. In GROUP BY a column
29 * matches by its column name, and a qualified name also by the occurrence
30 * the column belongs to: a column of another occurrence ends the search
31 * without a match, and two equally good columns that differ are ambiguous.
32 * In the select list an unqualified name matches the first item that is
33 * not a column and is named so, else the column items named so (two
34 * different ones are ambiguous), else the column items whose column has
35 * the name under another alias (likewise); a qualified name matches only
36 * column items of an occurrence it admits. An item that is not a column
37 * and whose name depends on missing inputs (OutputSlot::$unnamed) may be
38 * the item named so: the outcome is conditional. A column item resolves to its
39 * column, another item to the item (an alias target). Names of columns are
40 * compared by the context's column comparison. Terminates: one pass over
41 * each list.
42 * Source: https://dev.mysql.com/doc/refman/8.4/en/select.html ("MySQL
43 * permits HAVING to refer to columns in the SELECT list and columns in
44 * outer subqueries"), https://dev.mysql.com/doc/refman/8.4/en/group-by-handling.html.
45 * Status: Implemented.
46 *
47 * @visibility SqlSemantics\Platform\MySql
48 */
49final class ResultReferences
50{
51    /**
52     * Resolves a name at a HAVING position of a query that lies a number of queries outwards; null when neither list has it.
53     */
54    public function find(GroupedRow $row, Environment $scope, Name $column, ?QualifiedName $qualifier, int $depth): ?Resolution
55    {
56        return $this->grouping($row, $scope, $column, $qualifier, $depth) ?? $this->selected($row, $scope, $column, $qualifier, $depth);
57    }
58
59    /**
60     * Searches the GROUP BY columns; null when none has the name.
61     */
62    public function grouping(GroupedRow $row, Environment $scope, Name $column, ?QualifiedName $qualifier, int $depth): ?Resolution
63    {
64        $best = null;
65        $degree = 0;
66        foreach ($row->grouping as $item) {
67            $resolution = $item->resolution;
68            if (!$resolution instanceof ResolvedColumn || !$this->named($scope, $resolution, $column)) {
69                continue;
70            }
71            if ($qualifier !== null && !$this->admitted($scope, $resolution, $column, $qualifier)) {
72                return null;
73            }
74            $current = $qualifier === null ? 1 : ($qualifier->schema === null ? 2 : 3);
75            if ($best !== null && $current === $degree && !$this->same($best, $resolution)) {
76                return new AmbiguousColumn($column, [$this->deeper($best, $depth), $this->deeper($resolution, $depth)]);
77            }
78            if ($current > $degree) {
79                [$best, $degree] = [$resolution, $current];
80            }
81        }
82
83        return $best === null ? null : $this->deeper($best, $depth);
84    }
85
86    /**
87     * Searches the select list; null when no item has the name.
88     */
89    public function selected(GroupedRow $row, Environment $scope, Name $column, ?QualifiedName $qualifier, int $depth): ?Resolution
90    {
91        [$aliased, $unaliased, $other] = [null, null, null];
92        $unnamed = $this->unnamed($row, $scope, $column, $qualifier);
93        foreach ($row->selected as $item) {
94            $field = $item instanceof Field ? $item : null;
95            $resolution = $field?->expression instanceof ColumnUse ? $field->resolution : null;
96            $named = $qualifier === null && $field?->name !== null && $scope->context->columnNames->equal($field->name->value, $column->value);
97            if ($field !== null && $named && !$resolution instanceof ResolvedColumn) {
98                return $this->undecided($column, new AliasTarget($field), $unnamed);
99            }
100            if (!$resolution instanceof ResolvedColumn) {
101                continue;
102            }
103            if ($named) {
104                if ($aliased !== null && !$this->same($aliased, $resolution)) {
105                    return new AmbiguousColumn($column, [$this->deeper($aliased, $depth), $this->deeper($resolution, $depth)]);
106                }
107                $aliased = $resolution;
108            } elseif ($this->unaliased($scope, $resolution, $column, $qualifier)) {
109                $other = $other ?? ($unaliased !== null && !$this->same($unaliased, $resolution) ? $resolution : null);
110                $unaliased = $unaliased ?? $resolution;
111            }
112        }
113
114        return $this->undecided($column, $this->chosen($column, $aliased, $unaliased, $other, $depth), $unnamed);
115    }
116
117    /**
118     * Answers a select list match, or the conditional outcome while items whose names depend on missing inputs could be the match instead.
119     *
120     * @param list<MissingInput> $unnamed The inputs the names of those items depend on
121     */
122    public function undecided(Name $column, ?Resolution $match, array $unnamed): ?Resolution
123    {
124        if ($unnamed === []) {
125            return $match;
126        }
127
128        return new ConditionalColumn($column, $match instanceof ResolvedColumn ? [$match] : [], [], $unnamed);
129    }
130
131    /**
132     * Answers the inputs the names of the items that are not columns depend on, up to the first such item an unqualified name names.
133     *
134     * @return list<MissingInput>
135     */
136    public function unnamed(GroupedRow $row, Environment $scope, Name $column, ?QualifiedName $qualifier): array
137    {
138        $missing = [];
139        foreach ($qualifier === null ? $row->selected : [] as $item) {
140            if (!$item instanceof Field || ($item->expression instanceof ColumnUse && $item->resolution instanceof ResolvedColumn)) {
141                continue;
142            }
143            if ($item->name !== null && $scope->context->columnNames->equal($item->name->value, $column->value)) {
144                break;
145            }
146            array_push($missing, ...$item->slot->unnamed);
147        }
148
149        return $missing;
150    }
151
152    /**
153     * Tells whether a column item of the select list matches a name by its column rather than by its alias.
154     */
155    public function unaliased(Environment $scope, ResolvedColumn $resolution, Name $column, ?QualifiedName $qualifier): bool
156    {
157        return $this->named($scope, $resolution, $column) && ($qualifier === null || $this->admitted($scope, $resolution, $column, $qualifier));
158    }
159
160    /**
161     * Chooses among the select list matches: the item matched by its alias, else the only column matched by its own name.
162     */
163    public function chosen(Name $column, ?ResolvedColumn $aliased, ?ResolvedColumn $unaliased, ?ResolvedColumn $other, int $depth): ?Resolution
164    {
165        if ($aliased === null && $unaliased !== null && $other !== null) {
166            return new AmbiguousColumn($column, [$this->deeper($unaliased, $depth), $this->deeper($other, $depth)]);
167        }
168        $chosen = $aliased ?? $unaliased;
169
170        return $chosen === null ? null : $this->deeper($chosen, $depth);
171    }
172
173    /**
174     * Tells whether the column of a resolution has a name.
175     */
176    public function named(Environment $scope, ResolvedColumn $resolution, Name $column): bool
177    {
178        return $resolution->slot->name !== null && $scope->context->columnNames->equal($resolution->slot->name->value, $column->value);
179    }
180
181    /**
182     * Tells whether a qualified name finds a resolved column in the occurrences of a position.
183     */
184    public function admitted(Environment $scope, ResolvedColumn $resolution, Name $column, QualifiedName $qualifier): bool
185    {
186        foreach ((new LookupLevel($scope, $column, $qualifier, 0))->found() as $found) {
187            if ($this->same($found, $resolution)) {
188                return true;
189            }
190        }
191
192        return false;
193    }
194
195    /**
196     * Tells whether two resolutions denote the same column of the same occurrence.
197     */
198    public function same(ResolvedColumn $left, ResolvedColumn $right): bool
199    {
200        return $left->relation === $right->relation && $left->slot === $right->slot;
201    }
202
203    /**
204     * Answers a resolution as seen from a use a number of queries further in.
205     */
206    public function deeper(ResolvedColumn $resolution, int $depth): ResolvedColumn
207    {
208        return $depth === 0 ? $resolution : new ResolvedColumn($resolution->relation, $resolution->slot, $resolution->depth + $depth);
209    }
210}
211