3 * @file src/Database/DBStructure.php
6 namespace Friendica\Database;
9 use Friendica\Core\Config;
10 use Friendica\Core\Hook;
11 use Friendica\Core\L10n;
12 use Friendica\Core\Logger;
13 use Friendica\Util\DateTimeFormat;
16 * @brief This class contain functions for the database management
18 * This class contains functions that doesn't need to know if pdo, mysqli or whatever is used.
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
26 const RENAME_COLUMN = 0;
27 const RENAME_PRIMARY_KEY = 1;
30 * Database structure definition loaded from config/dbstructure.config.php
34 private static $definition = [];
37 * Converts all tables from MyISAM to InnoDB
39 public static function convertToInnoDB()
41 $r = q("SELECT `TABLE_NAME` FROM `information_schema`.`tables` WHERE `engine` = 'MyISAM' AND `table_schema` = '%s'",
42 DBA::escape(DBA::databaseName()));
44 if (!DBA::isResult($r)) {
45 echo L10n::t('There are no tables on MyISAM.') . "\n";
49 foreach ($r AS $table) {
50 $sql = sprintf("ALTER TABLE `%s` engine=InnoDB;", DBA::escape($table['TABLE_NAME']));
53 $result = DBA::e($sql);
54 if (!DBA::isResult($result)) {
55 self::printUpdateError($sql);
61 * @brief Print out database error messages
63 * @param string $message Message to be added to the error message
65 * @return string Error message
67 private static function printUpdateError($message)
69 echo L10n::t("\nError %d occurred during database update:\n%s\n",
70 DBA::errorNo(), DBA::errorMessage());
72 return L10n::t('Errors encountered performing database changes: ') . $message . EOL;
75 public static function printStructure()
77 $database = self::definition(false);
79 echo "-- ------------------------------------------\n";
80 echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n";
81 echo "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
82 echo "-- ------------------------------------------\n\n\n";
83 foreach ($database AS $name => $structure) {
85 echo "-- TABLE $name\n";
87 self::createTable($name, $structure, true, false);
94 * Loads the database structure definition from the config/dbstructure.config.php file.
95 * On first pass, defines DB_UPDATE_VERSION constant.
97 * @see config/dbstructure.config.php
98 * @param boolean $with_addons_structure Whether to tack on addons additional tables
102 public static function definition($with_addons_structure = true)
104 if (!self::$definition) {
105 $a = \Friendica\BaseObject::getApp();
107 $filename = $a->getBasePath() . '/config/dbstructure.config.php';
109 if (!is_readable($filename)) {
110 throw new Exception('Missing database structure config file config/dbstructure.config.php');
113 $definition = require $filename;
116 throw new Exception('Corrupted database structure config file config/dbstructure.config.php');
119 self::$definition = $definition;
121 $definition = self::$definition;
124 if ($with_addons_structure) {
125 Hook::callAll('dbstructure_definition', $definition);
131 private static function createTable($name, $structure, $verbose, $action)
139 foreach ($structure["fields"] AS $fieldname => $field) {
140 $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
141 if (!empty($field['primary'])) {
142 $primary_keys[] = $fieldname;
146 if (!empty($structure["indexes"])) {
147 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
148 $sql_index = self::createIndex($indexname, $fieldnames, "");
149 if (!is_null($sql_index)) {
150 $sql_rows[] = $sql_index;
155 if (isset($structure["engine"])) {
156 $engine = " ENGINE=" . $structure["engine"];
159 if (isset($structure["comment"])) {
160 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
163 $sql = implode(",\n\t", $sql_rows);
165 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
166 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
178 private static function FieldCommand($parameters, $create = true)
180 $fieldstruct = $parameters["type"];
182 if (isset($parameters["Collation"])) {
183 $fieldstruct .= " COLLATE " . $parameters["Collation"];
186 if (isset($parameters["not null"])) {
187 $fieldstruct .= " NOT NULL";
190 if (isset($parameters["default"])) {
191 if (strpos(strtolower($parameters["type"]), "int") !== false) {
192 $fieldstruct .= " DEFAULT " . $parameters["default"];
194 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
197 if (isset($parameters["extra"])) {
198 $fieldstruct .= " " . $parameters["extra"];
201 if (isset($parameters["comment"])) {
202 $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
205 /*if (($parameters["primary"] != "") && $create)
206 $fieldstruct .= " PRIMARY KEY";*/
208 return ($fieldstruct);
211 private static function createIndex($indexname, $fieldnames, $method = "ADD")
213 $method = strtoupper(trim($method));
214 if ($method != "" && $method != "ADD") {
215 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
218 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
219 $index_type = array_shift($fieldnames);
220 $method .= " " . $index_type;
224 foreach ($fieldnames AS $fieldname) {
229 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
230 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
232 $names .= "`" . DBA::escape($fieldname) . "`";
236 if ($indexname == "PRIMARY") {
237 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
241 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
246 * Updates DB structure and returns eventual errors messages
248 * @param bool $verbose
249 * @param bool $action Whether to actually apply the update
250 * @param bool $install Is this the initial update during the installation?
251 * @param array $tables An array of the database tables
252 * @param array $definition An array of the definition tables
253 * @return string Empty string if the update is successful, error messages otherwise
255 public static function update($verbose, $action, $install = false, array $tables = null, array $definition = null)
257 if ($action && !$install) {
258 Config::set('system', 'maintenance', 1);
259 Config::set('system', 'maintenance_reason', L10n::t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
264 Logger::log('updating structure', Logger::DEBUG);
266 // Get the current structure
269 if (is_null($tables)) {
270 $tables = q("SHOW TABLES");
273 if (DBA::isResult($tables)) {
274 foreach ($tables AS $table) {
275 $table = current($table);
277 Logger::log(sprintf('updating structure for table %s ...', $table), Logger::DEBUG);
278 $database[$table] = self::tableStructure($table);
282 // Get the definition
283 if (is_null($definition)) {
284 $definition = self::definition();
287 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
288 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
289 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
296 foreach ($definition AS $name => $structure) {
297 $is_new_table = false;
302 if (!isset($database[$name])) {
303 $r = self::createTable($name, $structure, $verbose, $action);
304 if (!DBA::isResult($r)) {
305 $errors .= self::printUpdateError($name);
307 $is_new_table = true;
309 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
310 if (isset($database[$name]["indexes"][$indexname])) {
311 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
313 $current_index_definition = "__NOT_SET__";
315 $new_index_definition = implode(",", $fieldnames);
316 if ($current_index_definition != $new_index_definition) {
317 if ($fieldnames[0] == "UNIQUE") {
320 $temp_name = "temp-" . $name;
327 * Drop the index if it isn't present in the definition
328 * or the definition differ from current status
329 * and index name doesn't start with "local_"
331 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
332 $current_index_definition = implode(",", $fieldnames);
333 if (isset($structure["indexes"][$indexname])) {
334 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
336 $new_index_definition = "__NOT_SET__";
338 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
339 $sql2 = self::dropIndex($indexname);
341 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
343 $sql3 .= ", " . $sql2;
347 // Compare the field structure field by field
348 foreach ($structure["fields"] AS $fieldname => $parameters) {
349 if (!isset($database[$name]["fields"][$fieldname])) {
350 $sql2 = self::addTableField($fieldname, $parameters);
352 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
354 $sql3 .= ", " . $sql2;
357 // Compare the field definition
358 $field_definition = $database[$name]["fields"][$fieldname];
360 // Remove the relation data that is used for the referential integrity
361 unset($parameters['relation']);
363 // We change the collation after the indexes had been changed.
364 // This is done to avoid index length problems.
365 // So here we always ensure that there is no need to change it.
366 unset($parameters['Collation']);
367 unset($field_definition['Collation']);
369 // Only update the comment when it is defined
370 if (!isset($parameters['comment'])) {
371 $parameters['comment'] = "";
374 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
375 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
376 if ($current_field_definition != $new_field_definition) {
377 $sql2 = self::modifyTableField($fieldname, $parameters);
379 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
381 $sql3 .= ", " . $sql2;
389 * Create the index if the index don't exists in database
390 * or the definition differ from the current status.
391 * Don't create keys if table is new
393 if (!$is_new_table) {
394 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
395 if (isset($database[$name]["indexes"][$indexname])) {
396 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
398 $current_index_definition = "__NOT_SET__";
400 $new_index_definition = implode(",", $fieldnames);
401 if ($current_index_definition != $new_index_definition) {
402 $sql2 = self::createIndex($indexname, $fieldnames);
404 // Fetch the "group by" fields for unique indexes
405 $group_by = self::groupBy($fieldnames);
408 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
410 $sql3 .= ", " . $sql2;
416 if (isset($database[$name]["table_status"]["Comment"])) {
417 $structurecomment = defaults($structure, "comment", "");
418 if ($database[$name]["table_status"]["Comment"] != $structurecomment) {
419 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
422 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
424 $sql3 .= ", " . $sql2;
429 if (isset($database[$name]["table_status"]["Engine"]) && isset($structure['engine'])) {
430 if ($database[$name]["table_status"]["Engine"] != $structure['engine']) {
431 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
434 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
436 $sql3 .= ", " . $sql2;
441 if (isset($database[$name]["table_status"]["Collation"])) {
442 if ($database[$name]["table_status"]["Collation"] != 'utf8mb4_general_ci') {
443 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
446 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
448 $sql3 .= ", " . $sql2;
457 // Now have a look at the field collations
458 // Compare the field structure field by field
459 foreach ($structure["fields"] AS $fieldname => $parameters) {
460 // Compare the field definition
461 $field_definition = defaults($database[$name]["fields"], $fieldname, ['Collation' => '']);
463 // Define the default collation if not given
464 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
465 $parameters['Collation'] = 'utf8mb4_general_ci';
467 $parameters['Collation'] = null;
470 if ($field_definition['Collation'] != $parameters['Collation']) {
471 $sql2 = self::modifyTableField($fieldname, $parameters);
472 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
473 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
475 $sql3 .= ", " . $sql2;
482 if (substr($sql3, -2, 2) != "; ") {
487 if ($is_unique && $ignore == '') {
488 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
489 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
491 $field_list = rtrim($field_list, ',');
495 // Ensure index conversion to unique removes duplicates
496 if ($is_unique && ($temp_name != $name)) {
498 echo "SET session old_alter_table=1;\n";
500 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
501 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
507 if ($is_unique && ($temp_name != $name)) {
509 echo "SET session old_alter_table=0;\n";
511 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
512 echo "DROP TABLE `" . $name . "`;\n";
513 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
520 Config::set('system', 'maintenance_reason', L10n::t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
523 // Ensure index conversion to unique removes duplicates
524 if ($is_unique && ($temp_name != $name)) {
526 DBA::e("SET session old_alter_table=1;");
528 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
529 if (!DBA::isResult($r)) {
530 $errors .= self::printUpdateError($sql3);
534 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
535 if (!DBA::isResult($r)) {
536 $errors .= self::printUpdateError($sql3);
543 if (!DBA::isResult($r)) {
544 $errors .= self::printUpdateError($sql3);
546 if ($is_unique && ($temp_name != $name)) {
548 DBA::e("SET session old_alter_table=0;");
550 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
551 if (!DBA::isResult($r)) {
552 $errors .= self::printUpdateError($sql3);
555 $r = DBA::e("DROP TABLE `" . $name . "`;");
556 if (!DBA::isResult($r)) {
557 $errors .= self::printUpdateError($sql3);
560 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
561 if (!DBA::isResult($r)) {
562 $errors .= self::printUpdateError($sql3);
571 if ($action && !$install) {
572 Config::set('system', 'maintenance', 0);
573 Config::set('system', 'maintenance_reason', '');
576 Config::set('system', 'dbupdate', self::UPDATE_FAILED);
578 Config::set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
585 private static function tableStructure($table)
587 $structures = q("DESCRIBE `%s`", $table);
589 $full_columns = q("SHOW FULL COLUMNS FROM `%s`", $table);
591 $indexes = q("SHOW INDEX FROM `%s`", $table);
593 $table_status = q("SHOW TABLE STATUS WHERE `name` = '%s'", $table);
595 if (DBA::isResult($table_status)) {
596 $table_status = $table_status[0];
604 if (DBA::isResult($indexes)) {
605 foreach ($indexes AS $index) {
606 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
607 $indexdata[$index["Key_name"]] = ["UNIQUE"];
610 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
611 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
614 $column = $index["Column_name"];
616 if ($index["Sub_part"] != "") {
617 $column .= "(" . $index["Sub_part"] . ")";
620 $indexdata[$index["Key_name"]][] = $column;
623 if (DBA::isResult($structures)) {
624 foreach ($structures AS $field) {
625 // Replace the default size values so that we don't have to define them
626 $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)'];
627 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
628 $field["Type"] = str_replace($search, $replace, $field["Type"]);
630 $fielddata[$field["Field"]]["type"] = $field["Type"];
631 if ($field["Null"] == "NO") {
632 $fielddata[$field["Field"]]["not null"] = true;
635 if (isset($field["Default"])) {
636 $fielddata[$field["Field"]]["default"] = $field["Default"];
639 if ($field["Extra"] != "") {
640 $fielddata[$field["Field"]]["extra"] = $field["Extra"];
643 if ($field["Key"] == "PRI") {
644 $fielddata[$field["Field"]]["primary"] = true;
648 if (DBA::isResult($full_columns)) {
649 foreach ($full_columns AS $column) {
650 $fielddata[$column["Field"]]["Collation"] = $column["Collation"];
651 $fielddata[$column["Field"]]["comment"] = $column["Comment"];
655 return ["fields" => $fielddata, "indexes" => $indexdata, "table_status" => $table_status];
658 private static function dropIndex($indexname)
660 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
664 private static function addTableField($fieldname, $parameters)
666 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
670 private static function modifyTableField($fieldname, $parameters)
672 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
677 * Constructs a GROUP BY clause from a UNIQUE index definition.
679 * @param array $fieldnames
682 private static function groupBy(array $fieldnames)
684 if ($fieldnames[0] != "UNIQUE") {
688 array_shift($fieldnames);
691 foreach ($fieldnames AS $fieldname) {
696 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
697 $names .= "`" . DBA::escape($matches[1]) . "`";
699 $names .= "`" . DBA::escape($fieldname) . "`";
703 $sql = sprintf(" GROUP BY %s", $names);
708 * Renames columns or the primary key of a table
710 * @todo You cannot rename a primary key if "auto increment" is set
712 * @param string $table Table name
713 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ] )
714 * Syntax for Primary Key: [ $col1, $col2, ...] )
715 * @param int $type The type of renaming (Default is Column)
717 * @return boolean Was the renaming successful?
720 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
722 if (empty($table) || empty($columns)) {
726 if (!is_array($columns)) {
730 $table = DBA::escape($table);
732 $sql = "ALTER TABLE `" . $table . "`";
734 case self::RENAME_COLUMN:
735 if (!self::existsColumn($table, array_keys($columns))) {
738 $sql .= implode(',', array_map(
739 function ($to, $from) {
740 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
746 case self::RENAME_PRIMARY_KEY:
747 if (!self::existsColumn($table, $columns)) {
750 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
758 $stmt = DBA::p($sql);
760 if (is_bool($stmt)) {
772 * Check if the columns of the table exists
774 * @param string $table Table name
775 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
777 * @return boolean Does the table exist?
779 public static function existsColumn($table, $columns = [])
785 if (is_null($columns) || empty($columns)) {
786 return self::existsTable($table);
789 $table = DBA::escape($table);
791 foreach ($columns AS $column) {
792 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
794 $stmt = DBA::p($sql);
796 if (is_bool($stmt)) {
799 $retval = (DBA::numRows($stmt) > 0);
813 * Check if a table exists
815 * @param string $table Table name
817 * @return boolean Does the table exist?
819 public static function existsTable($table)
825 $table = DBA::escape($table);
827 $sql = "SHOW TABLES LIKE '" . $table . "';";
829 $stmt = DBA::p($sql);
831 if (is_bool($stmt)) {
834 $retval = (DBA::numRows($stmt) > 0);