packages/sql-semantics-mysql/src/Statement/Table/CreateTable.php
1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Statement\Table;
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\Statement\Fact\RelationFact;
13use SqlSemantics\Platform\MySql\Model\Statement\Identifier\QualifiedName;
14use SqlSemantics\Platform\MySql\Model\Statement\Reference\Table\DeclaredTable;
15use SqlSemantics\Platform\MySql\Model\Statement\Relation;
16use SqlSemantics\Platform\MySql\Model\Statement\Snapshot;
17use SqlSemantics\Platform\MySql\Model\Statement\Statement;
18use SqlSemantics\Platform\MySql\Rules\TableDefinition\ElementFacts;
19use SqlSemantics\Platform\MySql\Rules\TableDefinition\EnclosedQuery;
20use SqlSemantics\Platform\MySql\Rules\TableDefinition\TableDeclaration;
21use SqlSemantics\Platform\MySql\Rules\TableDefinition\TableProblems;
22use SqlSemantics\Platform\MySql\Rules\TableDefinition\TableTargets;
23use SqlSemantics\Platform\MySql\Statement\Partition\Partitioning;
24
25/**
26 * A request to create a table from column, index and constraint definitions, a query, or both.
27 *
28 * Rule: MYSQL-CREATE-TABLE-001. The statement provides one table declaration
29 * (MYSQL-TABLE-DECLARATION-001); it executes nothing and changes no context,
30 * and neither TEMPORARY nor IF NOT EXISTS changes what it declares (a
31 * temporary table hides a permanent table of the same name for the session
32 * only). The statement node is the one relation occurrence of the new
33 * table: its relation fact resolves to the declaration the statement
34 * provides, the same object, and holds its row shape. The query of CREATE
35 * TABLE ... SELECT is derived as an independent query that does not see the
36 * new table. DEFAULT expressions, generated column expressions, CHECK
37 * conditions, functional key parts and the partitioning are derived in the
38 * scope of MYSQL-DEFINITION-SCOPE-001, whose only visible relation is that
39 * occurrence. MySQL 5.x accepts TEMPORARY written more than once, and a
40 * PARTITION BY clause inside the parenthesis that opens the query
41 * (MYSQL-ENCLOSED-PARTITIONING-001); both are kept so the statement is
42 * written back as it was. Diagnostics:
43 * MYSQL-TABLE-PROBLEMS-001.
44 * Source: https://dev.mysql.com/doc/refman/8.4/en/create-table.html,
45 * https://dev.mysql.com/doc/refman/8.4/en/create-table-select.html,
46 * https://dev.mysql.com/doc/refman/8.4/en/create-temporary-table.html. Status: Implemented.
47 *
48 * @visibility public
49 * @example Providing a declaration to a context
50 * $create = (new \SqlSemantics\Platform\MySql\Semantics())->analyze('CREATE TABLE t (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20), note TEXT NULL)');
51 * $table = $create->declarations()[0];
52 * [count($table->columns), $table->columns[0]->nullability, $table->columns[2]->nullability] // => [3, \SqlSemantics\Platform\MySql\Model\Statement\Type\Nullability::NotNull, \SqlSemantics\Platform\MySql\Model\Statement\Type\Nullability::Nullable]
53 * @example The relation fact of the statement resolves to the declaration it provides
54 * $create = (new \SqlSemantics\Platform\MySql\Semantics())->analyze('CREATE TABLE t (a INT, CHECK (a > 0))');
55 * $create->facts->scalar($create->statement->elements[1]->condition->left)->resolution->slot->column === $create->declarations()[0]->columns[0] // => true
56 */
57final class CreateTable implements Statement, Relation
58{
59 use Snapshot;
60
61 /**
62 * @var list<TableElement> The column, index and constraint definitions in order; empty when no parenthesized list is written
63 */
64 public readonly array $elements;
65
66 /**
67 * @var list<TableOption> The table options in order
68 */
69 public readonly array $options;
70
71 /**
72 * @param QualifiedName $name The table name
73 * @param list<TableElement> $elements The column, index and constraint definitions in order; empty when no list is written
74 * @param list<TableOption> $options The table options in order
75 * @param Partitioning|null $partitioning The PARTITION BY clause
76 * @param TableQuery|null $query The query whose rows fill the table
77 * @param int $temporaryWords How many times TEMPORARY is written; MySQL 8.0 and later accept it once
78 * @param bool $ifNotExists Whether IF NOT EXISTS is written
79 * @param bool $enclosed Whether the partitioning is written inside the parenthesis that opens the query (MySQL 5.x)
80 */
81 public function __construct(
82 public readonly QualifiedName $name,
83 array $elements = [],
84 array $options = [],
85 public readonly ?Partitioning $partitioning = null,
86 public readonly ?TableQuery $query = null,
87 public readonly int $temporaryWords = 0,
88 public readonly bool $ifNotExists = false,
89 public readonly bool $enclosed = false,
90 ) {
91 Check::input($name->catalog === null, 'A table name has at most a database qualifier.');
92 Check::input($temporaryWords >= 0, 'TEMPORARY is written a non-negative number of times.');
93 $this->elements = Check::listOf($elements, TableElement::class, 'Table elements are an ordered list of table elements.');
94 $this->options = Check::listOf($options, TableOption::class, 'Table options are an ordered list of table options.');
95 Check::input(
96 !$enclosed || ($this->elements === [] && $this->options === [] && $partitioning !== null && $query !== null && $query->duplicate === null && (new EnclosedQuery())->accepts($query->query)),
97 'Only a partitioning and a query that starts with a parenthesized query are written enclosed.',
98 );
99 }
100
101 /**
102 * Tells whether the table is TEMPORARY.
103 */
104 public function temporary(): bool
105 {
106 return $this->temporaryWords > 0;
107 }
108
109 /**
110 * Derives the definition: its declaration, its problems and the expressions inside it.
111 */
112 public function deriveStatement(Derivation $derivation): void
113 {
114 $fact = $derivation->relation($this, $derivation->environment());
115 $table = $fact->table instanceof DeclaredTable ? $fact->table->table : null;
116 $targets = new TableTargets();
117 $scope = $targets->scope($derivation, $this, $this->name, $fact->shape, $table === null ? [] : $targets->implicit($table));
118 $facts = new ElementFacts();
119 foreach ($this->elements as $element) {
120 $facts->element($element, $derivation, $scope, $table, $this->name);
121 }
122 $this->partitioning?->derivePartitioning($derivation, $scope);
123 }
124
125 /**
126 * Derives the query, provides the declaration and reports the problems of the definition; the fact resolves to that declaration.
127 */
128 public function deriveRelation(Derivation $derivation, Environment $environment): RelationFact
129 {
130 $output = $this->query === null ? null : $derivation->query($this->query->query, $derivation->environment());
131 $table = (new TableDeclaration())->table($this, $output, $derivation);
132 $derivation->declare($table);
133 $problems = new TableProblems();
134 $problems->report($this, $table, $derivation);
135 if ($output !== null) {
136 $problems->selected($this, $output, $derivation);
137 }
138
139 return new RelationFact((new TableTargets())->shape($table), new DeclaredTable($table));
140 }
141
142 /**
143 * Writes the definition.
144 */
145 public function render(Output $out): void
146 {
147 $out->keyword('CREATE');
148 for ($word = 0; $word < $this->temporaryWords; $word++) {
149 $out->keyword('TEMPORARY');
150 }
151 $out->keyword('TABLE');
152 if ($this->ifNotExists) {
153 $out->keyword('IF', 'NOT', 'EXISTS');
154 }
155 if ($this->name->schema !== null) {
156 $out->name($this->name->schema, NameUse::Qualifier)->symbol('.');
157 }
158 $out->name($this->name->name, NameUse::Relation);
159 if ($this->enclosed && $this->partitioning !== null && $this->query !== null) {
160 (new EnclosedQuery())->write($out, $this->query->query, $this->partitioning);
161
162 return;
163 }
164 if ($this->elements !== []) {
165 $out->symbol('(')->list($this->elements)->symbol(')');
166 }
167 foreach ($this->options as $option) {
168 $out->node($option);
169 }
170 $out->node($this->partitioning)->node($this->query);
171 }
172}
173