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;
15 require_once 'include/dba.php';
18 * @brief This class contain functions for the database management
20 * This class contains functions that doesn't need to know if pdo, mysqli or whatever is used.
24 const UPDATE_NOT_CHECKED = 0; // Database check wasn't executed before
25 const UPDATE_SUCCESSFUL = 1; // Database check was successful
26 const UPDATE_FAILED = 2; // Database check failed
28 const RENAME_COLUMN = 0;
29 const RENAME_PRIMARY_KEY = 1;
32 * Database structure definition loaded from config/dbstructure.config.php
36 private static $definition = [];
39 * Converts all tables from MyISAM to InnoDB
41 public static function convertToInnoDB()
43 $r = q("SELECT `TABLE_NAME` FROM `information_schema`.`tables` WHERE `engine` = 'MyISAM' AND `table_schema` = '%s'",
44 DBA::escape(DBA::databaseName()));
46 if (!DBA::isResult($r)) {
47 echo L10n::t('There are no tables on MyISAM.') . "\n";
51 foreach ($r AS $table) {
52 $sql = sprintf("ALTER TABLE `%s` engine=InnoDB;", DBA::escape($table['TABLE_NAME']));
55 $result = DBA::e($sql);
56 if (!DBA::isResult($result)) {
57 self::printUpdateError($sql);
63 * @brief Print out database error messages
65 * @param string $message Message to be added to the error message
67 * @return string Error message
69 private static function printUpdateError($message)
71 echo L10n::t("\nError %d occurred during database update:\n%s\n",
72 DBA::errorNo(), DBA::errorMessage());
74 return L10n::t('Errors encountered performing database changes: ') . $message . EOL;
77 public static function printStructure()
79 $database = self::definition(false);
81 echo "-- ------------------------------------------\n";
82 echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n";
83 echo "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
84 echo "-- ------------------------------------------\n\n\n";
85 foreach ($database AS $name => $structure) {
87 echo "-- TABLE $name\n";
89 self::createTable($name, $structure, true, false);
96 * Loads the database structure definition from the config/dbstructure.config.php file.
97 * On first pass, defines DB_UPDATE_VERSION constant.
99 * @see config/dbstructure.config.php
100 * @param boolean $with_addons_structure Whether to tack on addons additional tables
104 public static function definition($with_addons_structure = true)
106 if (!self::$definition) {
107 $a = \Friendica\BaseObject::getApp();
109 $filename = $a->getBasePath() . '/config/dbstructure.config.php';
111 if (!is_readable($filename)) {
112 throw new Exception('Missing database structure config file config/dbstructure.config.php');
115 $definition = require $filename;
118 throw new Exception('Corrupted database structure config file config/dbstructure.config.php');
121 self::$definition = $definition;
123 $definition = self::$definition;
126 if ($with_addons_structure) {
127 Hook::callAll('dbstructure_definition', $definition);
133 private static function createTable($name, $structure, $verbose, $action)
141 foreach ($structure["fields"] AS $fieldname => $field) {
142 $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
143 if (!empty($field['primary'])) {
144 $primary_keys[] = $fieldname;
148 if (!empty($structure["indexes"])) {
149 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
150 $sql_index = self::createIndex($indexname, $fieldnames, "");
151 if (!is_null($sql_index)) {
152 $sql_rows[] = $sql_index;
157 if (isset($structure["engine"])) {
158 $engine = " ENGINE=" . $structure["engine"];
161 if (isset($structure["comment"])) {
162 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
165 $sql = implode(",\n\t", $sql_rows);
167 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
168 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
180 private static function FieldCommand($parameters, $create = true)
182 $fieldstruct = $parameters["type"];
184 if (isset($parameters["Collation"])) {
185 $fieldstruct .= " COLLATE " . $parameters["Collation"];
188 if (isset($parameters["not null"])) {
189 $fieldstruct .= " NOT NULL";
192 if (isset($parameters["default"])) {
193 if (strpos(strtolower($parameters["type"]), "int") !== false) {
194 $fieldstruct .= " DEFAULT " . $parameters["default"];
196 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
199 if (isset($parameters["extra"])) {
200 $fieldstruct .= " " . $parameters["extra"];
203 if (isset($parameters["comment"])) {
204 $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
207 /*if (($parameters["primary"] != "") && $create)
208 $fieldstruct .= " PRIMARY KEY";*/
210 return ($fieldstruct);
213 private static function createIndex($indexname, $fieldnames, $method = "ADD")
215 $method = strtoupper(trim($method));
216 if ($method != "" && $method != "ADD") {
217 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
220 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
221 $index_type = array_shift($fieldnames);
222 $method .= " " . $index_type;
226 foreach ($fieldnames AS $fieldname) {
231 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
232 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
234 $names .= "`" . DBA::escape($fieldname) . "`";
238 if ($indexname == "PRIMARY") {
239 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
243 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
248 * Updates DB structure and returns eventual errors messages
250 * @param bool $verbose
251 * @param bool $action Whether to actually apply the update
252 * @param bool $install Is this the initial update during the installation?
253 * @param array $tables An array of the database tables
254 * @param array $definition An array of the definition tables
255 * @return string Empty string if the update is successful, error messages otherwise
258 public static function update($verbose, $action, $install = false, array $tables = null, array $definition = null)
260 if ($action && !$install) {
261 Config::set('system', 'maintenance', 1);
262 Config::set('system', 'maintenance_reason', L10n::t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
267 Logger::log('updating structure', Logger::DEBUG);
269 // Get the current structure
272 if (is_null($tables)) {
273 $tables = q("SHOW TABLES");
276 if (DBA::isResult($tables)) {
277 foreach ($tables AS $table) {
278 $table = current($table);
280 Logger::log(sprintf('updating structure for table %s ...', $table), Logger::DEBUG);
281 $database[$table] = self::tableStructure($table);
285 // Get the definition
286 if (is_null($definition)) {
287 $definition = self::definition();
290 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
291 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
292 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
299 foreach ($definition AS $name => $structure) {
300 $is_new_table = false;
305 if (!isset($database[$name])) {
306 $r = self::createTable($name, $structure, $verbose, $action);
307 if (!DBA::isResult($r)) {
308 $errors .= self::printUpdateError($name);
310 $is_new_table = true;
312 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
313 if (isset($database[$name]["indexes"][$indexname])) {
314 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
316 $current_index_definition = "__NOT_SET__";
318 $new_index_definition = implode(",", $fieldnames);
319 if ($current_index_definition != $new_index_definition) {
320 if ($fieldnames[0] == "UNIQUE") {
323 $temp_name = "temp-" . $name;
330 * Drop the index if it isn't present in the definition
331 * or the definition differ from current status
332 * and index name doesn't start with "local_"
334 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
335 $current_index_definition = implode(",", $fieldnames);
336 if (isset($structure["indexes"][$indexname])) {
337 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
339 $new_index_definition = "__NOT_SET__";
341 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
342 $sql2 = self::dropIndex($indexname);
344 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
346 $sql3 .= ", " . $sql2;
350 // Compare the field structure field by field
351 foreach ($structure["fields"] AS $fieldname => $parameters) {
352 if (!isset($database[$name]["fields"][$fieldname])) {
353 $sql2 = self::addTableField($fieldname, $parameters);
355 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
357 $sql3 .= ", " . $sql2;
360 // Compare the field definition
361 $field_definition = $database[$name]["fields"][$fieldname];
363 // Remove the relation data that is used for the referential integrity
364 unset($parameters['relation']);
366 // We change the collation after the indexes had been changed.
367 // This is done to avoid index length problems.
368 // So here we always ensure that there is no need to change it.
369 unset($parameters['Collation']);
370 unset($field_definition['Collation']);
372 // Only update the comment when it is defined
373 if (!isset($parameters['comment'])) {
374 $parameters['comment'] = "";
377 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
378 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
379 if ($current_field_definition != $new_field_definition) {
380 $sql2 = self::modifyTableField($fieldname, $parameters);
382 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
384 $sql3 .= ", " . $sql2;
392 * Create the index if the index don't exists in database
393 * or the definition differ from the current status.
394 * Don't create keys if table is new
396 if (!$is_new_table) {
397 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
398 if (isset($database[$name]["indexes"][$indexname])) {
399 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
401 $current_index_definition = "__NOT_SET__";
403 $new_index_definition = implode(",", $fieldnames);
404 if ($current_index_definition != $new_index_definition) {
405 $sql2 = self::createIndex($indexname, $fieldnames);
407 // Fetch the "group by" fields for unique indexes
408 $group_by = self::groupBy($fieldnames);
411 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
413 $sql3 .= ", " . $sql2;
419 if (isset($database[$name]["table_status"]["Comment"])) {
420 $structurecomment = defaults($structure, "comment", "");
421 if ($database[$name]["table_status"]["Comment"] != $structurecomment) {
422 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
425 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
427 $sql3 .= ", " . $sql2;
432 if (isset($database[$name]["table_status"]["Engine"]) && isset($structure['engine'])) {
433 if ($database[$name]["table_status"]["Engine"] != $structure['engine']) {
434 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
437 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
439 $sql3 .= ", " . $sql2;
444 if (isset($database[$name]["table_status"]["Collation"])) {
445 if ($database[$name]["table_status"]["Collation"] != 'utf8mb4_general_ci') {
446 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
449 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
451 $sql3 .= ", " . $sql2;
460 // Now have a look at the field collations
461 // Compare the field structure field by field
462 foreach ($structure["fields"] AS $fieldname => $parameters) {
463 // Compare the field definition
464 $field_definition = defaults($database[$name]["fields"], $fieldname, ['Collation' => '']);
466 // Define the default collation if not given
467 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
468 $parameters['Collation'] = 'utf8mb4_general_ci';
470 $parameters['Collation'] = null;
473 if ($field_definition['Collation'] != $parameters['Collation']) {
474 $sql2 = self::modifyTableField($fieldname, $parameters);
475 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
476 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
478 $sql3 .= ", " . $sql2;
485 if (substr($sql3, -2, 2) != "; ") {
490 if ($is_unique && $ignore == '') {
491 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
492 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
494 $field_list = rtrim($field_list, ',');
498 // Ensure index conversion to unique removes duplicates
499 if ($is_unique && ($temp_name != $name)) {
501 echo "SET session old_alter_table=1;\n";
503 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
504 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
510 if ($is_unique && ($temp_name != $name)) {
512 echo "SET session old_alter_table=0;\n";
514 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
515 echo "DROP TABLE `" . $name . "`;\n";
516 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
523 Config::set('system', 'maintenance_reason', L10n::t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
526 // Ensure index conversion to unique removes duplicates
527 if ($is_unique && ($temp_name != $name)) {
529 DBA::e("SET session old_alter_table=1;");
531 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
532 if (!DBA::isResult($r)) {
533 $errors .= self::printUpdateError($sql3);
537 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
538 if (!DBA::isResult($r)) {
539 $errors .= self::printUpdateError($sql3);
546 if (!DBA::isResult($r)) {
547 $errors .= self::printUpdateError($sql3);
549 if ($is_unique && ($temp_name != $name)) {
551 DBA::e("SET session old_alter_table=0;");
553 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
554 if (!DBA::isResult($r)) {
555 $errors .= self::printUpdateError($sql3);
558 $r = DBA::e("DROP TABLE `" . $name . "`;");
559 if (!DBA::isResult($r)) {
560 $errors .= self::printUpdateError($sql3);
563 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
564 if (!DBA::isResult($r)) {
565 $errors .= self::printUpdateError($sql3);
574 if ($action && !$install) {
575 Config::set('system', 'maintenance', 0);
576 Config::set('system', 'maintenance_reason', '');
579 Config::set('system', 'dbupdate', self::UPDATE_FAILED);
581 Config::set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
588 private static function tableStructure($table)
590 $structures = q("DESCRIBE `%s`", $table);
592 $full_columns = q("SHOW FULL COLUMNS FROM `%s`", $table);
594 $indexes = q("SHOW INDEX FROM `%s`", $table);
596 $table_status = q("SHOW TABLE STATUS WHERE `name` = '%s'", $table);
598 if (DBA::isResult($table_status)) {
599 $table_status = $table_status[0];
607 if (DBA::isResult($indexes)) {
608 foreach ($indexes AS $index) {
609 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
610 $indexdata[$index["Key_name"]] = ["UNIQUE"];
613 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
614 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
617 $column = $index["Column_name"];
619 if ($index["Sub_part"] != "") {
620 $column .= "(" . $index["Sub_part"] . ")";
623 $indexdata[$index["Key_name"]][] = $column;
626 if (DBA::isResult($structures)) {
627 foreach ($structures AS $field) {
628 // Replace the default size values so that we don't have to define them
629 $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)'];
630 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
631 $field["Type"] = str_replace($search, $replace, $field["Type"]);
633 $fielddata[$field["Field"]]["type"] = $field["Type"];
634 if ($field["Null"] == "NO") {
635 $fielddata[$field["Field"]]["not null"] = true;
638 if (isset($field["Default"])) {
639 $fielddata[$field["Field"]]["default"] = $field["Default"];
642 if ($field["Extra"] != "") {
643 $fielddata[$field["Field"]]["extra"] = $field["Extra"];
646 if ($field["Key"] == "PRI") {
647 $fielddata[$field["Field"]]["primary"] = true;
651 if (DBA::isResult($full_columns)) {
652 foreach ($full_columns AS $column) {
653 $fielddata[$column["Field"]]["Collation"] = $column["Collation"];
654 $fielddata[$column["Field"]]["comment"] = $column["Comment"];
658 return ["fields" => $fielddata, "indexes" => $indexdata, "table_status" => $table_status];
661 private static function dropIndex($indexname)
663 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
667 private static function addTableField($fieldname, $parameters)
669 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
673 private static function modifyTableField($fieldname, $parameters)
675 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
680 * Constructs a GROUP BY clause from a UNIQUE index definition.
682 * @param array $fieldnames
685 private static function groupBy(array $fieldnames)
687 if ($fieldnames[0] != "UNIQUE") {
691 array_shift($fieldnames);
694 foreach ($fieldnames AS $fieldname) {
699 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
700 $names .= "`" . DBA::escape($matches[1]) . "`";
702 $names .= "`" . DBA::escape($fieldname) . "`";
706 $sql = sprintf(" GROUP BY %s", $names);
711 * Renames columns or the primary key of a table
713 * @todo You cannot rename a primary key if "auto increment" is set
715 * @param string $table Table name
716 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ] )
717 * Syntax for Primary Key: [ $col1, $col2, ...] )
718 * @param int $type The type of renaming (Default is Column)
720 * @return boolean Was the renaming successful?
723 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
725 if (empty($table) || empty($columns)) {
729 if (!is_array($columns)) {
733 $table = DBA::escape($table);
735 $sql = "ALTER TABLE `" . $table . "`";
737 case self::RENAME_COLUMN:
738 if (!self::existsColumn($table, array_keys($columns))) {
741 $sql .= implode(',', array_map(
742 function ($to, $from) {
743 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
749 case self::RENAME_PRIMARY_KEY:
750 if (!self::existsColumn($table, $columns)) {
753 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
761 $stmt = DBA::p($sql);
763 if (is_bool($stmt)) {
775 * Check if the columns of the table exists
777 * @param string $table Table name
778 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
780 * @return boolean Does the table exist?
783 public static function existsColumn($table, $columns = [])
789 if (is_null($columns) || empty($columns)) {
790 return self::existsTable($table);
793 $table = DBA::escape($table);
795 foreach ($columns AS $column) {
796 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
798 $stmt = DBA::p($sql);
800 if (is_bool($stmt)) {
803 $retval = (DBA::numRows($stmt) > 0);
817 * Check if a table exists
819 * @param string $table Table name
821 * @return boolean Does the table exist?
824 public static function existsTable($table)
830 $table = DBA::escape($table);
832 $sql = "SHOW TABLES LIKE '" . $table . "';";
834 $stmt = DBA::p($sql);
836 if (is_bool($stmt)) {
839 $retval = (DBA::numRows($stmt) > 0);