packages/sql-semantics-postgres/src/Statement/Object/Rename.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Statement\Object;
6
7use SqlSemantics\Platform\PostgreSql\Model\Construction\Derivation;
8use SqlSemantics\Platform\PostgreSql\Model\Contract\NameUse;
9use SqlSemantics\Platform\PostgreSql\Model\Diagnostic\Check;
10use SqlSemantics\Platform\PostgreSql\Model\Rendering\Output;
11use SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\Name;
12use SqlSemantics\Platform\PostgreSql\Model\Statement\Snapshot;
13use SqlSemantics\Platform\PostgreSql\Model\Statement\Statement;
14use SqlSemantics\Platform\PostgreSql\Rules\Routine\ObjectFacts;
15use SqlSemantics\Platform\PostgreSql\Rules\Routine\ObjectForms;
16use SqlSemantics\Platform\PostgreSql\Rules\Routine\ObjectSpelling;
17use SqlSemantics\Platform\PostgreSql\Rules\Routine\RelationTargets;
18use SqlSemantics\Platform\PostgreSql\Rules\Table\RelationKinds;
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\Option\DropBehavior;
23
24/**
25 * `ALTER kind object RENAME [part name] TO new_name`: renames an object or one of its columns, constraints or attributes.
26 *
27 * Mirrors PostgreSQL's `RenameStmt` (`renameType`, `relationType`, object,
28 * `subname`, `newname`, `behavior`, `missing_ok`). How the object is named
29 * depends on the kind (PG-OBJECT-FORM-001). A renamed relation is resolved;
30 * renaming a column the declared relation lacks, or to a name it has, is
31 * reported. Renaming changes no declaration of the context.
32 * Source: https://www.postgresql.org/docs/17/sql-altertable.html, https://www.postgresql.org/docs/17/sql-alterfunction.html.
33 *
34 * @visibility public
35 * @example Reading a column rename
36 *     $operation = (new \SqlSemantics\Platform\PostgreSql\Semantics())->analyze('ALTER TABLE t RENAME COLUMN a TO b');
37 *     [$operation->statement->member?->name->value, $operation->statement->newName->value] // => ['a', 'b']
38 */
39final class Rename implements Statement
40{
41    use Snapshot;
42
43    /**
44     * @param ObjectKind $kind The kind of the object
45     * @param ObjectReference $object The object, named as ALTER ... RENAME names objects of the kind
46     * @param Name $newName The new name
47     * @param RenamedMember|null $member The renamed column, constraint or attribute, if the object itself is not renamed
48     * @param bool $ifExists Whether IF EXISTS is written
49     * @param DropBehavior|null $behavior CASCADE or RESTRICT, written only when renaming an attribute
50     * @param RoleWord|null $roleWord The keyword naming a role; given exactly for roles
51     */
52    public function __construct(
53        public readonly ObjectKind $kind,
54        public readonly ObjectReference $object,
55        public readonly Name $newName,
56        public readonly ?RenamedMember $member = null,
57        public readonly bool $ifExists = false,
58        public readonly ?DropBehavior $behavior = null,
59        public readonly ?RoleWord $roleWord = null,
60    ) {
61        $forms = new ObjectForms();
62        Check::input(in_array($forms->form($object), $forms->altered($kind, 'rename'), true), 'ALTER ... RENAME names the object as the grammar names objects of its kind.');
63        Check::input(($kind === ObjectKind::Role) === ($roleWord !== null), 'A role is renamed with ROLE, USER or GROUP; nothing else is.');
64        Check::input(!$ifExists || $kind === ObjectKind::Policy || in_array($kind->value, ObjectForms::ALTERED_RELATION, true), 'ALTER ... RENAME accepts IF EXISTS for policies and relations only.');
65        Check::input($member === null || in_array($kind->value, match ($member->part) {
66            RenamedPart::Column => ['TABLE', 'VIEW', 'MATERIALIZED VIEW', 'FOREIGN TABLE'],
67            RenamedPart::Constraint => ['TABLE', 'DOMAIN'],
68            RenamedPart::Attribute => ['TYPE'],
69        }, true), 'The renamed part belongs to the kind of the object.');
70        Check::input(!$ifExists || $member?->part !== RenamedPart::Constraint || $kind === ObjectKind::Table, 'A domain constraint is renamed without IF EXISTS.');
71        Check::input($behavior === null || $member?->part === RenamedPart::Attribute, 'CASCADE or RESTRICT is written only when renaming an attribute.');
72    }
73
74    /**
75     * Derives the object and reports a renamed column the declared relation lacks or a new column name it has.
76     */
77    public function deriveStatement(Derivation $derivation): void
78    {
79        [$fact] = (new ObjectFacts())->derive($this->kind, [$this->object], $this->ifExists, $derivation);
80        (new RelationKinds())->renamed($derivation, $this->kind, $this->object, true, $this->member !== null && $this->member->part !== RenamedPart::Attribute);
81        if ($fact !== null && $this->member?->part === RenamedPart::Column && $this->object instanceof RelationTarget) {
82            $targets = new RelationTargets();
83            $targets->member($fact, $this->member->name, $this->object->relation->name, $derivation);
84            $targets->renamed($fact, $this->newName, $derivation);
85        }
86    }
87
88    /**
89     * Writes the statement.
90     */
91    public function render(Output $out): void
92    {
93        $out->keyword('ALTER');
94        if ($this->roleWord !== null) {
95            $out->keyword($this->roleWord->value);
96        } else {
97            (new ObjectSpelling())->kind($out, $this->kind);
98        }
99        if ($this->ifExists) {
100            $out->keyword('IF', 'EXISTS');
101        }
102        $out->node($this->object)->keyword('RENAME')->node($this->member)->keyword('TO')->name($this->newName, NameUse::Column);
103        if ($this->behavior !== null) {
104            $out->keyword($this->behavior->value);
105        }
106    }
107}
108