]> git.mxchange.org Git - friendica.git/blob - src/Database/DBStructure.php
Merge remote-tracking branch 'upstream/develop' into views
[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                 DBView::printStructure($basePath);
117         }
118
119         /**
120          * Loads the database structure definition from the config/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                 foreach ($structure["fields"] AS $fieldname => $field) {
166                         $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
167                         if (!empty($field['primary'])) {
168                                 $primary_keys[] = $fieldname;
169                         }
170                 }
171
172                 if (!empty($structure["indexes"])) {
173                         foreach ($structure["indexes"] AS $indexname => $fieldnames) {
174                                 $sql_index = self::createIndex($indexname, $fieldnames, "");
175                                 if (!is_null($sql_index)) {
176                                         $sql_rows[] = $sql_index;
177                                 }
178                         }
179                 }
180
181                 if (isset($structure["engine"])) {
182                         $engine = " ENGINE=" . $structure["engine"];
183                 }
184
185                 if (isset($structure["comment"])) {
186                         $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
187                 }
188
189                 $sql = implode(",\n\t", $sql_rows);
190
191                 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
192                         "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
193                 if ($verbose) {
194                         echo $sql . ";\n";
195                 }
196
197                 if ($action) {
198                         $r = DBA::e($sql);
199                 }
200
201                 return $r;
202         }
203
204         private static function FieldCommand($parameters, $create = true)
205         {
206                 $fieldstruct = $parameters["type"];
207
208                 if (isset($parameters["Collation"])) {
209                         $fieldstruct .= " COLLATE " . $parameters["Collation"];
210                 }
211
212                 if (isset($parameters["not null"])) {
213                         $fieldstruct .= " NOT NULL";
214                 }
215
216                 if (isset($parameters["default"])) {
217                         if (strpos(strtolower($parameters["type"]), "int") !== false) {
218                                 $fieldstruct .= " DEFAULT " . $parameters["default"];
219                         } else {
220                                 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
221                         }
222                 }
223                 if (isset($parameters["extra"])) {
224                         $fieldstruct .= " " . $parameters["extra"];
225                 }
226
227                 if (isset($parameters["comment"])) {
228                         $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
229                 }
230
231                 /*if (($parameters["primary"] != "") && $create)
232                         $fieldstruct .= " PRIMARY KEY";*/
233
234                 return ($fieldstruct);
235         }
236
237         private static function createIndex($indexname, $fieldnames, $method = "ADD")
238         {
239                 $method = strtoupper(trim($method));
240                 if ($method != "" && $method != "ADD") {
241                         throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
242                 }
243
244                 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
245                         $index_type = array_shift($fieldnames);
246                         $method .= " " . $index_type;
247                 }
248
249                 $names = "";
250                 foreach ($fieldnames AS $fieldname) {
251                         if ($names != "") {
252                                 $names .= ",";
253                         }
254
255                         if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
256                                 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
257                         } else {
258                                 $names .= "`" . DBA::escape($fieldname) . "`";
259                         }
260                 }
261
262                 if ($indexname == "PRIMARY") {
263                         return sprintf("%s PRIMARY KEY(%s)", $method, $names);
264                 }
265
266
267                 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
268                 return ($sql);
269         }
270
271         /**
272          * Updates DB structure and returns eventual errors messages
273          *
274          * @param string $basePath   The base path of this application
275          * @param bool   $verbose
276          * @param bool   $action     Whether to actually apply the update
277          * @param bool   $install    Is this the initial update during the installation?
278          * @param array  $tables     An array of the database tables
279          * @param array  $definition An array of the definition tables
280          * @return string Empty string if the update is successful, error messages otherwise
281          * @throws Exception
282          */
283         public static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
284         {
285                 if ($action && !$install) {
286                         DI::config()->set('system', 'maintenance', 1);
287                         DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
288                 }
289
290                 $errors = '';
291
292                 Logger::log('updating structure', Logger::DEBUG);
293
294                 // Get the current structure
295                 $database = [];
296
297                 if (is_null($tables)) {
298                         $tables = q("SHOW TABLES");
299                 }
300
301                 if (DBA::isResult($tables)) {
302                         foreach ($tables AS $table) {
303                                 $table = current($table);
304
305                                 Logger::log(sprintf('updating structure for table %s ...', $table), Logger::DEBUG);
306                                 $database[$table] = self::tableStructure($table);
307                         }
308                 }
309
310                 // Get the definition
311                 if (is_null($definition)) {
312                         $definition = self::definition($basePath);
313                 }
314
315                 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
316                 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
317                         !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
318                         $ignore = '';
319                 } else {
320                         $ignore = ' IGNORE';
321                 }
322
323                 // Compare it
324                 foreach ($definition AS $name => $structure) {
325                         $is_new_table = false;
326                         $group_by = "";
327                         $sql3 = "";
328                         $is_unique = false;
329                         $temp_name = $name;
330                         if (!isset($database[$name])) {
331                                 $r = self::createTable($name, $structure, $verbose, $action);
332                                 if (!DBA::isResult($r)) {
333                                         $errors .= self::printUpdateError($name);
334                                 }
335                                 $is_new_table = true;
336                         } else {
337                                 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
338                                         if (isset($database[$name]["indexes"][$indexname])) {
339                                                 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
340                                         } else {
341                                                 $current_index_definition = "__NOT_SET__";
342                                         }
343                                         $new_index_definition = implode(",", $fieldnames);
344                                         if ($current_index_definition != $new_index_definition) {
345                                                 if ($fieldnames[0] == "UNIQUE") {
346                                                         $is_unique = true;
347                                                         if ($ignore == "") {
348                                                                 $temp_name = "temp-" . $name;
349                                                         }
350                                                 }
351                                         }
352                                 }
353
354                                 /*
355                                  * Drop the index if it isn't present in the definition
356                                  * or the definition differ from current status
357                                  * and index name doesn't start with "local_"
358                                  */
359                                 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
360                                         $current_index_definition = implode(",", $fieldnames);
361                                         if (isset($structure["indexes"][$indexname])) {
362                                                 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
363                                         } else {
364                                                 $new_index_definition = "__NOT_SET__";
365                                         }
366                                         if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
367                                                 $sql2 = self::dropIndex($indexname);
368                                                 if ($sql3 == "") {
369                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
370                                                 } else {
371                                                         $sql3 .= ", " . $sql2;
372                                                 }
373                                         }
374                                 }
375                                 // Compare the field structure field by field
376                                 foreach ($structure["fields"] AS $fieldname => $parameters) {
377                                         if (!isset($database[$name]["fields"][$fieldname])) {
378                                                 $sql2 = self::addTableField($fieldname, $parameters);
379                                                 if ($sql3 == "") {
380                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
381                                                 } else {
382                                                         $sql3 .= ", " . $sql2;
383                                                 }
384                                         } else {
385                                                 // Compare the field definition
386                                                 $field_definition = $database[$name]["fields"][$fieldname];
387
388                                                 // Remove the relation data that is used for the referential integrity
389                                                 unset($parameters['relation']);
390
391                                                 // We change the collation after the indexes had been changed.
392                                                 // This is done to avoid index length problems.
393                                                 // So here we always ensure that there is no need to change it.
394                                                 unset($parameters['Collation']);
395                                                 unset($field_definition['Collation']);
396
397                                                 // Only update the comment when it is defined
398                                                 if (!isset($parameters['comment'])) {
399                                                         $parameters['comment'] = "";
400                                                 }
401
402                                                 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
403                                                 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
404                                                 if ($current_field_definition != $new_field_definition) {
405                                                         $sql2 = self::modifyTableField($fieldname, $parameters);
406                                                         if ($sql3 == "") {
407                                                                 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
408                                                         } else {
409                                                                 $sql3 .= ", " . $sql2;
410                                                         }
411                                                 }
412                                         }
413                                 }
414                         }
415
416                         /*
417                          * Create the index if the index don't exists in database
418                          * or the definition differ from the current status.
419                          * Don't create keys if table is new
420                          */
421                         if (!$is_new_table) {
422                                 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
423                                         if (isset($database[$name]["indexes"][$indexname])) {
424                                                 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
425                                         } else {
426                                                 $current_index_definition = "__NOT_SET__";
427                                         }
428                                         $new_index_definition = implode(",", $fieldnames);
429                                         if ($current_index_definition != $new_index_definition) {
430                                                 $sql2 = self::createIndex($indexname, $fieldnames);
431
432                                                 // Fetch the "group by" fields for unique indexes
433                                                 $group_by = self::groupBy($fieldnames);
434                                                 if ($sql2 != "") {
435                                                         if ($sql3 == "") {
436                                                                 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
437                                                         } else {
438                                                                 $sql3 .= ", " . $sql2;
439                                                         }
440                                                 }
441                                         }
442                                 }
443
444                                 if (isset($database[$name]["table_status"]["Comment"])) {
445                                         $structurecomment = $structure["comment"] ?? '';
446                                         if ($database[$name]["table_status"]["Comment"] != $structurecomment) {
447                                                 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
448
449                                                 if ($sql3 == "") {
450                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
451                                                 } else {
452                                                         $sql3 .= ", " . $sql2;
453                                                 }
454                                         }
455                                 }
456
457                                 if (isset($database[$name]["table_status"]["Engine"]) && isset($structure['engine'])) {
458                                         if ($database[$name]["table_status"]["Engine"] != $structure['engine']) {
459                                                 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
460
461                                                 if ($sql3 == "") {
462                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
463                                                 } else {
464                                                         $sql3 .= ", " . $sql2;
465                                                 }
466                                         }
467                                 }
468
469                                 if (isset($database[$name]["table_status"]["Collation"])) {
470                                         if ($database[$name]["table_status"]["Collation"] != 'utf8mb4_general_ci') {
471                                                 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
472
473                                                 if ($sql3 == "") {
474                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
475                                                 } else {
476                                                         $sql3 .= ", " . $sql2;
477                                                 }
478                                         }
479                                 }
480
481                                 if ($sql3 != "") {
482                                         $sql3 .= "; ";
483                                 }
484
485                                 // Now have a look at the field collations
486                                 // Compare the field structure field by field
487                                 foreach ($structure["fields"] AS $fieldname => $parameters) {
488                                         // Compare the field definition
489                                         $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
490
491                                         // Define the default collation if not given
492                                         if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
493                                                 $parameters['Collation'] = 'utf8mb4_general_ci';
494                                         } else {
495                                                 $parameters['Collation'] = null;
496                                         }
497
498                                         if ($field_definition['Collation'] != $parameters['Collation']) {
499                                                 $sql2 = self::modifyTableField($fieldname, $parameters);
500                                                 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
501                                                         $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
502                                                 } else {
503                                                         $sql3 .= ", " . $sql2;
504                                                 }
505                                         }
506                                 }
507                         }
508
509                         if ($sql3 != "") {
510                                 if (substr($sql3, -2, 2) != "; ") {
511                                         $sql3 .= ";";
512                                 }
513
514                                 $field_list = '';
515                                 if ($is_unique && $ignore == '') {
516                                         foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
517                                                 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
518                                         }
519                                         $field_list = rtrim($field_list, ',');
520                                 }
521
522                                 if ($verbose) {
523                                         // Ensure index conversion to unique removes duplicates
524                                         if ($is_unique && ($temp_name != $name)) {
525                                                 if ($ignore != "") {
526                                                         echo "SET session old_alter_table=1;\n";
527                                                 } else {
528                                                         echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
529                                                         echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
530                                                 }
531                                         }
532
533                                         echo $sql3 . "\n";
534
535                                         if ($is_unique && ($temp_name != $name)) {
536                                                 if ($ignore != "") {
537                                                         echo "SET session old_alter_table=0;\n";
538                                                 } else {
539                                                         echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
540                                                         echo "DROP TABLE `" . $name . "`;\n";
541                                                         echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
542                                                 }
543                                         }
544                                 }
545
546                                 if ($action) {
547                                         if (!$install) {
548                                                 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
549                                         }
550
551                                         // Ensure index conversion to unique removes duplicates
552                                         if ($is_unique && ($temp_name != $name)) {
553                                                 if ($ignore != "") {
554                                                         DBA::e("SET session old_alter_table=1;");
555                                                 } else {
556                                                         $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
557                                                         if (!DBA::isResult($r)) {
558                                                                 $errors .= self::printUpdateError($sql3);
559                                                                 return $errors;
560                                                         }
561
562                                                         $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
563                                                         if (!DBA::isResult($r)) {
564                                                                 $errors .= self::printUpdateError($sql3);
565                                                                 return $errors;
566                                                         }
567                                                 }
568                                         }
569
570                                         $r = DBA::e($sql3);
571                                         if (!DBA::isResult($r)) {
572                                                 $errors .= self::printUpdateError($sql3);
573                                         }
574                                         if ($is_unique && ($temp_name != $name)) {
575                                                 if ($ignore != "") {
576                                                         DBA::e("SET session old_alter_table=0;");
577                                                 } else {
578                                                         $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
579                                                         if (!DBA::isResult($r)) {
580                                                                 $errors .= self::printUpdateError($sql3);
581                                                                 return $errors;
582                                                         }
583                                                         $r = DBA::e("DROP TABLE `" . $name . "`;");
584                                                         if (!DBA::isResult($r)) {
585                                                                 $errors .= self::printUpdateError($sql3);
586                                                                 return $errors;
587                                                         }
588                                                         $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
589                                                         if (!DBA::isResult($r)) {
590                                                                 $errors .= self::printUpdateError($sql3);
591                                                                 return $errors;
592                                                         }
593                                                 }
594                                         }
595                                 }
596                         }
597                 }
598
599                 DBView::create($verbose, $action);
600
601                 if ($action && !$install) {
602                         DI::config()->set('system', 'maintenance', 0);
603                         DI::config()->set('system', 'maintenance_reason', '');
604
605                         if ($errors) {
606                                 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
607                         } else {
608                                 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
609                         }
610                 }
611
612                 return $errors;
613         }
614
615         private static function tableStructure($table)
616         {
617                 $structures = q("DESCRIBE `%s`", $table);
618
619                 $full_columns = q("SHOW FULL COLUMNS FROM `%s`", $table);
620
621                 $indexes = q("SHOW INDEX FROM `%s`", $table);
622
623                 $table_status = q("SHOW TABLE STATUS WHERE `name` = '%s'", $table);
624
625                 if (DBA::isResult($table_status)) {
626                         $table_status = $table_status[0];
627                 } else {
628                         $table_status = [];
629                 }
630
631                 $fielddata = [];
632                 $indexdata = [];
633
634                 if (DBA::isResult($indexes)) {
635                         foreach ($indexes AS $index) {
636                                 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
637                                         $indexdata[$index["Key_name"]] = ["UNIQUE"];
638                                 }
639
640                                 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
641                                         $indexdata[$index["Key_name"]] = ["FULLTEXT"];
642                                 }
643
644                                 $column = $index["Column_name"];
645
646                                 if ($index["Sub_part"] != "") {
647                                         $column .= "(" . $index["Sub_part"] . ")";
648                                 }
649
650                                 $indexdata[$index["Key_name"]][] = $column;
651                         }
652                 }
653                 if (DBA::isResult($structures)) {
654                         foreach ($structures AS $field) {
655                                 // Replace the default size values so that we don't have to define them
656                                 $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)'];
657                                 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
658                                 $field["Type"] = str_replace($search, $replace, $field["Type"]);
659
660                                 $fielddata[$field["Field"]]["type"] = $field["Type"];
661                                 if ($field["Null"] == "NO") {
662                                         $fielddata[$field["Field"]]["not null"] = true;
663                                 }
664
665                                 if (isset($field["Default"])) {
666                                         $fielddata[$field["Field"]]["default"] = $field["Default"];
667                                 }
668
669                                 if ($field["Extra"] != "") {
670                                         $fielddata[$field["Field"]]["extra"] = $field["Extra"];
671                                 }
672
673                                 if ($field["Key"] == "PRI") {
674                                         $fielddata[$field["Field"]]["primary"] = true;
675                                 }
676                         }
677                 }
678                 if (DBA::isResult($full_columns)) {
679                         foreach ($full_columns AS $column) {
680                                 $fielddata[$column["Field"]]["Collation"] = $column["Collation"];
681                                 $fielddata[$column["Field"]]["comment"] = $column["Comment"];
682                         }
683                 }
684
685                 return ["fields" => $fielddata, "indexes" => $indexdata, "table_status" => $table_status];
686         }
687
688         private static function dropIndex($indexname)
689         {
690                 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
691                 return ($sql);
692         }
693
694         private static function addTableField($fieldname, $parameters)
695         {
696                 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
697                 return ($sql);
698         }
699
700         private static function modifyTableField($fieldname, $parameters)
701         {
702                 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
703                 return ($sql);
704         }
705
706         /**
707          * Constructs a GROUP BY clause from a UNIQUE index definition.
708          *
709          * @param array $fieldnames
710          * @return string
711          */
712         private static function groupBy(array $fieldnames)
713         {
714                 if ($fieldnames[0] != "UNIQUE") {
715                         return "";
716                 }
717
718                 array_shift($fieldnames);
719
720                 $names = "";
721                 foreach ($fieldnames AS $fieldname) {
722                         if ($names != "") {
723                                 $names .= ",";
724                         }
725
726                         if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
727                                 $names .= "`" . DBA::escape($matches[1]) . "`";
728                         } else {
729                                 $names .= "`" . DBA::escape($fieldname) . "`";
730                         }
731                 }
732
733                 $sql = sprintf(" GROUP BY %s", $names);
734                 return $sql;
735         }
736
737         /**
738          * Renames columns or the primary key of a table
739          *
740          * @todo You cannot rename a primary key if "auto increment" is set
741          *
742          * @param string $table            Table name
743          * @param array  $columns          Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
744          *                                 Syntax for Primary Key: [ $col1, $col2, ...]
745          * @param int    $type             The type of renaming (Default is Column)
746          *
747          * @return boolean Was the renaming successful?
748          * @throws Exception
749          */
750         public static function rename($table, $columns, $type = self::RENAME_COLUMN)
751         {
752                 if (empty($table) || empty($columns)) {
753                         return false;
754                 }
755
756                 if (!is_array($columns)) {
757                         return false;
758                 }
759
760                 $table = DBA::escape($table);
761
762                 $sql = "ALTER TABLE `" . $table . "`";
763                 switch ($type) {
764                         case self::RENAME_COLUMN:
765                                 if (!self::existsColumn($table, array_keys($columns))) {
766                                         return false;
767                                 }
768                                 $sql .= implode(',', array_map(
769                                         function ($to, $from) {
770                                                 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
771                                         },
772                                         $columns,
773                                         array_keys($columns)
774                                 ));
775                                 break;
776                         case self::RENAME_PRIMARY_KEY:
777                                 if (!self::existsColumn($table, $columns)) {
778                                         return false;
779                                 }
780                                 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
781                                 break;
782                         default:
783                                 return false;
784                 }
785
786                 $sql .= ";";
787
788                 $stmt = DBA::p($sql);
789
790                 if (is_bool($stmt)) {
791                         $retval = $stmt;
792                 } else {
793                         $retval = true;
794                 }
795
796                 DBA::close($stmt);
797
798                 return $retval;
799         }
800
801         /**
802          *    Check if the columns of the table exists
803          *
804          * @param string $table   Table name
805          * @param array  $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
806          *
807          * @return boolean Does the table exist?
808          * @throws Exception
809          */
810         public static function existsColumn($table, $columns = [])
811         {
812                 if (empty($table)) {
813                         return false;
814                 }
815
816                 if (is_null($columns) || empty($columns)) {
817                         return self::existsTable($table);
818                 }
819
820                 $table = DBA::escape($table);
821
822                 foreach ($columns AS $column) {
823                         $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
824
825                         $stmt = DBA::p($sql);
826
827                         if (is_bool($stmt)) {
828                                 $retval = $stmt;
829                         } else {
830                                 $retval = (DBA::numRows($stmt) > 0);
831                         }
832
833                         DBA::close($stmt);
834
835                         if (!$retval) {
836                                 return false;
837                         }
838                 }
839
840                 return true;
841         }
842
843         /**
844          *    Check if a table exists
845          *
846          * @param string|array $table Table name
847          *
848          * @return boolean Does the table exist?
849          * @throws Exception
850          */
851         public static function existsTable($table)
852         {
853                 if (empty($table)) {
854                         return false;
855                 }
856
857                 if (is_array($table)) {
858                         $condition = ['table_schema' => key($table), 'table_name' => current($table)];
859                 } else {
860                         $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
861                 }
862
863                 $result = DBA::exists(['information_schema' => 'tables'], $condition);
864
865                 return $result;
866         }
867
868         /**
869          * Returns the columns of a table
870          *
871          * @param string $table Table name
872          *
873          * @return array An array of the table columns
874          * @throws Exception
875          */
876         public static function getColumns($table)
877         {
878                 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
879                 return DBA::toArray($stmtColumns);
880         }
881 }