packages/sql-semantics-postgres/src/Rules/Expression/WholeRows.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Rules\Expression;
6
7use SqlSemantics\Platform\PostgreSql\Model\Construction\Derivation;
8use SqlSemantics\Platform\PostgreSql\Model\Resolution\Environment;
9use SqlSemantics\Platform\PostgreSql\Model\Resolution\VisibleRelation;
10use SqlSemantics\Platform\PostgreSql\Model\Statement\Fact\ScalarFact;
11use SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\Name;
12use SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\QualifiedName;
13use SqlSemantics\Platform\PostgreSql\Model\Statement\Reference\Table\MissingTable;
14use SqlSemantics\Platform\PostgreSql\Model\Statement\Type\Dependent;
15use SqlSemantics\Platform\PostgreSql\Model\Statement\Type\Invalid;
16use SqlSemantics\Platform\PostgreSql\Model\Statement\Type\Known;
17use SqlSemantics\Platform\PostgreSql\Model\Statement\Type\Nullability;
18use SqlSemantics\Platform\PostgreSql\Rules\Resolution\LateralReach;
19use SqlSemantics\Platform\PostgreSql\Statement\Expression\Constructor\Composite;
20use SqlSemantics\Platform\PostgreSql\Statement\Expression\Problem\AmbiguousRelation;
21use SqlSemantics\Platform\PostgreSql\Statement\Name\DottedName;
22use SqlSemantics\Platform\PostgreSql\Statement\Name\ImproperName;
23
24/**
25 * Resolves a relation name used as a value: the whole row of a visible relation.
26 *
27 * Rule: PG-WHOLE-ROW-001. The name is matched against the relations visible
28 * at the position and then at the enclosing query levels, nearest first: an
29 * alias by its name alone, an unaliased relation by its name and, when
30 * written, its schema. The nearest level with a match decides; two matches
31 * there are ambiguous; a relation a lateral item must not reference is
32 * reported (PG-LATERAL-JOIN-001). Facts: the row type of the relation, whose fields are
33 * its columns, or a dependence on the missing inputs of an open shape; a
34 * row of an outer join's NULL side is NULL, so the value can be NULL.
35 * Termination: the chain of levels and each relation list are finite.
36 * Source: https://www.postgresql.org/docs/17/rowtypes.html#ROWTYPES-USAGE,
37 * https://www.postgresql.org/docs/17/sql-expressions.html#SQL-EXPRESSIONS-COLUMN-REFS. Status: Implemented.
38 *
39 * @visibility SqlSemantics
40 */
41final class WholeRows
42{
43    /**
44     * Derives the whole row a `name.*` reference stands for; a relation that is not visible is reported.
45     *
46     * @param non-empty-list<Name> $qualifiers
47     */
48    public function star(Derivation $derivation, Environment $environment, array $qualifiers): ScalarFact
49    {
50        $name = (new DottedName($qualifiers))->qualified();
51        if ($name === null) {
52            $problem = new ImproperName(new DottedName($qualifiers));
53            $derivation->report($problem);
54
55            return new ScalarFact(new Invalid($problem), Nullability::Dependent);
56        }
57        $fact = $this->row($derivation, $environment, $name);
58        if ($fact !== null) {
59            return $fact;
60        }
61        $problem = new MissingTable($name);
62        $derivation->report($problem);
63
64        return new ScalarFact(new Invalid($problem), Nullability::Dependent);
65    }
66
67    /**
68     * Derives the whole row of the visible relation a name matches, or answers null when none matches.
69     */
70    public function row(Derivation $derivation, Environment $environment, QualifiedName $name): ?ScalarFact
71    {
72        $found = $this->find($environment, $name);
73        if ($found === []) {
74            return null;
75        }
76        if (count($found) > 1) {
77            $problem = new AmbiguousRelation($name->name->value);
78            $derivation->report($problem);
79
80            return new ScalarFact(new Invalid($problem), Nullability::Dependent);
81        }
82        $relation = $found[0];
83        $reach = new LateralReach();
84        if ($reach->barred($relation)) {
85            return $reach->report($derivation, $relation);
86        }
87        if (!$relation->shape->complete()) {
88            return new ScalarFact(new Dependent($relation->shape->missing), Nullability::Dependent);
89        }
90
91        return new ScalarFact(new Known(new Composite($relation->shape->slots, $relation->alias ?? $relation->name?->name)), Nullability::Nullable);
92    }
93
94    /**
95     * Answers the relations of the nearest level that the name matches.
96     *
97     * @return list<VisibleRelation>
98     */
99    public function find(Environment $environment, QualifiedName $name): array
100    {
101        $names = $environment->context->relationNames;
102        for ($scope = $environment; $scope !== null; $scope = $scope->outer) {
103            $found = [];
104            foreach ($scope->relations as $relation) {
105                if ($relation->alias !== null) {
106                    $match = $name->schema === null && $names->equal($relation->alias->value, $name->name->value);
107                } else {
108                    $match = $relation->name !== null && $names->equal($relation->name->name->value, $name->name->value)
109                        && ($name->schema === null || $relation->name->schema === null || $names->equal($relation->name->schema->value, $name->schema->value));
110                }
111                if ($match) {
112                    $found[] = $relation;
113                }
114            }
115            if ($found !== []) {
116                return $found;
117            }
118        }
119
120        return [];
121    }
122}
123