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