packages/sql-semantics-postgres/src/Lowering/Expression/PrimaryRule.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Lowering\Expression;
6
7use SqlParser\Parser\Node;
8use SqlSemantics\Platform\PostgreSql\Lowering\Lowering;
9use SqlSemantics\Platform\PostgreSql\Model\Diagnostic\ImplementationGap;
10use SqlSemantics\Platform\PostgreSql\Model\Lowering\Form;
11use SqlSemantics\Platform\PostgreSql\Model\Statement\Scalar;
12use SqlSemantics\Platform\PostgreSql\Statement\Expression\ColumnReference;
13use SqlSemantics\Platform\PostgreSql\Statement\Expression\ColumnStar;
14use SqlSemantics\Platform\PostgreSql\Statement\Expression\Constructor\ArrayConstructor;
15use SqlSemantics\Platform\PostgreSql\Statement\Expression\FieldSelection;
16use SqlSemantics\Platform\PostgreSql\Statement\Expression\Grouped;
17use SqlSemantics\Platform\PostgreSql\Statement\Expression\GroupingFunction;
18use SqlSemantics\Platform\PostgreSql\Statement\Expression\Indirection;
19use SqlSemantics\Platform\PostgreSql\Statement\Expression\IndirectionStep;
20use SqlSemantics\Platform\PostgreSql\Statement\Expression\Step\AllFields;
21use SqlSemantics\Platform\PostgreSql\Statement\Expression\Step\Slice;
22use SqlSemantics\Platform\PostgreSql\Statement\Expression\Step\Subscript;
23use SqlSemantics\Platform\PostgreSql\Statement\Expression\Subquery\ArraySubquery;
24use SqlSemantics\Platform\PostgreSql\Statement\Expression\Subquery\Exists;
25use SqlSemantics\Platform\PostgreSql\Statement\Expression\Subquery\ScalarSubquery;
26
27/**
28 * Lowers `c_expr`, `columnref` and the indirection steps.
29 *
30 * Rule: PG-EXPRESSION-PRIMARY-001. Scope: `c_expr` (column references,
31 * constants, parameters, parenthesized expressions, CASE, function calls,
32 * scalar, EXISTS and ARRAY subqueries, array and row constructors,
33 * GROUPING), `columnref`, `indirection`, `opt_indirection`,
34 * `indirection_el` and `opt_slice_bound`. A dotted name followed only by
35 * field names is a `ColumnReference`; one that ends in `.*` is a
36 * `ColumnStar`; the steps from the first subscript on, or after a `.*`,
37 * make an `Indirection` of it, as PostgreSQL's `makeColumnRef` splits them.
38 * Function calls go to the invocation family, queries to the query family.
39 * Termination: the indirection list is flattened iteratively.
40 * Source: https://www.postgresql.org/docs/17/sql-expressions.html. Status: Implemented.
41 *
42 * @visibility SqlSemantics\Platform\PostgreSql\Lowering
43 */
44final class PrimaryRule
45{
46    /**
47     * @param Lowering $lowering The hub
48     */
49    public function __construct(private readonly Lowering $lowering)
50    {
51    }
52
53    /**
54     * Lowers a `c_expr`.
55     *
56     * @throws ImplementationGap When the production has no rule
57     */
58    public function lower(Form $form): Scalar
59    {
60        $queries = $this->lowering->queries;
61
62        return match ($form->signature) {
63            'c_expr: columnref' => $this->columnReference($form->node(0)),
64            'c_expr: AexprConst' => $this->lowering->literals->constant($form->node(0)),
65            'c_expr: PARAM opt_indirection' => $this->parameter($form),
66            'c_expr: ( a_expr ) opt_indirection' => $this->applied(new Grouped($this->lowering->expressions->expression($form->node(1))), $this->indirection($form->node(3))),
67            'c_expr: case_expr' => $this->lowering->expressions->caseExpression($form->node(0)),
68            'c_expr: func_expr' => $this->lowering->invocations->call($form->node(0)),
69            'c_expr: select_with_parens' => new ScalarSubquery($queries->query($form->node(0))),
70            'c_expr: select_with_parens indirection' => new Indirection(new ScalarSubquery($queries->query($form->node(0))), $this->indirection($form->node(1))),
71            'c_expr: EXISTS select_with_parens' => new Exists($queries->query($form->node(1))),
72            'c_expr: ARRAY select_with_parens' => new ArraySubquery($queries->query($form->node(1))),
73            'c_expr: ARRAY array_expr' => new ArrayConstructor($this->lowering->expressions->arrayLiteral($form->node(1))),
74            'c_expr: explicit_row', 'c_expr: implicit_row' => $this->lowering->expressions->rowConstructor($form->node(0)),
75            'c_expr: GROUPING ( expr_list )' => new GroupingFunction($this->lowering->expressions->expressions($form->node(2))),
76            default => throw ImplementationGap::production($form),
77        };
78    }
79
80    /**
81     * Lowers `c_expr: PARAM opt_indirection`.
82     */
83    public function parameter(Form $form): Scalar
84    {
85        return $this->applied($this->lowering->literals->parameter($form->token(0)), $this->indirection($form->node(1)));
86    }
87
88    /**
89     * Applies steps to a value: the value itself when there is none.
90     *
91     * @param list<IndirectionStep> $steps
92     */
93    public function applied(Scalar $base, array $steps): Scalar
94    {
95        return $steps === [] ? $base : new Indirection($base, $steps);
96    }
97
98    /**
99     * Lowers `columnref`.
100     *
101     * @throws ImplementationGap When the production has no rule
102     */
103    public function columnReference(Node $reference): Scalar
104    {
105        $form = $this->lowering->productions->form($reference);
106        $parts = [$this->lowering->names->name($form->node(0))];
107        $steps = match ($form->signature) {
108            'columnref: ColId' => [],
109            'columnref: ColId indirection' => $this->indirection($form->node(1)),
110            default => throw ImplementationGap::production($form),
111        };
112        $index = 0;
113        while ($index < count($steps) && $steps[$index] instanceof FieldSelection) {
114            $parts[] = $steps[$index]->name;
115            $index++;
116        }
117        $rest = array_slice($steps, $index);
118        if ($rest !== [] && $rest[0] instanceof AllFields) {
119            return $this->applied(new ColumnStar($parts), array_slice($rest, 1));
120        }
121
122        return $this->applied(new ColumnReference($parts), $rest);
123    }
124
125    /**
126     * Lowers `indirection` or `opt_indirection`; no step is an empty list.
127     *
128     * @return list<IndirectionStep>
129     *
130     * @throws ImplementationGap When the list or a step has no rule
131     */
132    public function indirection(Node $indirection): array
133    {
134        $spine = match ($indirection->name) {
135            'indirection' => ['indirection: indirection_el', 'indirection: indirection indirection_el'],
136            'opt_indirection' => ['opt_indirection:', 'opt_indirection: opt_indirection indirection_el'],
137            default => throw ImplementationGap::production($this->lowering->productions->form($indirection)),
138        };
139        $steps = [];
140        foreach ($this->lowering->items($indirection, ...$spine) as $element) {
141            $steps[] = $this->step($this->lowering->productions->form($element));
142        }
143
144        return $steps;
145    }
146
147    /**
148     * Lowers `indirection_el`.
149     *
150     * @throws ImplementationGap When the production has no rule
151     */
152    public function step(Form $form): IndirectionStep
153    {
154        return match ($form->signature) {
155            'indirection_el: . attr_name' => new FieldSelection($this->lowering->names->name($form->node(1))),
156            'indirection_el: . *' => new AllFields(),
157            'indirection_el: [ a_expr ]' => new Subscript($this->lowering->expressions->expression($form->node(1))),
158            'indirection_el: [ opt_slice_bound : opt_slice_bound ]' => new Slice($this->bound($form->node(1)), $this->bound($form->node(3))),
159            default => throw ImplementationGap::production($form),
160        };
161    }
162
163    /**
164     * Lowers `opt_slice_bound`; an omitted bound is null.
165     *
166     * @throws ImplementationGap When the production has no rule
167     */
168    public function bound(Node $bound): ?Scalar
169    {
170        $form = $this->lowering->productions->form($bound);
171
172        return match ($form->signature) {
173            'opt_slice_bound: a_expr' => $this->lowering->expressions->expression($form->node(0)),
174            'opt_slice_bound:' => null,
175            default => throw ImplementationGap::production($form),
176        };
177    }
178}
179