]> git.mxchange.org Git - friendica.git/blob - src/Database/DBStructure.php
Merge pull request #8618 from annando/foreign-keys
[friendica.git] / src / Database / DBStructure.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Database;
23
24 use Exception;
25 use Friendica\Core\Hook;
26 use Friendica\Core\Logger;
27 use Friendica\DI;
28 use Friendica\Util\DateTimeFormat;
29
30 require_once __DIR__ . '/../../include/dba.php';
31
32 /**
33  * This class contains functions that doesn't need to know if pdo, mysqli or whatever is used.
34  */
35 class DBStructure
36 {
37         const UPDATE_NOT_CHECKED = 0; // Database check wasn't executed before
38         const UPDATE_SUCCESSFUL  = 1; // Database check was successful
39         const UPDATE_FAILED      = 2; // Database check failed
40
41         const RENAME_COLUMN      = 0;
42         const RENAME_PRIMARY_KEY = 1;
43
44         /**
45          * Database structure definition loaded from config/dbstructure.config.php
46          *
47          * @var array
48          */
49         private static $definition = [];
50
51         /**
52          * Converts all tables from MyISAM/InnoDB Antelope to InnoDB Barracuda
53          */
54         public static function convertToInnoDB()
55         {
56                 $tables = DBA::selectToArray(
57                         ['information_schema' => 'tables'],
58                         ['table_name'],
59                         ['engine' => 'MyISAM', 'table_schema' => DBA::databaseName()]
60                 );
61
62                 $tables = array_merge($tables, DBA::selectToArray(
63                         ['information_schema' => 'tables'],
64                         ['table_name'],
65                         ['engine' => 'InnoDB', 'ROW_FORMAT' => ['COMPACT', 'REDUNDANT'], 'table_schema' => DBA::databaseName()]
66                 ));
67
68                 if (!DBA::isResult($tables)) {
69                         echo DI::l10n()->t('There are no tables on MyISAM or InnoDB with the Antelope file format.') . "\n";
70                         return;
71                 }
72
73                 foreach ($tables AS $table) {
74                         $sql = "ALTER TABLE " . DBA::quoteIdentifier($table['table_name']) . " ENGINE=InnoDB ROW_FORMAT=DYNAMIC;";
75                         echo $sql . "\n";
76
77                         $result = DBA::e($sql);
78                         if (!DBA::isResult($result)) {
79                                 self::printUpdateError($sql);
80                         }
81                 }
82         }
83
84         /**
85          * Print out database error messages
86          *
87          * @param string $message Message to be added to the error message
88          *
89          * @return string Error message
90          */
91         private static function printUpdateError($message)
92         {
93                 echo DI::l10n()->t("\nError %d occurred during database update:\n%s\n",
94                         DBA::errorNo(), DBA::errorMessage());
95
96                 return DI::l10n()->t('Errors encountered performing database changes: ') . $message . EOL;
97         }
98
99         public static function printStructure($basePath)
100         {
101                 $database = self::definition($basePath, false);
102
103                 echo "-- ------------------------------------------\n";
104                 echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n";
105                 echo "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
106                 echo "-- ------------------------------------------\n\n\n";
107                 foreach ($database AS $name => $structure) {
108                         echo "--\n";
109                         echo "-- TABLE $name\n";
110                         echo "--\n";
111                         self::createTable($name, $structure, true, false);
112
113                         echo "\n";
114                 }
115
116                 View::printStructure($basePath);
117         }
118
119         /**
120          * Loads the database structure definition from the static/dbstructure.config.php file.
121          * On first pass, defines DB_UPDATE_VERSION constant.
122          *
123          * @see static/dbstructure.config.php
124          * @param boolean $with_addons_structure Whether to tack on addons additional tables
125          * @param string  $basePath              The base path of this application
126          * @return array
127          * @throws Exception
128          */
129         public static function definition($basePath, $with_addons_structure = true)
130         {
131                 if (!self::$definition) {
132
133                         $filename = $basePath . '/static/dbstructure.config.php';
134
135                         if (!is_readable($filename)) {
136                                 throw new Exception('Missing database structure config file static/dbstructure.config.php');
137                         }
138
139                         $definition = require $filename;
140
141                         if (!$definition) {
142                                 throw new Exception('Corrupted database structure config file static/dbstructure.config.php');
143                         }
144
145                         self::$definition = $definition;
146                 } else {
147                         $definition = self::$definition;
148                 }
149
150                 if ($with_addons_structure) {
151                         Hook::callAll('dbstructure_definition', $definition);
152                 }
153
154                 return $definition;
155         }
156
157         private static function createTable($name, $structure, $verbose, $action)
158         {
159                 $r = true;
160
161                 $engine = "";
162                 $comment = "";
163                 $sql_rows = [];
164                 $primary_keys = [];
165                 $foreign_keys = [];
166
167                 foreach ($structure["fields"] AS $fieldname => $field) {
168                         $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
169                         if (!empty($field['primary'])) {
170                                 $primary_keys[] = $fieldname;
171                         }
172                         if (!empty($field['foreign'])) {
173                                 $foreign_keys[$fieldname] = $field;
174                         }
175                 }
176
177                 if (!empty($structure["indexes"])) {
178                         foreach ($structure["indexes"] AS $indexname => $fieldnames) {
179                                 $sql_index = self::createIndex($indexname, $fieldnames, "");
180                                 if (!is_null($sql_index)) {
181                                         $sql_rows[] = $sql_index;
182                                 }
183                         }
184                 }
185
186                 foreach ($foreign_keys AS $fieldname => $parameters) {
187                         $sql_rows[] = self::foreignCommand($name, $fieldname, $parameters);
188                 }
189
190                 if (isset($structure["engine"])) {
191                         $engine = " ENGINE=" . $structure["engine"];
192                 }
193
194                 if (isset($structure["comment"])) {
195                         $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
196                 }
197
198                 $sql = implode(",\n\t", $sql_rows);
199
200                 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
201                         "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
202                 if ($verbose) {
203                         echo $sql . ";\n";
204                 }
205
206                 if ($action) {
207                         $r = DBA::e($sql);
208                 }
209
210                 return $r;
211         }
212
213         private static function FieldCommand($parameters, $create = true)
214         {
215                 $fieldstruct = $parameters["type"];
216
217                 if (isset($parameters["Collation"])) {
218                         $fieldstruct .= " COLLATE " . $parameters["Collation"];
219                 }
220
221                 if (isset($parameters["not null"])) {
222                         $fieldstruct .= " NOT NULL";
223                 }
224
225                 if (isset($parameters["default"])) {
226                         if (strpos(strtolower($parameters["type"]), "int") !== false) {
227                                 $fieldstruct .= " DEFAULT " . $parameters["default"];
228                         } else {
229                                 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
230                         }
231                 }
232                 if (isset($parameters["extra"])) {
233                         $fieldstruct .= " " . $parameters["extra"];
234                 }
235
236                 if (isset($parameters["comment"])) {
237                         $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
238                 }
239
240                 /*if (($parameters["primary"] != "") && $create)
241                         $fieldstruct .= " PRIMARY KEY";*/
242
243                 return ($fieldstruct);
244         }
245
246         private static function createIndex($indexname, $fieldnames, $method = "ADD")
247         {
248                 $method = strtoupper(trim($method));
249                 if ($method != "" && $method != "ADD") {
250                         throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
251                 }
252
253                 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
254                         $index_type = array_shift($fieldnames);
255                         $method .= " " . $index_type;
256                 }
257
258                 $names = "";
259                 foreach ($fieldnames AS $fieldname) {
260                         if ($names != "") {
261                                 $names .= ",";
262                         }
263
264                         if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
265                                 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
266                         } else {
267                                 $names .= "`" . DBA::escape($fieldname) . "`";
268                         }
269                 }
270
271                 if ($indexname == "PRIMARY") {
272                         return sprintf("%s PRIMARY KEY(%s)", $method, $names);
273                 }
274
275
276                 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
277                 return ($sql);
278         }
279
280         /**
281          * Updates DB structure and returns eventual errors messages
282          *
283          * @param string $basePath   The base path of this application
284          * @param bool   $verbose
285          * @param bool   $action     Whether to actually apply the update
286          * @param bool   $install    Is this the initial update during the installation?
287          * @param array  $tables     An array of the database tables
288          * @param array  $definition An array of the definition tables
289          * @return string Empty string if the update is successful, error messages otherwise
290          * @throws Exception
291          */
292         public static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
293         {
294                 if ($action && !$install) {
295                         DI::config()->set('system', 'maintenance', 1);
296                         DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
297                 }
298
299                 $errors = '';
300
301                 Logger::log('updating structure', Logger::DEBUG);
302
303                 // Get the current structure
304                 $database = [];
305
306                 if (is_null($tables)) {
307                         $tables = DBA::toArray(DBA::p("SHOW TABLES"));
308                 }
309
310                 if (DBA::isResult($tables)) {
311                         foreach ($tables AS $table) {
312                                 $table = current($table);
313
314                                 Logger::log(sprintf('updating structure for table %s ...', $table), Logger::DEBUG);
315                                 $database[$table] = self::tableStructure($table);
316                         }
317                 }
318
319                 // Get the definition
320                 if (is_null($definition)) {
321                         $definition = self::definition($basePath);
322                 }
323
324                 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
325                 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
326                         !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
327                         $ignore = '';
328                 } else {
329                         $ignore = ' IGNORE';
330                 }
331
332                 // Compare it
333                 foreach ($definition AS $name => $structure) {
334                         $is_new_table = false;
335                         $group_by = "";
336                         $sql3 = "";
337                         $is_unique = false;
338                         $temp_name = $name;
339                         if (!isset($database[$name])) {
340                                 $r = self::createTable($name, $structure, $verbose, $action);
341                                 if (!DBA::isResult($r)) {
342                                         $errors .= self::printUpdateError($name);
343                                 }
344                                 $is_new_table = true;
345                         } else {
346                                 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
347                                         if (isset($database[$name]["indexes"][$indexname])) {
348                                                 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
349                                         } else {
350                                                 $current_index_definition = "__NOT_SET__";
351                                         }
352                                         $new_index_definition = implode(",", $fieldnames);
353                                         if ($current_index_definition != $new_index_definition) {
354                                                 if ($fieldnames[0] == "UNIQUE") {
355                                                         $is_unique = true;
356                                                         if ($ignore == "") {
357                                                                 $temp_name = "temp-" . $name;
358                                                         }
359                                                 }
360                                         }
361                                 }
362
363                                 /*
364                                  * Drop the index if it isn't present in the definition
365                                  * or the definition differ from current status
366                                  * and index name doesn't start with "local_"
367                                  */
368                                 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
369                                         $current_index_definition = implode(",", $fieldnames);
370                                         if (isset($structure["indexes"][$indexname])) {
371                                                 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
372                                         } else {
373                                                 $new_index_definition = "__NOT_SET__";
374                                         }
375                                         if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
376                                                 $sql2 = self::dropIndex($indexname);
377                                                 if ($sql3 == "") {
378                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
379                                                 } else {
380                                                         $sql3 .= ", " . $sql2;
381                                                 }
382                                         }
383                                 }
384                                 // Compare the field structure field by field
385                                 foreach ($structure["fields"] AS $fieldname => $parameters) {
386                                         if (!isset($database[$name]["fields"][$fieldname])) {
387                                                 $sql2 = self::addTableField($fieldname, $parameters);
388                                                 if ($sql3 == "") {
389                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
390                                                 } else {
391                                                         $sql3 .= ", " . $sql2;
392                                                 }
393                                         } else {
394                                                 // Compare the field definition
395                                                 $field_definition = $database[$name]["fields"][$fieldname];
396
397                                                 // Remove the relation data that is used for the referential integrity
398                                                 unset($parameters['relation']);
399                                                 unset($parameters['foreign']);
400
401                                                 // We change the collation after the indexes had been changed.
402                                                 // This is done to avoid index length problems.
403                                                 // So here we always ensure that there is no need to change it.
404                                                 unset($parameters['Collation']);
405                                                 unset($field_definition['Collation']);
406
407                                                 // Only update the comment when it is defined
408                                                 if (!isset($parameters['comment'])) {
409                                                         $parameters['comment'] = "";
410                                                 }
411
412                                                 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
413                                                 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
414                                                 if ($current_field_definition != $new_field_definition) {
415                                                         $sql2 = self::modifyTableField($fieldname, $parameters);
416                                                         if ($sql3 == "") {
417                                                                 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
418                                                         } else {
419                                                                 $sql3 .= ", " . $sql2;
420                                                         }
421                                                 }
422                                         }
423                                 }
424                         }
425
426                         /*
427                          * Create the index if the index don't exists in database
428                          * or the definition differ from the current status.
429                          * Don't create keys if table is new
430                          */
431                         if (!$is_new_table) {
432                                 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
433                                         if (isset($database[$name]["indexes"][$indexname])) {
434                                                 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
435                                         } else {
436                                                 $current_index_definition = "__NOT_SET__";
437                                         }
438                                         $new_index_definition = implode(",", $fieldnames);
439                                         if ($current_index_definition != $new_index_definition) {
440                                                 $sql2 = self::createIndex($indexname, $fieldnames);
441
442                                                 // Fetch the "group by" fields for unique indexes
443                                                 $group_by = self::groupBy($fieldnames);
444                                                 if ($sql2 != "") {
445                                                         if ($sql3 == "") {
446                                                                 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
447                                                         } else {
448                                                                 $sql3 .= ", " . $sql2;
449                                                         }
450                                                 }
451                                         }
452                                 }
453
454                                 $existing_foreign_keys = $database[$name]['foreign_keys'];
455
456                                 // Foreign keys
457                                 // Compare the field structure field by field
458                                 foreach ($structure["fields"] AS $fieldname => $parameters) {
459                                         if (empty($parameters['foreign'])) {
460                                                 continue;
461                                         }
462
463                                         $constraint = self::getConstraintName($name, $fieldname, $parameters);
464
465                                         unset($existing_foreign_keys[$constraint]);
466
467                                         if (empty($database[$name]['foreign_keys'][$constraint])) {
468                                                 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
469
470                                                 if ($sql3 == "") {
471                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
472                                                 } else {
473                                                         $sql3 .= ", " . $sql2;
474                                                 }
475                                         }
476                                 }
477
478                                 foreach ($existing_foreign_keys as $constraint => $param) {
479                                         $sql2 = self::dropForeignKey($constraint);
480
481                                         if ($sql3 == "") {
482                                                 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
483                                         } else {
484                                                 $sql3 .= ", " . $sql2;
485                                         }
486                                 }
487
488                                 if (isset($database[$name]["table_status"]["Comment"])) {
489                                         $structurecomment = $structure["comment"] ?? '';
490                                         if ($database[$name]["table_status"]["Comment"] != $structurecomment) {
491                                                 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
492
493                                                 if ($sql3 == "") {
494                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
495                                                 } else {
496                                                         $sql3 .= ", " . $sql2;
497                                                 }
498                                         }
499                                 }
500
501                                 if (isset($database[$name]["table_status"]["Engine"]) && isset($structure['engine'])) {
502                                         if ($database[$name]["table_status"]["Engine"] != $structure['engine']) {
503                                                 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
504
505                                                 if ($sql3 == "") {
506                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
507                                                 } else {
508                                                         $sql3 .= ", " . $sql2;
509                                                 }
510                                         }
511                                 }
512
513                                 if (isset($database[$name]["table_status"]["Collation"])) {
514                                         if ($database[$name]["table_status"]["Collation"] != 'utf8mb4_general_ci') {
515                                                 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
516
517                                                 if ($sql3 == "") {
518                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
519                                                 } else {
520                                                         $sql3 .= ", " . $sql2;
521                                                 }
522                                         }
523                                 }
524
525                                 if ($sql3 != "") {
526                                         $sql3 .= "; ";
527                                 }
528
529                                 // Now have a look at the field collations
530                                 // Compare the field structure field by field
531                                 foreach ($structure["fields"] AS $fieldname => $parameters) {
532                                         // Compare the field definition
533                                         $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
534
535                                         // Define the default collation if not given
536                                         if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
537                                                 $parameters['Collation'] = 'utf8mb4_general_ci';
538                                         } else {
539                                                 $parameters['Collation'] = null;
540                                         }
541
542                                         if ($field_definition['Collation'] != $parameters['Collation']) {
543                                                 $sql2 = self::modifyTableField($fieldname, $parameters);
544                                                 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
545                                                         $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
546                                                 } else {
547                                                         $sql3 .= ", " . $sql2;
548                                                 }
549                                         }
550                                 }
551                         }
552
553                         if ($sql3 != "") {
554                                 if (substr($sql3, -2, 2) != "; ") {
555                                         $sql3 .= ";";
556                                 }
557
558                                 $field_list = '';
559                                 if ($is_unique && $ignore == '') {
560                                         foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
561                                                 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
562                                         }
563                                         $field_list = rtrim($field_list, ',');
564                                 }
565
566                                 if ($verbose) {
567                                         // Ensure index conversion to unique removes duplicates
568                                         if ($is_unique && ($temp_name != $name)) {
569                                                 if ($ignore != "") {
570                                                         echo "SET session old_alter_table=1;\n";
571                                                 } else {
572                                                         echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
573                                                         echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
574                                                 }
575                                         }
576
577                                         echo $sql3 . "\n";
578
579                                         if ($is_unique && ($temp_name != $name)) {
580                                                 if ($ignore != "") {
581                                                         echo "SET session old_alter_table=0;\n";
582                                                 } else {
583                                                         echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
584                                                         echo "DROP TABLE `" . $name . "`;\n";
585                                                         echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
586                                                 }
587                                         }
588                                 }
589
590                                 if ($action) {
591                                         if (!$install) {
592                                                 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
593                                         }
594
595                                         // Ensure index conversion to unique removes duplicates
596                                         if ($is_unique && ($temp_name != $name)) {
597                                                 if ($ignore != "") {
598                                                         DBA::e("SET session old_alter_table=1;");
599                                                 } else {
600                                                         $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
601                                                         if (!DBA::isResult($r)) {
602                                                                 $errors .= self::printUpdateError($sql3);
603                                                                 return $errors;
604                                                         }
605
606                                                         $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
607                                                         if (!DBA::isResult($r)) {
608                                                                 $errors .= self::printUpdateError($sql3);
609                                                                 return $errors;
610                                                         }
611                                                 }
612                                         }
613
614                                         $r = DBA::e($sql3);
615                                         if (!DBA::isResult($r)) {
616                                                 $errors .= self::printUpdateError($sql3);
617                                         }
618                                         if ($is_unique && ($temp_name != $name)) {
619                                                 if ($ignore != "") {
620                                                         DBA::e("SET session old_alter_table=0;");
621                                                 } else {
622                                                         $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
623                                                         if (!DBA::isResult($r)) {
624                                                                 $errors .= self::printUpdateError($sql3);
625                                                                 return $errors;
626                                                         }
627                                                         $r = DBA::e("DROP TABLE `" . $name . "`;");
628                                                         if (!DBA::isResult($r)) {
629                                                                 $errors .= self::printUpdateError($sql3);
630                                                                 return $errors;
631                                                         }
632                                                         $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
633                                                         if (!DBA::isResult($r)) {
634                                                                 $errors .= self::printUpdateError($sql3);
635                                                                 return $errors;
636                                                         }
637                                                 }
638                                         }
639                                 }
640                         }
641                 }
642
643                 View::create(false, $action);
644
645                 if ($action && !$install) {
646                         DI::config()->set('system', 'maintenance', 0);
647                         DI::config()->set('system', 'maintenance_reason', '');
648
649                         if ($errors) {
650                                 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
651                         } else {
652                                 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
653                         }
654                 }
655
656                 return $errors;
657         }
658
659         private static function tableStructure($table)
660         {
661                 $structures = q("DESCRIBE `%s`", $table);
662
663                 $full_columns = q("SHOW FULL COLUMNS FROM `%s`", $table);
664
665                 $indexes = q("SHOW INDEX FROM `%s`", $table);
666
667                 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
668                         ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
669                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
670                         DBA::databaseName(), $table]);
671
672                 $table_status = q("SHOW TABLE STATUS WHERE `name` = '%s'", $table);
673
674                 if (DBA::isResult($table_status)) {
675                         $table_status = $table_status[0];
676                 } else {
677                         $table_status = [];
678                 }
679
680                 $fielddata = [];
681                 $indexdata = [];
682                 $foreigndata = [];
683
684                 if (DBA::isResult($foreign_keys)) {
685                         foreach ($foreign_keys as $foreign_key) {
686                                 $constraint = $foreign_key['CONSTRAINT_NAME'];
687                                 unset($foreign_key['CONSTRAINT_NAME']); 
688                                 $foreigndata[$constraint] = $foreign_key;
689                         }
690                 }
691
692                 if (DBA::isResult($indexes)) {
693                         foreach ($indexes AS $index) {
694                                 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
695                                         $indexdata[$index["Key_name"]] = ["UNIQUE"];
696                                 }
697
698                                 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
699                                         $indexdata[$index["Key_name"]] = ["FULLTEXT"];
700                                 }
701
702                                 $column = $index["Column_name"];
703
704                                 if ($index["Sub_part"] != "") {
705                                         $column .= "(" . $index["Sub_part"] . ")";
706                                 }
707
708                                 $indexdata[$index["Key_name"]][] = $column;
709                         }
710                 }
711                 if (DBA::isResult($structures)) {
712                         foreach ($structures AS $field) {
713                                 // Replace the default size values so that we don't have to define them
714                                 $search = ['tinyint(1)', 'tinyint(3) unsigned', 'tinyint(4)', 'smallint(5) unsigned', 'smallint(6)', 'mediumint(8) unsigned', 'mediumint(9)', 'bigint(20)', 'int(10) unsigned', 'int(11)'];
715                                 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
716                                 $field["Type"] = str_replace($search, $replace, $field["Type"]);
717
718                                 $fielddata[$field["Field"]]["type"] = $field["Type"];
719                                 if ($field["Null"] == "NO") {
720                                         $fielddata[$field["Field"]]["not null"] = true;
721                                 }
722
723                                 if (isset($field["Default"])) {
724                                         $fielddata[$field["Field"]]["default"] = $field["Default"];
725                                 }
726
727                                 if ($field["Extra"] != "") {
728                                         $fielddata[$field["Field"]]["extra"] = $field["Extra"];
729                                 }
730
731                                 if ($field["Key"] == "PRI") {
732                                         $fielddata[$field["Field"]]["primary"] = true;
733                                 }
734                         }
735                 }
736                 if (DBA::isResult($full_columns)) {
737                         foreach ($full_columns AS $column) {
738                                 $fielddata[$column["Field"]]["Collation"] = $column["Collation"];
739                                 $fielddata[$column["Field"]]["comment"] = $column["Comment"];
740                         }
741                 }
742
743                 return ["fields" => $fielddata, "indexes" => $indexdata,
744                         "foreign_keys" => $foreigndata, "table_status" => $table_status];
745         }
746
747         private static function dropIndex($indexname)
748         {
749                 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
750                 return ($sql);
751         }
752
753         private static function addTableField($fieldname, $parameters)
754         {
755                 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
756                 return ($sql);
757         }
758
759         private static function modifyTableField($fieldname, $parameters)
760         {
761                 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
762                 return ($sql);
763         }
764
765         private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
766         {
767                 $foreign_table = array_keys($parameters['foreign'])[0];
768                 $foreign_field = array_values($parameters['foreign'])[0];
769
770                 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
771         }
772
773         private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
774                 $foreign_table = array_keys($parameters['foreign'])[0];
775                 $foreign_field = array_values($parameters['foreign'])[0];
776
777                 $constraint = self::getConstraintName($tablename, $fieldname, $parameters);
778
779                 $sql = "CONSTRAINT `" . $constraint . "` FOREIGN KEY (`" . $fieldname . "`)" .
780                         " REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
781
782                 if (!empty($parameters['foreign']['on update'])) {
783                         $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
784                 } else {
785                         $sql .= " ON UPDATE RESTRICT";
786                 }
787
788                 if (!empty($parameters['foreign']['on delete'])) {
789                         $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
790                 } else {
791                         $sql .= " ON DELETE CASCADE";
792                 }
793
794                 return $sql;
795         }
796
797         private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
798         {
799                 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
800         }
801
802         private static function dropForeignKey(string $constraint)
803         {
804                 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
805         }
806
807         /**
808          * Constructs a GROUP BY clause from a UNIQUE index definition.
809          *
810          * @param array $fieldnames
811          * @return string
812          */
813         private static function groupBy(array $fieldnames)
814         {
815                 if ($fieldnames[0] != "UNIQUE") {
816                         return "";
817                 }
818
819                 array_shift($fieldnames);
820
821                 $names = "";
822                 foreach ($fieldnames AS $fieldname) {
823                         if ($names != "") {
824                                 $names .= ",";
825                         }
826
827                         if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
828                                 $names .= "`" . DBA::escape($matches[1]) . "`";
829                         } else {
830                                 $names .= "`" . DBA::escape($fieldname) . "`";
831                         }
832                 }
833
834                 $sql = sprintf(" GROUP BY %s", $names);
835                 return $sql;
836         }
837
838         /**
839          * Renames columns or the primary key of a table
840          *
841          * @todo You cannot rename a primary key if "auto increment" is set
842          *
843          * @param string $table            Table name
844          * @param array  $columns          Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
845          *                                 Syntax for Primary Key: [ $col1, $col2, ...]
846          * @param int    $type             The type of renaming (Default is Column)
847          *
848          * @return boolean Was the renaming successful?
849          * @throws Exception
850          */
851         public static function rename($table, $columns, $type = self::RENAME_COLUMN)
852         {
853                 if (empty($table) || empty($columns)) {
854                         return false;
855                 }
856
857                 if (!is_array($columns)) {
858                         return false;
859                 }
860
861                 $table = DBA::escape($table);
862
863                 $sql = "ALTER TABLE `" . $table . "`";
864                 switch ($type) {
865                         case self::RENAME_COLUMN:
866                                 if (!self::existsColumn($table, array_keys($columns))) {
867                                         return false;
868                                 }
869                                 $sql .= implode(',', array_map(
870                                         function ($to, $from) {
871                                                 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
872                                         },
873                                         $columns,
874                                         array_keys($columns)
875                                 ));
876                                 break;
877                         case self::RENAME_PRIMARY_KEY:
878                                 if (!self::existsColumn($table, $columns)) {
879                                         return false;
880                                 }
881                                 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
882                                 break;
883                         default:
884                                 return false;
885                 }
886
887                 $sql .= ";";
888
889                 $stmt = DBA::p($sql);
890
891                 if (is_bool($stmt)) {
892                         $retval = $stmt;
893                 } else {
894                         $retval = true;
895                 }
896
897                 DBA::close($stmt);
898
899                 return $retval;
900         }
901
902         /**
903          *    Check if the columns of the table exists
904          *
905          * @param string $table   Table name
906          * @param array  $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
907          *
908          * @return boolean Does the table exist?
909          * @throws Exception
910          */
911         public static function existsColumn($table, $columns = [])
912         {
913                 if (empty($table)) {
914                         return false;
915                 }
916
917                 if (is_null($columns) || empty($columns)) {
918                         return self::existsTable($table);
919                 }
920
921                 $table = DBA::escape($table);
922
923                 foreach ($columns AS $column) {
924                         $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
925
926                         $stmt = DBA::p($sql);
927
928                         if (is_bool($stmt)) {
929                                 $retval = $stmt;
930                         } else {
931                                 $retval = (DBA::numRows($stmt) > 0);
932                         }
933
934                         DBA::close($stmt);
935
936                         if (!$retval) {
937                                 return false;
938                         }
939                 }
940
941                 return true;
942         }
943
944         /**
945          *    Check if a table exists
946          *
947          * @param string|array $table Table name
948          *
949          * @return boolean Does the table exist?
950          * @throws Exception
951          */
952         public static function existsTable($table)
953         {
954                 if (empty($table)) {
955                         return false;
956                 }
957
958                 if (is_array($table)) {
959                         $condition = ['table_schema' => key($table), 'table_name' => current($table)];
960                 } else {
961                         $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
962                 }
963
964                 $result = DBA::exists(['information_schema' => 'tables'], $condition);
965
966                 return $result;
967         }
968
969         /**
970          * Returns the columns of a table
971          *
972          * @param string $table Table name
973          *
974          * @return array An array of the table columns
975          * @throws Exception
976          */
977         public static function getColumns($table)
978         {
979                 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
980                 return DBA::toArray($stmtColumns);
981         }
982 }