packages/sql-semantics-mysql/src/Statement/Alter/AlterTable.php
1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Statement\Alter;
6
7use SqlSemantics\Platform\MySql\Model\Construction\Derivation;
8use SqlSemantics\Platform\MySql\Model\Contract\NameUse;
9use SqlSemantics\Platform\MySql\Model\Diagnostic\Check;
10use SqlSemantics\Platform\MySql\Model\Rendering\Output;
11use SqlSemantics\Platform\MySql\Model\Resolution\Environment;
12use SqlSemantics\Platform\MySql\Model\Resolution\VisibleRelation;
13use SqlSemantics\Platform\MySql\Model\Statement\Declaration\RelationKind;
14use SqlSemantics\Platform\MySql\Model\Statement\Fact\RelationFact;
15use SqlSemantics\Platform\MySql\Model\Statement\Identifier\QualifiedName;
16use SqlSemantics\Platform\MySql\Model\Statement\Relation;
17use SqlSemantics\Platform\MySql\Model\Statement\Snapshot;
18use SqlSemantics\Platform\MySql\Model\Statement\Statement;
19use SqlSemantics\Platform\MySql\Rules\TableChange\ColumnChanges;
20use SqlSemantics\Platform\MySql\Rules\TableChange\Targets;
21use SqlSemantics\Platform\MySql\Rules\TableDefinition\RelationKinds;
22use SqlSemantics\Platform\MySql\Statement\Alter\Modifier\AlterModifier;
23use SqlSemantics\Platform\MySql\Statement\Alter\Partition\StandaloneCommand;
24use SqlSemantics\Platform\MySql\Statement\Alter\Partition\TrailingCommand;
25
26/**
27 * `ALTER [IGNORE] TABLE t action, …`: a request to change the structure of a table.
28 *
29 * Mirrors PT_alter_table_stmt and PT_alter_table_standalone_stmt. Rule:
30 * MYSQL-ALTER-TABLE-001. The actions are kept in the order written,
31 * modifiers (ALGORITHM, LOCK, VALIDATION) among them; a standalone action
32 * (a partition or tablespace operation) is the last one and only modifiers
33 * precede it; `PARTITION BY` and `REMOVE PARTITIONING` are the last one and
34 * follow the others without a comma. The table resolves by
35 * MYSQL-CHANGE-TARGET-001; a declared view is refused (MYSQL-RELATION-KIND-001). The statement node is the relation occurrence the
36 * expressions of the actions see: its relation fact holds the resolution of
37 * the table and the row shape of the visible columns the table has after
38 * the column actions; its invisible columns are found by name only
39 * (MYSQL-COLUMN-CHANGES-001), which also reports a changed, dropped,
40 * renamed or altered column the completely known table does not have and a
41 * column name the table would have twice. The statement changes no
42 * declaration and provides none. IGNORE exists in 5.6 only.
43 * Source: https://dev.mysql.com/doc/refman/8.4/en/alter-table.html,
44 * https://dev.mysql.com/doc/refman/5.6/en/alter-table.html.
45 * Status: Implemented.
46 *
47 * @visibility public
48 * @example Reading the actions of a table change
49 * $semantics = new \SqlSemantics\Platform\MySql\Semantics();
50 * $table = $semantics->analyze('CREATE TABLE t (a INT)');
51 * $semantics->analyze('ALTER TABLE t DROP COLUMN b, ALGORITHM = INPLACE', [$table]) // throws \SqlSemantics\Platform\MySql\Model\Diagnostic\SemanticException: Column b does not exist in the table.
52 */
53final class AlterTable implements Statement, Relation
54{
55 use Snapshot;
56
57 /**
58 * @var list<AlterCommand> The actions in the order written
59 */
60 public readonly array $commands;
61
62 /**
63 * @param QualifiedName $table The table with its optional database
64 * @param list<AlterCommand> $commands The actions in the order written
65 * @param bool $ignore Whether IGNORE is written (5.6)
66 */
67 public function __construct(public readonly QualifiedName $table, array $commands, public readonly bool $ignore = false)
68 {
69 Check::input($table->catalog === null, 'A table is qualified by at most a database.');
70 $this->commands = Check::listOf($commands, AlterCommand::class, 'ALTER TABLE holds a list of actions.');
71 $last = count($this->commands) - 1;
72 foreach ($this->commands as $index => $command) {
73 Check::input(!$command instanceof TrailingCommand || $index === $last, 'PARTITION BY and REMOVE PARTITIONING are the last action.');
74 Check::input(!$command instanceof StandaloneCommand || $index === $last, 'A partition or tablespace operation is the last action.');
75 Check::input(
76 $index === $last || $command instanceof AlterModifier || !$this->commands[$last] instanceof StandaloneCommand,
77 'Only modifiers precede a partition or tablespace operation.',
78 );
79 }
80 }
81
82 /**
83 * Derives the table and every action in the scope of the table as the statement leaves it.
84 */
85 public function deriveStatement(Derivation $derivation): void
86 {
87 $original = (new Targets())->target($derivation, $this->table);
88 (new RelationKinds())->require($derivation, $this->table, $original->table, RelationKind::BaseTable);
89 $changes = new ColumnChanges();
90 $fact = $derivation->target($this, new RelationFact($changes->apply($original, $this->commands, $derivation, true), $original->table));
91 $scope = new Environment($derivation->context, null, [new VisibleRelation($this, $fact->shape, null, $this->table, [], $changes->implicit())]);
92 foreach ($this->commands as $command) {
93 $command->deriveCommand($derivation, $scope);
94 }
95 }
96
97 /**
98 * Resolves the table and answers the row shape of its visible columns after the column actions.
99 */
100 public function deriveRelation(Derivation $derivation, Environment $environment): RelationFact
101 {
102 $original = (new Targets())->target($derivation, $this->table);
103
104 return new RelationFact((new ColumnChanges())->apply($original, $this->commands, $derivation, false), $original->table);
105 }
106
107 /**
108 * Writes the request.
109 */
110 public function render(Output $out): void
111 {
112 $out->keyword('ALTER');
113 if ($this->ignore) {
114 $out->keyword('IGNORE');
115 }
116 $out->keyword('TABLE');
117 if ($this->table->schema !== null) {
118 $out->name($this->table->schema, NameUse::Qualifier)->symbol('.');
119 }
120 $out->name($this->table->name, NameUse::Relation);
121 foreach ($this->commands as $index => $command) {
122 if ($index > 0 && !$command instanceof TrailingCommand) {
123 $out->symbol(',');
124 }
125 $out->node($command);
126 }
127 }
128}
129