3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Util\Writer;
26 use Friendica\Database\Definition\DbaDefinition;
29 * SQL writer utility for the database definition
31 class DbaDefinitionSqlWriter
34 * Creates a complete SQL definition bases on a give DBA Definition class
36 * @param DbaDefinition $definition The DBA definition class
38 * @return string The SQL definition as a string
40 * @throws Exception in case of parameter failures
42 public static function create(DbaDefinition $definition): string
44 $sqlString = "-- ------------------------------------------\n";
45 $sqlString .= "-- " . App::PLATFORM . " " . App::VERSION . " (" . App::CODENAME . ")\n";
46 $sqlString .= "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
47 $sqlString .= "-- ------------------------------------------\n\n\n";
49 foreach ($definition->getAll() as $tableName => $tableStructure) {
51 $sqlString .= "-- TABLE $tableName\n";
53 $sqlString .= static::createTable($tableName, $tableStructure);
60 * Creates the SQL definition of one table
62 * @param string $tableName The table name
63 * @param array $tableStructure The table structure
65 * @return string The SQL definition
67 * @throws Exception in cases of structure failures
69 public static function createTable(string $tableName, array $tableStructure): string
77 foreach ($tableStructure['fields'] as $fieldName => $field) {
78 $sql_rows[] = '`' . static::escape($fieldName) . '` ' . self::fieldCommand($field);
79 if (!empty($field['primary'])) {
80 $primary_keys[] = $fieldName;
82 if (!empty($field['foreign'])) {
83 $foreign_keys[$fieldName] = $field;
87 if (!empty($tableStructure['indexes'])) {
88 foreach ($tableStructure['indexes'] as $indexName => $fieldNames) {
89 $sql_index = self::createIndex($indexName, $fieldNames, '');
90 if (!is_null($sql_index)) {
91 $sql_rows[] = $sql_index;
96 foreach ($foreign_keys as $fieldName => $parameters) {
97 $sql_rows[] = self::foreignCommand($fieldName, $parameters);
100 if (isset($tableStructure['engine'])) {
101 $engine = ' ENGINE=' . $tableStructure['engine'];
104 if (isset($tableStructure['comment'])) {
105 $comment = " COMMENT='" . static::escape($tableStructure['comment']) . "'";
108 $sql = implode(",\n\t", $sql_rows);
110 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", static::escape($tableName)) . $sql .
111 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
112 return $sql . ";\n\n";
116 * Standard escaping for SQL definitions
118 * @param string $sqlString the SQL string to escape
120 * @return string escaped SQL string
122 public static function escape(string $sqlString): string
124 return str_replace("'", "\\'", $sqlString);
128 * Creates the SQL definition to add a foreign key
130 * @param string $keyName The foreign key name
131 * @param array $parameters The given parameters of the foreign key
133 * @return string The SQL definition
135 public static function addForeignKey(string $keyName, array $parameters): string
137 return sprintf("ADD %s", static::foreignCommand($keyName, $parameters));
141 * Creates the SQL definition to drop a foreign key
143 * @param string $keyName The foreign key name
145 * @return string The SQL definition
147 public static function dropForeignKey(string $keyName): string
149 return sprintf("DROP FOREIGN KEY `%s`", $keyName);
153 * Creates the SQL definition to drop an index
155 * @param string $indexName The index name
157 * @return string The SQL definition
159 public static function dropIndex(string $indexName): string
161 return sprintf("DROP INDEX `%s`", static::escape($indexName));
165 * Creates the SQL definition to add a table field
167 * @param string $fieldName The table field name
168 * @param array $parameters The parameters of the table field
170 * @return string The SQL definition
172 public static function addTableField(string $fieldName, array $parameters): string
174 return sprintf("ADD `%s` %s", static::escape($fieldName), static::fieldCommand($parameters));
178 * Creates the SQL definition to modify a table field
180 * @param string $fieldName The table field name
181 * @param array $parameters The parameters to modify
183 * @return string The SQL definition
185 public static function modifyTableField(string $fieldName, array $parameters): string
187 return sprintf("MODIFY `%s` %s", static::escape($fieldName), self::fieldCommand($parameters, false));
191 * Returns SQL statement for field
193 * @param array $parameters Parameters for SQL statement
194 * @param boolean $create Whether to include PRIMARY KEY statement (unused)
195 * @return string SQL statement part
197 public static function fieldCommand(array $parameters, bool $create = true): string
199 $fieldstruct = $parameters['type'];
201 if (isset($parameters['Collation'])) {
202 $fieldstruct .= ' COLLATE ' . $parameters['Collation'];
205 if (isset($parameters['not null'])) {
206 $fieldstruct .= ' NOT NULL';
209 if (isset($parameters['default'])) {
210 if (strpos(strtolower($parameters['type']), 'int') !== false) {
211 $fieldstruct .= ' DEFAULT ' . $parameters['default'];
213 $fieldstruct .= " DEFAULT '" . $parameters['default'] . "'";
216 if (isset($parameters['extra'])) {
217 $fieldstruct .= ' ' . $parameters['extra'];
220 if (isset($parameters['comment'])) {
221 $fieldstruct .= " COMMENT '" . static::escape($parameters['comment']) . "'";
224 /*if (($parameters['primary'] != '') && $create)
225 $fieldstruct .= ' PRIMARY KEY';*/
231 * Creates the SQL definition to create an index
233 * @param string $indexName The index name
234 * @param array $fieldNames The field names of this index
235 * @param string $method The method to create the index (default is ADD)
237 * @return string The SQL definition
238 * @throws Exception in cases the parameter contains invalid content
240 public static function createIndex(string $indexName, array $fieldNames, string $method = 'ADD'): string
242 $method = strtoupper(trim($method));
243 if ($method != '' && $method != 'ADD') {
244 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
247 if (in_array($fieldNames[0], ['UNIQUE', 'FULLTEXT'])) {
248 $index_type = array_shift($fieldNames);
249 $method .= " " . $index_type;
253 foreach ($fieldNames as $fieldName) {
258 if (preg_match('|(.+)\((\d+)\)|', $fieldName, $matches)) {
259 $names .= "`" . static::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
261 $names .= "`" . static::escape($fieldName) . "`";
265 if ($indexName == 'PRIMARY') {
266 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
270 return sprintf("%s INDEX `%s` (%s)", $method, static::escape($indexName), $names);
274 * Creates the SQL definition for foreign keys
276 * @param string $foreignKeyName The foreign key name
277 * @param array $parameters The parameters of the foreign key
279 * @return string The SQL definition
281 public static function foreignCommand(string $foreignKeyName, array $parameters): string
283 $foreign_table = array_keys($parameters['foreign'])[0];
284 $foreign_field = array_values($parameters['foreign'])[0];
286 $sql = "FOREIGN KEY (`" . $foreignKeyName . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
288 if (!empty($parameters['foreign']['on update'])) {
289 $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
291 $sql .= " ON UPDATE RESTRICT";
294 if (!empty($parameters['foreign']['on delete'])) {
295 $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
297 $sql .= " ON DELETE CASCADE";