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