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