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