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