packages/sql-semantics-postgres/src/Lowering/Query/ClauseRule.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Lowering\Query;
6
7use SqlParser\Parser\Node;
8use SqlSemantics\Platform\PostgreSql\Lowering\Lowering;
9use SqlSemantics\Platform\PostgreSql\Model\Diagnostic\ImplementationGap;
10use SqlSemantics\Platform\PostgreSql\Model\Statement\Scalar;
11use SqlSemantics\Platform\PostgreSql\Rules\Query\Positions;
12use SqlSemantics\Platform\PostgreSql\Statement\Expression\Constructor\RowConstructor;
13use SqlSemantics\Platform\PostgreSql\Statement\Expression\Constructor\RowSpelling;
14use SqlSemantics\Platform\PostgreSql\Statement\Expression\Grouped;
15use SqlSemantics\Platform\PostgreSql\Statement\Query\Clause\OutputPosition;
16use SqlSemantics\Platform\PostgreSql\Statement\Query\Clause\SelectOptions;
17use SqlSemantics\Platform\PostgreSql\Statement\Query\Clause\WindowDefinition;
18use SqlSemantics\Platform\PostgreSql\Statement\Query\Grouping\GroupingRow;
19use SqlSemantics\Platform\PostgreSql\Statement\Query\Grouping\GroupingSet;
20use SqlSemantics\Platform\PostgreSql\Statement\Query\Grouping\GroupingSetKind;
21use SqlSemantics\Platform\PostgreSql\Statement\Query\NullsOrder;
22use SqlSemantics\Platform\PostgreSql\Statement\Query\Problem\OrderingClause;
23use SqlSemantics\Platform\PostgreSql\Statement\Query\SetQuantifier;
24use SqlSemantics\Platform\PostgreSql\Statement\Query\SortDirection;
25use SqlSemantics\Platform\PostgreSql\Statement\Query\SortItem;
26
27/**
28 * Lowers the clauses of a selection and the clauses written after a query body.
29 *
30 * Rule: PG-CLAUSE-LOWER-001. Scope: `where_clause`, `group_clause`,
31 * `group_by_list`, `group_by_item`, `empty_grouping_set`, `rollup_clause`,
32 * `cube_clause`, `grouping_sets_clause`, `having_clause`, `window_clause`,
33 * `window_definition_list`, `window_definition`, `opt_sort_clause`,
34 * `sort_clause`, `sortby_list`, `sortby`, `opt_asc_desc`, `opt_nulls_order`.
35 * Constructors: `SortItem`, `GroupingSet`, `WindowDefinition`,
36 * `OutputPosition`, `SelectOptions`. An integer constant written as an
37 * ORDER BY, GROUP BY or DISTINCT ON term becomes an `OutputPosition`
38 * (PG-OUTPUT-POSITION-001); in the ORDER BY of an aggregate or a window it
39 * stays a constant. Termination: lists are flattened iteratively; grouping
40 * sets recurse on the tree depth.
41 * Source: https://www.postgresql.org/docs/17/sql-select.html. Status: Implemented.
42 *
43 * @visibility SqlSemantics
44 */
45final class ClauseRule
46{
47    /**
48     * @param Lowering $lowering The hub
49     */
50    public function __construct(private readonly Lowering $lowering)
51    {
52    }
53
54    /**
55     * Lowers the ORDER BY, LIMIT and locking clauses written after a query body; none is null.
56     */
57    public function options(Node $sort, ?Node $limit, ?Node $locking, bool $lockingFirst): ?SelectOptions
58    {
59        $order = [];
60        foreach ($this->sortClause($sort) as $item) {
61            $order[] = new SortItem($this->positioned([$item->expression], OrderingClause::OrderBy)[0], $item->direction, $item->using, $item->nulls);
62        }
63        $rows = $limit === null ? null : (new LimitRule($this->lowering))->limit($limit);
64        [$clauses, $readOnly] = $locking === null ? [[], false] : (new LimitRule($this->lowering))->locking($locking);
65        if ($order === [] && $rows === null && $clauses === [] && !$readOnly) {
66            return null;
67        }
68
69        return new SelectOptions($order, $rows, $clauses, $readOnly, $lockingFirst && $rows !== null && ($clauses !== [] || $readOnly));
70    }
71
72    /**
73     * Wraps the integer constants among ORDER BY, GROUP BY or DISTINCT ON terms as output positions.
74     *
75     * @param list<Scalar> $terms
76     * @return list<Scalar>
77     */
78    public function positioned(array $terms, OrderingClause $clause): array
79    {
80        $result = [];
81        foreach ($terms as $term) {
82            $result[] = (new Positions())->value($term) === null ? $term : new OutputPosition($term, $clause);
83        }
84
85        return $result;
86    }
87
88    /**
89     * Reads expressions in a grouping position: a row written without ROW, in any parentheses, is a list of grouping terms, and an integer constant is an output position.
90     *
91     * @param list<Scalar> $terms
92     * @return list<Scalar|GroupingRow>
93     */
94    public function groupingTerms(array $terms): array
95    {
96        $result = [];
97        foreach ($terms as $term) {
98            $layers = 0;
99            $inner = $term;
100            while ($inner instanceof Grouped) {
101                $inner = $inner->operand;
102                $layers++;
103            }
104            if (!$inner instanceof RowConstructor || $inner->spelling !== RowSpelling::Implicit) {
105                $result[] = $this->positioned([$term], OrderingClause::GroupBy)[0];
106                continue;
107            }
108            $row = new GroupingRow($this->groupingTerms($inner->fields));
109            for (; $layers > 0; $layers--) {
110                $row = new GroupingRow([$row]);
111            }
112            $result[] = $row;
113        }
114
115        return $result;
116    }
117
118    /**
119     * Lowers `sort_clause`, `opt_sort_clause` or `sortby_list` without reading positions; no clause is an empty list.
120     *
121     * @return list<SortItem>
122     *
123     * @throws ImplementationGap When the production has no rule
124     */
125    public function sortClause(Node $clause): array
126    {
127        $form = $this->lowering->productions->form($clause);
128        $list = match ($form->signature) {
129            'opt_sort_clause:' => null,
130            'opt_sort_clause: sort_clause' => $this->lowering->productions->form($form->node(0))->node(2),
131            'sort_clause: ORDER BY sortby_list' => $form->node(2),
132            'sortby_list: sortby', 'sortby_list: sortby_list , sortby' => $clause,
133            default => throw ImplementationGap::production($form),
134        };
135        $items = [];
136        foreach ($list === null ? [] : $this->lowering->items($list, 'sortby_list: sortby', 'sortby_list: sortby_list , sortby') as $sortby) {
137            $item = $this->lowering->productions->form($sortby);
138            $items[] = match ($item->signature) {
139                'sortby: a_expr USING qual_all_Op opt_nulls_order' => new SortItem($this->lowering->expressions->expression($item->node(0)), null, $this->lowering->operators->operator($item->node(2)), $this->nullsOrder($item->node(3))),
140                'sortby: a_expr opt_asc_desc opt_nulls_order' => new SortItem($this->lowering->expressions->expression($item->node(0)), $this->sortDirection($item->node(1)), null, $this->nullsOrder($item->node(2))),
141                default => throw ImplementationGap::production($item),
142            };
143        }
144
145        return $items;
146    }
147
148    /**
149     * Lowers `opt_asc_desc`; no direction is null.
150     *
151     * @throws ImplementationGap When the production has no rule
152     */
153    public function sortDirection(Node $direction): ?SortDirection
154    {
155        $form = $this->lowering->productions->form($direction);
156
157        return match ($form->signature) {
158            'opt_asc_desc: ASC' => SortDirection::Ascending,
159            'opt_asc_desc: DESC' => SortDirection::Descending,
160            'opt_asc_desc:' => null,
161            default => throw ImplementationGap::production($form),
162        };
163    }
164
165    /**
166     * Lowers `opt_nulls_order`; no clause is null.
167     *
168     * @throws ImplementationGap When the production has no rule
169     */
170    public function nullsOrder(Node $order): ?NullsOrder
171    {
172        $form = $this->lowering->productions->form($order);
173
174        return match ($form->signature) {
175            'opt_nulls_order: NULLS_LA FIRST_P' => NullsOrder::First,
176            'opt_nulls_order: NULLS_LA LAST_P' => NullsOrder::Last,
177            'opt_nulls_order:' => null,
178            default => throw ImplementationGap::production($form),
179        };
180    }
181
182    /**
183     * Lowers `where_clause`; no clause is null.
184     *
185     * @throws ImplementationGap When the production has no rule
186     */
187    public function where(Node $clause): ?Scalar
188    {
189        $form = $this->lowering->productions->form($clause);
190
191        return match ($form->signature) {
192            'where_clause:' => null,
193            'where_clause: WHERE a_expr' => $this->lowering->expressions->expression($form->node(1)),
194            default => throw ImplementationGap::production($form),
195        };
196    }
197
198    /**
199     * Lowers `having_clause`; no clause is null.
200     *
201     * @throws ImplementationGap When the production has no rule
202     */
203    public function having(Node $clause): ?Scalar
204    {
205        $form = $this->lowering->productions->form($clause);
206
207        return match ($form->signature) {
208            'having_clause:' => null,
209            'having_clause: HAVING a_expr' => $this->lowering->expressions->expression($form->node(1)),
210            default => throw ImplementationGap::production($form),
211        };
212    }
213
214    /**
215     * Lowers `group_clause`: the quantifier and the items; no clause has neither.
216     *
217     * @return array{SetQuantifier|null, list<Scalar|GroupingRow|GroupingSet>}
218     *
219     * @throws ImplementationGap When the production has no rule
220     */
221    public function group(Node $clause): array
222    {
223        $form = $this->lowering->productions->form($clause);
224
225        return match ($form->signature) {
226            'group_clause:' => [null, []],
227            'group_clause: GROUP_P BY set_quantifier group_by_list' => [(new SelectRule($this->lowering))->quantifier($form->node(2)), $this->groupItems($form->node(3))],
228            default => throw ImplementationGap::production($form),
229        };
230    }
231
232    /**
233     * Lowers `group_by_list`.
234     *
235     * @return list<Scalar|GroupingRow|GroupingSet>
236     *
237     * @throws ImplementationGap When an item has no rule
238     */
239    public function groupItems(Node $list): array
240    {
241        $items = [];
242        foreach ($this->lowering->items($list, 'group_by_list: group_by_item', 'group_by_list: group_by_list , group_by_item') as $item) {
243            $form = $this->lowering->productions->form($item);
244            $items[] = match ($form->signature) {
245                'group_by_item: a_expr' => $this->groupingTerms([$this->lowering->expressions->expression($form->node(0))])[0],
246                'group_by_item: empty_grouping_set', 'group_by_item: cube_clause', 'group_by_item: rollup_clause', 'group_by_item: grouping_sets_clause' => $this->groupingSet($form->node(0)),
247                default => throw ImplementationGap::production($form),
248            };
249        }
250
251        return $items;
252    }
253
254    /**
255     * Lowers `empty_grouping_set`, `rollup_clause`, `cube_clause` or `grouping_sets_clause`.
256     *
257     * @throws ImplementationGap When the production has no rule
258     */
259    public function groupingSet(Node $set): GroupingSet
260    {
261        $form = $this->lowering->productions->form($set);
262
263        return match ($form->signature) {
264            'empty_grouping_set: ( )' => new GroupingSet(GroupingSetKind::Empty),
265            'rollup_clause: ROLLUP ( expr_list )' => new GroupingSet(GroupingSetKind::Rollup, $this->groupingTerms($this->lowering->expressions->expressions($form->node(2)))),
266            'cube_clause: CUBE ( expr_list )' => new GroupingSet(GroupingSetKind::Cube, $this->groupingTerms($this->lowering->expressions->expressions($form->node(2)))),
267            'grouping_sets_clause: GROUPING SETS ( group_by_list )' => new GroupingSet(GroupingSetKind::Sets, $this->groupItems($form->node(3))),
268            default => throw ImplementationGap::production($form),
269        };
270    }
271
272    /**
273     * Lowers `window_clause`; no clause is an empty list.
274     *
275     * @return list<WindowDefinition>
276     *
277     * @throws ImplementationGap When the production has no rule
278     */
279    public function windows(Node $clause): array
280    {
281        $form = $this->lowering->productions->form($clause);
282        if ($form->signature === 'window_clause:') {
283            return [];
284        }
285        if ($form->signature !== 'window_clause: WINDOW window_definition_list') {
286            throw ImplementationGap::production($form);
287        }
288        $windows = [];
289        foreach ($this->lowering->items($form->node(1), 'window_definition_list: window_definition', 'window_definition_list: window_definition_list , window_definition') as $definition) {
290            $window = $this->lowering->productions->form($definition);
291            if ($window->signature !== 'window_definition: ColId AS window_specification') {
292                throw ImplementationGap::production($window);
293            }
294            $windows[] = new WindowDefinition($this->lowering->names->name($window->node(0)), $this->lowering->invocations->window($window->node(2)));
295        }
296
297        return $windows;
298    }
299}
300