packages/sql-semantics-postgres/src/Rules/Table/RelationKinds.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Rules\Table;
6
7use SqlSemantics\Platform\PostgreSql\Model\Construction\Derivation;
8use SqlSemantics\Platform\PostgreSql\Model\Contract\GrammarRelease;
9use SqlSemantics\Platform\PostgreSql\Model\Resolution\Environment;
10use SqlSemantics\Platform\PostgreSql\Model\Statement\Declaration\RelationKind;
11use SqlSemantics\Platform\PostgreSql\Model\Statement\Fact\RelationFact;
12use SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\Name;
13use SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\QualifiedName;
14use SqlSemantics\Platform\PostgreSql\Model\Statement\Reference\Table\DeclaredTable;
15use SqlSemantics\Platform\PostgreSql\Statement\Clause;
16use SqlSemantics\Platform\PostgreSql\Statement\Constraint\Constraint;
17use SqlSemantics\Platform\PostgreSql\Statement\Constraint\ConstraintKind;
18use SqlSemantics\Platform\PostgreSql\Statement\Name\DottedName;
19use SqlSemantics\Platform\PostgreSql\Statement\Name\ObjectKind;
20use SqlSemantics\Platform\PostgreSql\Statement\Name\ObjectReference;
21use SqlSemantics\Platform\PostgreSql\Statement\Object\Reference\RelationTarget;
22use SqlSemantics\Platform\PostgreSql\Statement\Table\Element\ColumnDefinition;
23use SqlSemantics\Platform\PostgreSql\Statement\Table\Element\ColumnOptions;
24use SqlSemantics\Platform\PostgreSql\Statement\Table\Problem\KindProblem;
25use SqlSemantics\Platform\PostgreSql\Statement\Table\Problem\KindRule;
26use SqlSemantics\Platform\PostgreSql\Statement\Table\Trigger\TriggerTiming;
27
28/**
29 * Checks the kind of the relation a command names against the kinds the command accepts.
30 *
31 * Rule: PG-RELATION-KIND-001. A relation declaration states whether it is a
32 * base table (a partitioned table included), a view, a materialized view, a
33 * foreign table or a sequence. A command that names a relation of a kind it
34 * does not accept is the server's error, reported in its words: DROP, COMMENT
35 * and ALTER EXTENSION written with one kind accept only that kind (DROP TABLE
36 * of a view: `"v" is not a table`; nothing the context declares is an
37 * index); ALTER, RENAME and SET SCHEMA written with VIEW, MATERIALIZED VIEW,
38 * FOREIGN TABLE, SEQUENCE or INDEX accept only that kind, while ALTER TABLE
39 * accepts every kind and ALTER INDEX ... RENAME any relation
40 * (RangeVarCallbackForAlterRelation); a column or constraint of a sequence
41 * cannot be renamed (`cannot rename columns of relation`). The commands with their own lists of
42 * accepted kinds apply them where they resolve the relation. A relation the
43 * context does not declare, or declares without stating a kind it can know,
44 * is never reported.
45 * Source: https://www.postgresql.org/docs/17/sql-droptable.html,
46 * https://www.postgresql.org/docs/17/sql-alterview.html, `tablecmds.c` and
47 * `objectaddress.c` (get_relation_by_qualified_name). Termination: one lookup
48 * per relation. Status: Implemented.
49 *
50 * @visibility SqlSemantics\Platform\PostgreSql
51 */
52final class RelationKinds
53{
54    /**
55     * The kinds of relation whose columns and constraints can be renamed (renameatt_check).
56     */
57    public const COLUMNED = [RelationKind::BaseTable, RelationKind::View, RelationKind::MaterializedView, RelationKind::ForeignTable];
58
59    /**
60     * Answers the kind the declaration a relation fact resolved to states, or null when it resolved to none.
61     */
62    public function of(RelationFact $fact): ?RelationKind
63    {
64        return $fact->table instanceof DeclaredTable ? $fact->table->table->kind : null;
65    }
66
67    /**
68     * Answers the kind of the relation a name resolves to, or null when it resolves to no declaration.
69     */
70    public function declared(Derivation $derivation, QualifiedName $name, ?Environment $environment = null): ?RelationKind
71    {
72        $resolution = $derivation->table($name, $environment ?? $derivation->environment());
73
74        return $resolution instanceof DeclaredTable ? $resolution->table->kind : null;
75    }
76
77    /**
78     * Reports the rule when the declared kind is known and is not one of the accepted kinds; tells whether it reported.
79     *
80     * @param list<RelationKind> $accepted
81     */
82    public function require(Derivation $derivation, ?RelationKind $kind, Name $relation, array $accepted, KindRule $rule): bool
83    {
84        if ($kind === null || in_array($kind, $accepted, true)) {
85            return false;
86        }
87        $derivation->report(new KindProblem($rule, $relation));
88
89        return true;
90    }
91
92    /**
93     * Checks the relations of a command written with one relation kind that accepts only that kind: DROP, COMMENT and ALTER EXTENSION.
94     *
95     * @param list<ObjectReference> $objects
96     */
97    public function named(Derivation $derivation, ObjectKind $kind, array $objects): void
98    {
99        $expected = $this->expected($kind);
100        if ($expected === null) {
101            return;
102        }
103        foreach ($objects as $object) {
104            $name = $this->name($object);
105            if ($name !== null) {
106                $this->require($derivation, $this->declared($derivation, $name), $name->name, $expected[0] === null ? [] : [$expected[0]], $expected[1]);
107            }
108        }
109    }
110
111    /**
112     * Checks the relation of an ALTER, RENAME or SET SCHEMA command written with a relation kind; tells whether it reported.
113     */
114    public function altered(Derivation $derivation, ObjectKind $kind, QualifiedName $name, bool $rename): bool
115    {
116        $expected = $kind === ObjectKind::Table || ($kind === ObjectKind::Index && $rename) ? null : $this->expected($kind);
117
118        return $expected !== null && $this->require($derivation, $this->declared($derivation, $name), $name->name, $expected[0] === null ? [] : [$expected[0]], $expected[1]);
119    }
120
121    /**
122     * Checks the relation of ALTER ... RENAME (`$rename`) or SET SCHEMA written with a relation kind; a renamed column or constraint needs a relation that has columns.
123     */
124    public function renamed(Derivation $derivation, ObjectKind $kind, ObjectReference $object, bool $rename, bool $member): void
125    {
126        $name = $this->expected($kind) === null ? null : $this->name($object);
127        if ($name === null) {
128            return;
129        }
130        if ($member) {
131            $this->require($derivation, $this->declared($derivation, $name), $name->name, self::COLUMNED, KindRule::RenameColumns);
132        } else {
133            $this->altered($derivation, $kind, $name, $rename);
134        }
135    }
136
137    /**
138     * Reports the target of INSERT, UPDATE, DELETE or MERGE when its declared kind cannot be changed.
139     *
140     * A sequence or a materialized view cannot be changed (CheckValidResultRel);
141     * whether a view or a foreign table can depends on its definition, its
142     * triggers or its wrapper. MERGE accepts only a table and, from
143     * PostgreSQL 17, a view (transformMergeStmt).
144     */
145    public function modified(Derivation $derivation, ?RelationKind $kind, Name $relation, bool $merge): void
146    {
147        if ($merge) {
148            $view = $derivation->context->profile->grammar === GrammarRelease::PostgreSql166 ? [] : [RelationKind::View];
149            $this->require($derivation, $kind, $relation, [RelationKind::BaseTable, ...$view], KindRule::Merge);
150        } elseif ($kind === RelationKind::Sequence || $kind === RelationKind::MaterializedView) {
151            $derivation->report(new KindProblem($kind === RelationKind::Sequence ? KindRule::ChangeSequence : KindRule::ChangeMaterializedView, $relation));
152        }
153    }
154
155    /**
156     * Reports the constraints a foreign table cannot have among table elements, column qualifiers included.
157     *
158     * A foreign table has no primary key, unique, exclusion or foreign key
159     * constraint (transformTableConstraint, transformColumnDefinition).
160     *
161     * @param list<Clause> $elements
162     */
163    public function foreign(Derivation $derivation, array $elements): void
164    {
165        foreach ($elements as $element) {
166            $members = $element instanceof ColumnDefinition || $element instanceof ColumnOptions ? $element->qualifiers : [$element];
167            foreach ($members as $member) {
168                $rule = $member instanceof Constraint ? match ($member->kind()) {
169                    ConstraintKind::PrimaryKey => KindRule::ForeignPrimaryKey,
170                    ConstraintKind::Unique => KindRule::ForeignUnique,
171                    ConstraintKind::Exclusion => KindRule::ForeignExclusion,
172                    ConstraintKind::ForeignKey => KindRule::ForeignForeignKey,
173                    ConstraintKind::Null, ConstraintKind::NotNull, ConstraintKind::Default, ConstraintKind::Identity, ConstraintKind::Generated, ConstraintKind::Check => null,
174                } : null;
175                if ($rule !== null) {
176                    $derivation->report(new KindProblem($rule, null));
177                }
178            }
179        }
180    }
181
182    /**
183     * Reports a trigger the kind of its relation cannot have (CreateTriggerFiringOn).
184     *
185     * A table or a foreign table has no INSTEAD OF trigger, a view no row
186     * trigger other than INSTEAD OF and no TRUNCATE trigger, a foreign table no
187     * constraint trigger, neither a view nor a foreign table a trigger with
188     * transition tables; a materialized view and a sequence have no trigger.
189     */
190    public function triggered(Derivation $derivation, ?RelationKind $kind, Name $relation, TriggerTiming $timing, bool $row, bool $truncate, bool $constraint, bool $transitions = false): void
191    {
192        $rule = match ($kind) {
193            RelationKind::BaseTable => $timing === TriggerTiming::InsteadOf ? KindRule::TriggerOnTable : null,
194            RelationKind::View => ($timing !== TriggerTiming::InsteadOf && $row) || $truncate || $transitions ? KindRule::TriggerOnView : null,
195            RelationKind::ForeignTable => $timing === TriggerTiming::InsteadOf || $constraint || $transitions ? KindRule::TriggerOnForeignTable : null,
196            RelationKind::MaterializedView, RelationKind::Sequence => KindRule::TriggersOnRelation,
197            null => null,
198        };
199        if ($rule !== null) {
200            $derivation->report(new KindProblem($rule, $relation));
201        }
202    }
203
204    /**
205     * Answers the kind a relation kind keyword accepts and the rule a relation of another kind breaks; null for the kinds that name no relation.
206     *
207     * @return array{RelationKind|null, KindRule}|null
208     */
209    public function expected(ObjectKind $kind): ?array
210    {
211        return match ($kind) {
212            ObjectKind::Table => [RelationKind::BaseTable, KindRule::NotTable],
213            ObjectKind::View => [RelationKind::View, KindRule::NotView],
214            ObjectKind::MaterializedView => [RelationKind::MaterializedView, KindRule::NotMaterializedView],
215            ObjectKind::ForeignTable => [RelationKind::ForeignTable, KindRule::NotForeignTable],
216            ObjectKind::Sequence => [RelationKind::Sequence, KindRule::NotSequence],
217            ObjectKind::Index => [null, KindRule::NotIndex],
218            default => null,
219        };
220    }
221
222    /**
223     * Answers the relation name an object reference writes, or null when it writes none.
224     */
225    public function name(ObjectReference $object): ?QualifiedName
226    {
227        return match (true) {
228            $object instanceof RelationTarget => $object->relation->name,
229            $object instanceof DottedName => $object->qualified(),
230            default => null,
231        };
232    }
233}
234