packages/sql-semantics-postgres/src/Rules/Routine/RelationTargets.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Rules\Routine;
6
7use SqlSemantics\Platform\PostgreSql\Model\Construction\Derivation;
8use SqlSemantics\Platform\PostgreSql\Model\Statement\Fact\RelationFact;
9use SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\Name;
10use SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\QualifiedName;
11use SqlSemantics\Platform\PostgreSql\Model\Statement\Reference\Column\MissingColumn;
12use SqlSemantics\Platform\PostgreSql\Model\Statement\Reference\Missing\IncompleteMembers;
13use SqlSemantics\Platform\PostgreSql\Model\Statement\Reference\Table\ConditionalTable;
14use SqlSemantics\Platform\PostgreSql\Model\Statement\Reference\Table\DeclaredTable;
15use SqlSemantics\Platform\PostgreSql\Model\Statement\Reference\Table\MissingTable;
16use SqlSemantics\Platform\PostgreSql\Model\Statement\Reference\Table\UndeclaredTable;
17use SqlSemantics\Platform\PostgreSql\Model\Statement\Shape\OutputSlot;
18use SqlSemantics\Platform\PostgreSql\Model\Statement\Shape\RowShape;
19use SqlSemantics\Platform\PostgreSql\Rules\Typing\DeclaredTyping;
20use SqlSemantics\Platform\PostgreSql\Statement\Name\DottedName;
21use SqlSemantics\Platform\PostgreSql\Statement\Name\ImproperName;
22use SqlSemantics\Platform\PostgreSql\Statement\Name\ObjectKind;
23use SqlSemantics\Platform\PostgreSql\Statement\Name\ObjectReference;
24use SqlSemantics\Platform\PostgreSql\Statement\Object\Problem\ObjectProblem;
25use SqlSemantics\Platform\PostgreSql\Statement\Object\Problem\ObjectProblemKind;
26use SqlSemantics\Platform\PostgreSql\Statement\Object\Reference\MemberName;
27use SqlSemantics\Platform\PostgreSql\Statement\Object\Reference\RelationTarget;
28
29/**
30 * Resolves the relations and columns a generic object command names.
31 *
32 * Rule: PG-OBJECT-RELATION-001. A table, view, materialized view or foreign
33 * table named by DROP, COMMENT, SECURITY LABEL or an ALTER command, the table
34 * a policy, rule, trigger or table constraint belongs to, and the table of a
35 * column are resolved along the search path (CORE-TABLE-LOOKUP-001) and
36 * recorded as the relation fact of the object reference: a declared relation
37 * with its columns, an undeclared one as an open shape naming the missing
38 * declaration, a missing or conflicting one as a diagnostic. A relation that
39 * IF EXISTS lets the server skip is recorded without a table and is no
40 * diagnostic. A dotted relation name of more than three parts is reported. A
41 * column is named by a dotted name whose last part is the column: one part is
42 * reported as unqualified, more than four parts as an improper relation name,
43 * and a column the declared complete relation certainly lacks is reported.
44 * Renaming a column to a name the relation certainly has is reported.
45 * Indexes and sequences are not declarations the context can hold and are not
46 * resolved. Terminates: one lookup per reference.
47 * Source: https://www.postgresql.org/docs/17/sql-comment.html, https://www.postgresql.org/docs/17/sql-droptable.html,
48 * https://www.postgresql.org/docs/17/sql-altertable.html, https://www.postgresql.org/docs/17/ddl-schemas.html#DDL-SCHEMAS-PATH.
49 * Status: Implemented.
50 *
51 * @visibility SqlSemantics\Platform\PostgreSql
52 */
53final class RelationTargets
54{
55    /**
56     * Resolves the relation an object reference names, if its kind names one, and records the fact; answers it.
57     */
58    public function resolve(ObjectKind $kind, ObjectReference $object, bool $ifExists, Derivation $derivation): ?RelationFact
59    {
60        $relation = in_array($kind->value, ObjectForms::RELATION, true);
61        if ($kind === ObjectKind::Column && $object instanceof DottedName) {
62            return $this->column($object, $derivation);
63        }
64        if ($relation && $object instanceof DottedName) {
65            return $this->dotted($object, $object, $ifExists, $derivation);
66        }
67        if ($relation && $object instanceof RelationTarget) {
68            return $this->record($object, $object->relation->name, $ifExists, $derivation);
69        }
70        if ($object instanceof MemberName && in_array($kind, [ObjectKind::Policy, ObjectKind::Rule, ObjectKind::Trigger, ObjectKind::Constraint], true)) {
71            return $object->owner instanceof QualifiedName ? $this->record($object, $object->owner, $ifExists, $derivation) : $this->dotted($object, $object->owner, $ifExists, $derivation);
72        }
73
74        return null;
75    }
76
77    /**
78     * Resolves a relation written as a dotted name and records the fact on the reference.
79     */
80    public function dotted(ObjectReference $reference, DottedName $name, bool $ifExists, Derivation $derivation): RelationFact
81    {
82        $qualified = $name->qualified();
83        if ($qualified === null) {
84            $derivation->report(new ImproperName($name));
85
86            return $derivation->target($reference, new RelationFact(new RowShape([])));
87        }
88
89        return $this->record($reference, $qualified, $ifExists, $derivation);
90    }
91
92    /**
93     * Resolves a relation name and records the fact on the reference.
94     */
95    public function record(ObjectReference $reference, QualifiedName $name, bool $ifExists, Derivation $derivation): RelationFact
96    {
97        $resolution = $derivation->table($name, $derivation->environment());
98        if ($ifExists && $resolution instanceof MissingTable) {
99            return $derivation->target($reference, new RelationFact(new RowShape([])));
100        }
101        $shape = new RowShape([]);
102        if ($resolution instanceof DeclaredTable) {
103            $slots = [];
104            foreach ($resolution->table->columns as $column) {
105                $slots[] = new OutputSlot($column->name, (new DeclaredTyping())->fact($column->type), $column->nullability, $column);
106            }
107            $shape = new RowShape($slots, $resolution->table->complete ? [] : [new IncompleteMembers($resolution->table)]);
108        } elseif ($resolution instanceof UndeclaredTable || $resolution instanceof ConditionalTable) {
109            $shape = new RowShape([], [$resolution->missing]);
110        }
111
112        return $derivation->target($reference, new RelationFact($shape, $resolution));
113    }
114
115    /**
116     * Resolves the table of a column written as a dotted name, records the fact on the name and reports a column the table certainly lacks.
117     */
118    public function column(DottedName $name, Derivation $derivation): RelationFact
119    {
120        $parts = $name->parts;
121        $count = count($parts);
122        if ($count < 2 || $count > 4) {
123            $derivation->report($count < 2 ? new ObjectProblem(ObjectProblemKind::UnqualifiedColumn) : new ObjectProblem(ObjectProblemKind::ImproperRelation, $this->spelled($parts)));
124
125            return $derivation->target($name, new RelationFact(new RowShape([])));
126        }
127        $table = (new DottedName(array_slice($parts, 0, $count - 1)))->qualified() ?? new QualifiedName($parts[0]);
128        $fact = $this->record($name, $table, false, $derivation);
129        $this->member($fact, $parts[$count - 1], $table, $derivation);
130
131        return $fact;
132    }
133
134    /**
135     * Reports a column that a declared complete relation certainly lacks.
136     */
137    public function member(RelationFact $fact, Name $column, QualifiedName $table, Derivation $derivation): void
138    {
139        if ($this->has($fact, $column, $derivation) === false) {
140            $derivation->report(new MissingColumn($column, $table));
141        }
142    }
143
144    /**
145     * Reports renaming a column to a name a declared relation certainly has.
146     */
147    public function renamed(RelationFact $fact, Name $column, Derivation $derivation): void
148    {
149        if ($this->has($fact, $column, $derivation) === true) {
150            $derivation->report(new ObjectProblem(ObjectProblemKind::ColumnExists, '"' . $column->value . '"'));
151        }
152    }
153
154    /**
155     * Tells whether the relation of a fact has a column of the name: true, false, or null when its declaration does not tell.
156     */
157    public function has(RelationFact $fact, Name $column, Derivation $derivation): ?bool
158    {
159        if (!$fact->table instanceof DeclaredTable) {
160            return null;
161        }
162        if ($fact->table->table->matchingColumns($column->value, $derivation->context->columnNames) !== []) {
163            return true;
164        }
165
166        return $fact->table->table->complete ? false : null;
167    }
168
169    /**
170     * Spells dotted name parts for a message.
171     *
172     * @param list<Name> $parts
173     */
174    public function spelled(array $parts): string
175    {
176        $values = [];
177        foreach ($parts as $part) {
178            $values[] = $part->value;
179        }
180
181        return implode('.', $values);
182    }
183}
184