3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Database;
25 use Friendica\Core\Hook;
26 use Friendica\Core\Logger;
28 use Friendica\Util\DateTimeFormat;
30 require_once __DIR__ . '/../../include/dba.php';
33 * This class contains functions that doesn't need to know if pdo, mysqli or whatever is used.
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
41 const RENAME_COLUMN = 0;
42 const RENAME_PRIMARY_KEY = 1;
45 * Database structure definition loaded from config/dbstructure.config.php
49 private static $definition = [];
52 * Converts all tables from MyISAM/InnoDB Antelope to InnoDB Barracuda
54 public static function convertToInnoDB()
56 $tables = DBA::selectToArray(
57 ['information_schema' => 'tables'],
59 ['engine' => 'MyISAM', 'table_schema' => DBA::databaseName()]
62 $tables = array_merge($tables, DBA::selectToArray(
63 ['information_schema' => 'tables'],
65 ['engine' => 'InnoDB', 'ROW_FORMAT' => ['COMPACT', 'REDUNDANT'], 'table_schema' => DBA::databaseName()]
68 if (!DBA::isResult($tables)) {
69 echo DI::l10n()->t('There are no tables on MyISAM or InnoDB with the Antelope file format.') . "\n";
73 foreach ($tables AS $table) {
74 $sql = "ALTER TABLE " . DBA::quoteIdentifier($table['table_name']) . " ENGINE=InnoDB ROW_FORMAT=DYNAMIC;";
77 $result = DBA::e($sql);
78 if (!DBA::isResult($result)) {
79 self::printUpdateError($sql);
85 * Print out database error messages
87 * @param string $message Message to be added to the error message
89 * @return string Error message
91 private static function printUpdateError($message)
93 echo DI::l10n()->t("\nError %d occurred during database update:\n%s\n",
94 DBA::errorNo(), DBA::errorMessage());
96 return DI::l10n()->t('Errors encountered performing database changes: ') . $message . EOL;
99 public static function printStructure($basePath)
101 $database = self::definition($basePath, false);
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) {
109 echo "-- TABLE $name\n";
111 self::createTable($name, $structure, true, false);
116 View::printStructure($basePath);
120 * Loads the database structure definition from the static/dbstructure.config.php file.
121 * On first pass, defines DB_UPDATE_VERSION constant.
123 * @see static/dbstructure.config.php
124 * @param boolean $with_addons_structure Whether to tack on addons additional tables
125 * @param string $basePath The base path of this application
129 public static function definition($basePath, $with_addons_structure = true)
131 if (!self::$definition) {
133 $filename = $basePath . '/static/dbstructure.config.php';
135 if (!is_readable($filename)) {
136 throw new Exception('Missing database structure config file static/dbstructure.config.php');
139 $definition = require $filename;
142 throw new Exception('Corrupted database structure config file static/dbstructure.config.php');
145 self::$definition = $definition;
147 $definition = self::$definition;
150 if ($with_addons_structure) {
151 Hook::callAll('dbstructure_definition', $definition);
157 private static function createTable($name, $structure, $verbose, $action)
167 foreach ($structure["fields"] AS $fieldname => $field) {
168 $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
169 if (!empty($field['primary'])) {
170 $primary_keys[] = $fieldname;
172 if (!empty($field['foreign'])) {
173 $foreign_keys[$fieldname] = $field;
177 if (!empty($structure["indexes"])) {
178 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
179 $sql_index = self::createIndex($indexname, $fieldnames, "");
180 if (!is_null($sql_index)) {
181 $sql_rows[] = $sql_index;
186 foreach ($foreign_keys AS $fieldname => $parameters) {
187 $sql_rows[] = self::foreignCommand($name, $fieldname, $parameters);
190 if (isset($structure["engine"])) {
191 $engine = " ENGINE=" . $structure["engine"];
194 if (isset($structure["comment"])) {
195 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
198 $sql = implode(",\n\t", $sql_rows);
200 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
201 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
213 private static function FieldCommand($parameters, $create = true)
215 $fieldstruct = $parameters["type"];
217 if (isset($parameters["Collation"])) {
218 $fieldstruct .= " COLLATE " . $parameters["Collation"];
221 if (isset($parameters["not null"])) {
222 $fieldstruct .= " NOT NULL";
225 if (isset($parameters["default"])) {
226 if (strpos(strtolower($parameters["type"]), "int") !== false) {
227 $fieldstruct .= " DEFAULT " . $parameters["default"];
229 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
232 if (isset($parameters["extra"])) {
233 $fieldstruct .= " " . $parameters["extra"];
236 if (isset($parameters["comment"])) {
237 $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
240 /*if (($parameters["primary"] != "") && $create)
241 $fieldstruct .= " PRIMARY KEY";*/
243 return ($fieldstruct);
246 private static function createIndex($indexname, $fieldnames, $method = "ADD")
248 $method = strtoupper(trim($method));
249 if ($method != "" && $method != "ADD") {
250 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
253 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
254 $index_type = array_shift($fieldnames);
255 $method .= " " . $index_type;
259 foreach ($fieldnames AS $fieldname) {
264 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
265 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
267 $names .= "`" . DBA::escape($fieldname) . "`";
271 if ($indexname == "PRIMARY") {
272 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
276 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
281 * Updates DB structure and returns eventual errors messages
283 * @param string $basePath The base path of this application
284 * @param bool $verbose
285 * @param bool $action Whether to actually apply the update
286 * @param bool $install Is this the initial update during the installation?
287 * @param array $tables An array of the database tables
288 * @param array $definition An array of the definition tables
289 * @return string Empty string if the update is successful, error messages otherwise
292 public static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
294 if ($action && !$install) {
295 DI::config()->set('system', 'maintenance', 1);
296 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
301 Logger::log('updating structure', Logger::DEBUG);
303 // Get the current structure
306 if (is_null($tables)) {
307 $tables = DBA::toArray(DBA::p("SHOW TABLES"));
310 if (DBA::isResult($tables)) {
311 foreach ($tables AS $table) {
312 $table = current($table);
314 Logger::log(sprintf('updating structure for table %s ...', $table), Logger::DEBUG);
315 $database[$table] = self::tableStructure($table);
319 // Get the definition
320 if (is_null($definition)) {
321 $definition = self::definition($basePath);
324 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
325 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
326 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
333 foreach ($definition AS $name => $structure) {
334 $is_new_table = false;
339 if (!isset($database[$name])) {
340 $r = self::createTable($name, $structure, $verbose, $action);
341 if (!DBA::isResult($r)) {
342 $errors .= self::printUpdateError($name);
344 $is_new_table = true;
346 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
347 if (isset($database[$name]["indexes"][$indexname])) {
348 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
350 $current_index_definition = "__NOT_SET__";
352 $new_index_definition = implode(",", $fieldnames);
353 if ($current_index_definition != $new_index_definition) {
354 if ($fieldnames[0] == "UNIQUE") {
357 $temp_name = "temp-" . $name;
364 * Drop the index if it isn't present in the definition
365 * or the definition differ from current status
366 * and index name doesn't start with "local_"
368 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
369 $current_index_definition = implode(",", $fieldnames);
370 if (isset($structure["indexes"][$indexname])) {
371 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
373 $new_index_definition = "__NOT_SET__";
375 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
376 $sql2 = self::dropIndex($indexname);
378 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
380 $sql3 .= ", " . $sql2;
384 // Compare the field structure field by field
385 foreach ($structure["fields"] AS $fieldname => $parameters) {
386 if (!isset($database[$name]["fields"][$fieldname])) {
387 $sql2 = self::addTableField($fieldname, $parameters);
389 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
391 $sql3 .= ", " . $sql2;
394 // Compare the field definition
395 $field_definition = $database[$name]["fields"][$fieldname];
397 // Remove the relation data that is used for the referential integrity
398 unset($parameters['relation']);
399 unset($parameters['foreign']);
401 // We change the collation after the indexes had been changed.
402 // This is done to avoid index length problems.
403 // So here we always ensure that there is no need to change it.
404 unset($parameters['Collation']);
405 unset($field_definition['Collation']);
407 // Only update the comment when it is defined
408 if (!isset($parameters['comment'])) {
409 $parameters['comment'] = "";
412 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
413 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
414 if ($current_field_definition != $new_field_definition) {
415 $sql2 = self::modifyTableField($fieldname, $parameters);
417 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
419 $sql3 .= ", " . $sql2;
427 * Create the index if the index don't exists in database
428 * or the definition differ from the current status.
429 * Don't create keys if table is new
431 if (!$is_new_table) {
432 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
433 if (isset($database[$name]["indexes"][$indexname])) {
434 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
436 $current_index_definition = "__NOT_SET__";
438 $new_index_definition = implode(",", $fieldnames);
439 if ($current_index_definition != $new_index_definition) {
440 $sql2 = self::createIndex($indexname, $fieldnames);
442 // Fetch the "group by" fields for unique indexes
443 $group_by = self::groupBy($fieldnames);
446 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
448 $sql3 .= ", " . $sql2;
454 $existing_foreign_keys = $database[$name]['foreign_keys'];
457 // Compare the field structure field by field
458 foreach ($structure["fields"] AS $fieldname => $parameters) {
459 if (empty($parameters['foreign'])) {
463 $constraint = self::getConstraintName($name, $fieldname, $parameters);
465 unset($existing_foreign_keys[$constraint]);
467 if (empty($database[$name]['foreign_keys'][$constraint])) {
468 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
471 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
473 $sql3 .= ", " . $sql2;
478 foreach ($existing_foreign_keys as $constraint => $param) {
479 $sql2 = self::dropForeignKey($constraint);
482 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
484 $sql3 .= ", " . $sql2;
488 if (isset($database[$name]["table_status"]["Comment"])) {
489 $structurecomment = $structure["comment"] ?? '';
490 if ($database[$name]["table_status"]["Comment"] != $structurecomment) {
491 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
494 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
496 $sql3 .= ", " . $sql2;
501 if (isset($database[$name]["table_status"]["Engine"]) && isset($structure['engine'])) {
502 if ($database[$name]["table_status"]["Engine"] != $structure['engine']) {
503 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
506 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
508 $sql3 .= ", " . $sql2;
513 if (isset($database[$name]["table_status"]["Collation"])) {
514 if ($database[$name]["table_status"]["Collation"] != 'utf8mb4_general_ci') {
515 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
518 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
520 $sql3 .= ", " . $sql2;
529 // Now have a look at the field collations
530 // Compare the field structure field by field
531 foreach ($structure["fields"] AS $fieldname => $parameters) {
532 // Compare the field definition
533 $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
535 // Define the default collation if not given
536 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
537 $parameters['Collation'] = 'utf8mb4_general_ci';
539 $parameters['Collation'] = null;
542 if ($field_definition['Collation'] != $parameters['Collation']) {
543 $sql2 = self::modifyTableField($fieldname, $parameters);
544 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
545 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
547 $sql3 .= ", " . $sql2;
554 if (substr($sql3, -2, 2) != "; ") {
559 if ($is_unique && $ignore == '') {
560 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
561 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
563 $field_list = rtrim($field_list, ',');
567 // Ensure index conversion to unique removes duplicates
568 if ($is_unique && ($temp_name != $name)) {
570 echo "SET session old_alter_table=1;\n";
572 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
573 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
579 if ($is_unique && ($temp_name != $name)) {
581 echo "SET session old_alter_table=0;\n";
583 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
584 echo "DROP TABLE `" . $name . "`;\n";
585 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
592 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
595 // Ensure index conversion to unique removes duplicates
596 if ($is_unique && ($temp_name != $name)) {
598 DBA::e("SET session old_alter_table=1;");
600 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
601 if (!DBA::isResult($r)) {
602 $errors .= self::printUpdateError($sql3);
606 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
607 if (!DBA::isResult($r)) {
608 $errors .= self::printUpdateError($sql3);
615 if (!DBA::isResult($r)) {
616 $errors .= self::printUpdateError($sql3);
618 if ($is_unique && ($temp_name != $name)) {
620 DBA::e("SET session old_alter_table=0;");
622 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
623 if (!DBA::isResult($r)) {
624 $errors .= self::printUpdateError($sql3);
627 $r = DBA::e("DROP TABLE `" . $name . "`;");
628 if (!DBA::isResult($r)) {
629 $errors .= self::printUpdateError($sql3);
632 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
633 if (!DBA::isResult($r)) {
634 $errors .= self::printUpdateError($sql3);
643 View::create(false, $action);
645 if ($action && !$install) {
646 DI::config()->set('system', 'maintenance', 0);
647 DI::config()->set('system', 'maintenance_reason', '');
650 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
652 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
659 private static function tableStructure($table)
661 $structures = q("DESCRIBE `%s`", $table);
663 $full_columns = q("SHOW FULL COLUMNS FROM `%s`", $table);
665 $indexes = q("SHOW INDEX FROM `%s`", $table);
667 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
668 ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
669 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
670 DBA::databaseName(), $table]);
672 $table_status = q("SHOW TABLE STATUS WHERE `name` = '%s'", $table);
674 if (DBA::isResult($table_status)) {
675 $table_status = $table_status[0];
684 if (DBA::isResult($foreign_keys)) {
685 foreach ($foreign_keys as $foreign_key) {
686 $constraint = $foreign_key['CONSTRAINT_NAME'];
687 unset($foreign_key['CONSTRAINT_NAME']);
688 $foreigndata[$constraint] = $foreign_key;
692 if (DBA::isResult($indexes)) {
693 foreach ($indexes AS $index) {
694 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
695 $indexdata[$index["Key_name"]] = ["UNIQUE"];
698 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
699 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
702 $column = $index["Column_name"];
704 if ($index["Sub_part"] != "") {
705 $column .= "(" . $index["Sub_part"] . ")";
708 $indexdata[$index["Key_name"]][] = $column;
711 if (DBA::isResult($structures)) {
712 foreach ($structures AS $field) {
713 // Replace the default size values so that we don't have to define them
714 $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)'];
715 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
716 $field["Type"] = str_replace($search, $replace, $field["Type"]);
718 $fielddata[$field["Field"]]["type"] = $field["Type"];
719 if ($field["Null"] == "NO") {
720 $fielddata[$field["Field"]]["not null"] = true;
723 if (isset($field["Default"])) {
724 $fielddata[$field["Field"]]["default"] = $field["Default"];
727 if ($field["Extra"] != "") {
728 $fielddata[$field["Field"]]["extra"] = $field["Extra"];
731 if ($field["Key"] == "PRI") {
732 $fielddata[$field["Field"]]["primary"] = true;
736 if (DBA::isResult($full_columns)) {
737 foreach ($full_columns AS $column) {
738 $fielddata[$column["Field"]]["Collation"] = $column["Collation"];
739 $fielddata[$column["Field"]]["comment"] = $column["Comment"];
743 return ["fields" => $fielddata, "indexes" => $indexdata,
744 "foreign_keys" => $foreigndata, "table_status" => $table_status];
747 private static function dropIndex($indexname)
749 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
753 private static function addTableField($fieldname, $parameters)
755 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
759 private static function modifyTableField($fieldname, $parameters)
761 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
765 private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
767 $foreign_table = array_keys($parameters['foreign'])[0];
768 $foreign_field = array_values($parameters['foreign'])[0];
770 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
773 private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
774 $foreign_table = array_keys($parameters['foreign'])[0];
775 $foreign_field = array_values($parameters['foreign'])[0];
777 $constraint = self::getConstraintName($tablename, $fieldname, $parameters);
779 $sql = "CONSTRAINT `" . $constraint . "` FOREIGN KEY (`" . $fieldname . "`)" .
780 " REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
782 if (!empty($parameters['foreign']['on update'])) {
783 $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
785 $sql .= " ON UPDATE RESTRICT";
788 if (!empty($parameters['foreign']['on delete'])) {
789 $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
791 $sql .= " ON DELETE CASCADE";
797 private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
799 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
802 private static function dropForeignKey(string $constraint)
804 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
808 * Constructs a GROUP BY clause from a UNIQUE index definition.
810 * @param array $fieldnames
813 private static function groupBy(array $fieldnames)
815 if ($fieldnames[0] != "UNIQUE") {
819 array_shift($fieldnames);
822 foreach ($fieldnames AS $fieldname) {
827 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
828 $names .= "`" . DBA::escape($matches[1]) . "`";
830 $names .= "`" . DBA::escape($fieldname) . "`";
834 $sql = sprintf(" GROUP BY %s", $names);
839 * Renames columns or the primary key of a table
841 * @todo You cannot rename a primary key if "auto increment" is set
843 * @param string $table Table name
844 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
845 * Syntax for Primary Key: [ $col1, $col2, ...]
846 * @param int $type The type of renaming (Default is Column)
848 * @return boolean Was the renaming successful?
851 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
853 if (empty($table) || empty($columns)) {
857 if (!is_array($columns)) {
861 $table = DBA::escape($table);
863 $sql = "ALTER TABLE `" . $table . "`";
865 case self::RENAME_COLUMN:
866 if (!self::existsColumn($table, array_keys($columns))) {
869 $sql .= implode(',', array_map(
870 function ($to, $from) {
871 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
877 case self::RENAME_PRIMARY_KEY:
878 if (!self::existsColumn($table, $columns)) {
881 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
889 $stmt = DBA::p($sql);
891 if (is_bool($stmt)) {
903 * Check if the columns of the table exists
905 * @param string $table Table name
906 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
908 * @return boolean Does the table exist?
911 public static function existsColumn($table, $columns = [])
917 if (is_null($columns) || empty($columns)) {
918 return self::existsTable($table);
921 $table = DBA::escape($table);
923 foreach ($columns AS $column) {
924 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
926 $stmt = DBA::p($sql);
928 if (is_bool($stmt)) {
931 $retval = (DBA::numRows($stmt) > 0);
945 * Check if a table exists
947 * @param string|array $table Table name
949 * @return boolean Does the table exist?
952 public static function existsTable($table)
958 if (is_array($table)) {
959 $condition = ['table_schema' => key($table), 'table_name' => current($table)];
961 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
964 $result = DBA::exists(['information_schema' => 'tables'], $condition);
970 * Returns the columns of a table
972 * @param string $table Table name
974 * @return array An array of the table columns
977 public static function getColumns($table)
979 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
980 return DBA::toArray($stmtColumns);