packages/sql-semantics-postgres/src/Lowering/Invocation/WindowRule.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Lowering\Invocation;
6
7use SqlParser\Parser\Node;
8use SqlSemantics\Platform\PostgreSql\Lowering\Lowering;
9use SqlSemantics\Platform\PostgreSql\Model\Diagnostic\AnalysisException;
10use SqlSemantics\Platform\PostgreSql\Model\Diagnostic\ImplementationGap;
11use SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\Name;
12use SqlSemantics\Platform\PostgreSql\Statement\Invocation\FrameBound;
13use SqlSemantics\Platform\PostgreSql\Statement\Invocation\FrameBoundKind;
14use SqlSemantics\Platform\PostgreSql\Statement\Invocation\FrameExclusion;
15use SqlSemantics\Platform\PostgreSql\Statement\Invocation\FrameMode;
16use SqlSemantics\Platform\PostgreSql\Statement\Invocation\WindowFrame;
17use SqlSemantics\Platform\PostgreSql\Statement\Invocation\WindowSpecification;
18
19/**
20 * Lowers OVER clauses and window specifications.
21 *
22 * Rule: PG-WINDOW-LOWERING-001. Scope: `over_clause`,
23 * `window_specification`, `opt_existing_window_name`, `opt_partition_clause`,
24 * `opt_frame_clause`, `frame_extent`, `frame_bound`,
25 * `opt_window_exclusion_clause`. Constructors: `WindowSpecification`,
26 * `WindowFrame`, `FrameBound`. `EXCLUDE NO OTHERS` states the default and is
27 * noise (see `InvocationNoise`). The frames the grammar's action rejects
28 * (a start at UNBOUNDED FOLLOWING, an end at UNBOUNDED PRECEDING, a frame
29 * that ends before it starts) raise an `AnalysisException` with the server's
30 * message. Termination: the partition list is flattened iteratively.
31 * Source: https://www.postgresql.org/docs/17/sql-expressions.html#SYNTAX-WINDOW-FUNCTIONS. Status: Implemented.
32 *
33 * @visibility SqlSemantics\Platform\PostgreSql\Lowering
34 */
35final class WindowRule
36{
37    /**
38     * The frame bound kinds by production signature.
39     */
40    private const BOUNDS = [
41        'frame_bound: UNBOUNDED PRECEDING' => FrameBoundKind::UnboundedPreceding,
42        'frame_bound: UNBOUNDED FOLLOWING' => FrameBoundKind::UnboundedFollowing,
43        'frame_bound: CURRENT_P ROW' => FrameBoundKind::CurrentRow,
44        'frame_bound: a_expr PRECEDING' => FrameBoundKind::OffsetPreceding,
45        'frame_bound: a_expr FOLLOWING' => FrameBoundKind::OffsetFollowing,
46    ];
47
48    /**
49     * The frame exclusions by production signature; EXCLUDE NO OTHERS is no exclusion.
50     */
51    private const EXCLUSIONS = [
52        'opt_window_exclusion_clause:' => null,
53        'opt_window_exclusion_clause: EXCLUDE NO OTHERS' => null,
54        'opt_window_exclusion_clause: EXCLUDE CURRENT_P ROW' => FrameExclusion::CurrentRow,
55        'opt_window_exclusion_clause: EXCLUDE GROUP_P' => FrameExclusion::Group,
56        'opt_window_exclusion_clause: EXCLUDE TIES' => FrameExclusion::Ties,
57    ];
58
59    /**
60     * The frame modes by production signature.
61     */
62    private const MODES = [
63        'opt_frame_clause: RANGE frame_extent opt_window_exclusion_clause' => FrameMode::Range,
64        'opt_frame_clause: ROWS frame_extent opt_window_exclusion_clause' => FrameMode::Rows,
65        'opt_frame_clause: GROUPS frame_extent opt_window_exclusion_clause' => FrameMode::Groups,
66    ];
67
68    /**
69     * @param Lowering $lowering The hub
70     */
71    public function __construct(private readonly Lowering $lowering)
72    {
73    }
74
75    /**
76     * Lowers `over_clause`: a specification, a window name, or nothing.
77     *
78     * @throws AnalysisException When the frame is one the actions of `frame_extent` in `gram.y` reject
79     * @throws ImplementationGap When the production has no rule
80     */
81    public function over(Node $clause): WindowSpecification|Name|null
82    {
83        $form = $this->lowering->productions->form($clause);
84
85        return match ($form->signature) {
86            'over_clause:' => null,
87            'over_clause: OVER window_specification' => $this->specification($form->node(1)),
88            'over_clause: OVER ColId' => $this->lowering->names->name($form->node(1)),
89            default => throw ImplementationGap::production($form),
90        };
91    }
92
93    /**
94     * Lowers `window_specification`.
95     *
96     * @throws AnalysisException When the frame is one the server rejects while parsing
97     * @throws ImplementationGap When the production has no rule
98     */
99    public function specification(Node $specification): WindowSpecification
100    {
101        $form = $this->lowering->productions->form($specification);
102        if ($form->signature !== 'window_specification: ( opt_existing_window_name opt_partition_clause opt_sort_clause opt_frame_clause )') {
103            throw ImplementationGap::production($form);
104        }
105        $existing = $this->lowering->productions->form($form->node(1));
106        $name = match ($existing->signature) {
107            'opt_existing_window_name:' => null,
108            'opt_existing_window_name: ColId' => $this->lowering->names->name($existing->node(0)),
109            default => throw ImplementationGap::production($existing),
110        };
111        $partition = $this->lowering->productions->form($form->node(2));
112        $expressions = match ($partition->signature) {
113            'opt_partition_clause:' => [],
114            'opt_partition_clause: PARTITION BY expr_list' => $this->lowering->expressions->expressions($partition->node(2)),
115            default => throw ImplementationGap::production($partition),
116        };
117
118        return new WindowSpecification($name, $expressions, $this->lowering->queries->sortClause($form->node(3)), $this->frame($form->node(4)));
119    }
120
121    /**
122     * Lowers `opt_frame_clause`; no clause is null.
123     *
124     * @throws AnalysisException When the frame is one the server rejects while parsing
125     * @throws ImplementationGap When the production has no rule
126     */
127    public function frame(Node $clause): ?WindowFrame
128    {
129        $form = $this->lowering->productions->form($clause);
130        if ($form->signature === 'opt_frame_clause:') {
131            return null;
132        }
133        $mode = self::MODES[$form->signature] ?? throw ImplementationGap::production($form);
134        $exclusion = $this->lowering->productions->form($form->node(2));
135        if (!array_key_exists($exclusion->signature, self::EXCLUSIONS)) {
136            throw ImplementationGap::production($exclusion);
137        }
138        $extent = $this->lowering->productions->form($form->node(1));
139        [$start, $end] = match ($extent->signature) {
140            'frame_extent: frame_bound' => [$this->bound($extent->node(0)), null],
141            'frame_extent: BETWEEN frame_bound AND frame_bound' => [$this->bound($extent->node(1)), $this->bound($extent->node(3))],
142            default => throw ImplementationGap::production($extent),
143        };
144        $this->check($start->kind, $end?->kind);
145
146        return new WindowFrame($mode, $start, $end, self::EXCLUSIONS[$exclusion->signature]);
147    }
148
149    /**
150     * Rejects the frames the actions of `frame_extent` in `gram.y` reject, with the server's messages.
151     *
152     * @throws AnalysisException When the frame is rejected
153     */
154    public function check(FrameBoundKind $start, ?FrameBoundKind $end): void
155    {
156        $last = $end ?? FrameBoundKind::CurrentRow;
157        $problem = match (true) {
158            $start === FrameBoundKind::UnboundedFollowing => 'frame start cannot be UNBOUNDED FOLLOWING',
159            $end === null && $start === FrameBoundKind::OffsetFollowing => 'frame starting from following row cannot end with current row',
160            $last === FrameBoundKind::UnboundedPreceding => 'frame end cannot be UNBOUNDED PRECEDING',
161            $start === FrameBoundKind::CurrentRow && $last === FrameBoundKind::OffsetPreceding => 'frame starting from current row cannot have preceding rows',
162            $start === FrameBoundKind::OffsetFollowing && ($last === FrameBoundKind::OffsetPreceding || $last === FrameBoundKind::CurrentRow) => 'frame starting from following row cannot have preceding rows',
163            default => null,
164        };
165        if ($problem !== null) {
166            throw new AnalysisException($problem);
167        }
168    }
169
170    /**
171     * Lowers `frame_bound`.
172     *
173     * @throws ImplementationGap When the production has no rule
174     */
175    public function bound(Node $bound): FrameBound
176    {
177        $form = $this->lowering->productions->form($bound);
178        $kind = self::BOUNDS[$form->signature] ?? throw ImplementationGap::production($form);
179
180        return new FrameBound($kind, $kind->offset() ? $this->lowering->expressions->expression($form->node(0)) : null);
181    }
182}
183