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 'boot.php';
16 require_once 'include/dba.php';
17 require_once 'include/enotify.php';
18 require_once 'include/text.php';
21 * @brief This class contain functions for the database management
23 * This class contains functions that doesn't need to know if pdo, mysqli or whatever is used.
27 const UPDATE_NOT_CHECKED = 0; // Database check wasn't executed before
28 const UPDATE_SUCCESSFUL = 1; // Database check was successful
29 const UPDATE_FAILED = 2; // Database check failed
31 const RENAME_COLUMN = 0;
32 const RENAME_PRIMARY_KEY = 1;
35 * Database structure definition loaded from config/dbstructure.config.php
39 private static $definition = [];
42 * Converts all tables from MyISAM to InnoDB
44 public static function convertToInnoDB()
46 $r = q("SELECT `TABLE_NAME` FROM `information_schema`.`tables` WHERE `engine` = 'MyISAM' AND `table_schema` = '%s'",
47 DBA::escape(DBA::databaseName()));
49 if (!DBA::isResult($r)) {
50 echo L10n::t('There are no tables on MyISAM.') . "\n";
54 foreach ($r AS $table) {
55 $sql = sprintf("ALTER TABLE `%s` engine=InnoDB;", DBA::escape($table['TABLE_NAME']));
58 $result = DBA::e($sql);
59 if (!DBA::isResult($result)) {
60 self::printUpdateError($sql);
66 * @brief Print out database error messages
68 * @param string $message Message to be added to the error message
70 * @return string Error message
72 private static function printUpdateError($message)
74 echo L10n::t("\nError %d occurred during database update:\n%s\n",
75 DBA::errorNo(), DBA::errorMessage());
77 return L10n::t('Errors encountered performing database changes: ') . $message . EOL;
80 public static function printStructure()
82 $database = self::definition(false);
84 echo "-- ------------------------------------------\n";
85 echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n";
86 echo "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
87 echo "-- ------------------------------------------\n\n\n";
88 foreach ($database AS $name => $structure) {
90 echo "-- TABLE $name\n";
92 self::createTable($name, $structure, true, false);
99 * Loads the database structure definition from the config/dbstructure.config.php file.
100 * On first pass, defines DB_UPDATE_VERSION constant.
102 * @see config/dbstructure.config.php
103 * @param boolean $with_addons_structure Whether to tack on addons additional tables
107 public static function definition($with_addons_structure = true)
109 if (!self::$definition) {
110 $a = \Friendica\BaseObject::getApp();
112 $filename = $a->getBasePath() . '/config/dbstructure.config.php';
114 if (!is_readable($filename)) {
115 throw new Exception('Missing database structure config file config/dbstructure.config.php');
118 $definition = require $filename;
121 throw new Exception('Corrupted database structure config file config/dbstructure.config.php');
124 self::$definition = $definition;
126 $definition = self::$definition;
129 if ($with_addons_structure) {
130 Hook::callAll('dbstructure_definition', $definition);
136 private static function createTable($name, $structure, $verbose, $action)
144 foreach ($structure["fields"] AS $fieldname => $field) {
145 $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
146 if (!empty($field['primary'])) {
147 $primary_keys[] = $fieldname;
151 if (!empty($structure["indexes"])) {
152 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
153 $sql_index = self::createIndex($indexname, $fieldnames, "");
154 if (!is_null($sql_index)) {
155 $sql_rows[] = $sql_index;
160 if (isset($structure["engine"])) {
161 $engine = " ENGINE=" . $structure["engine"];
164 if (isset($structure["comment"])) {
165 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
168 $sql = implode(",\n\t", $sql_rows);
170 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
171 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
183 private static function FieldCommand($parameters, $create = true)
185 $fieldstruct = $parameters["type"];
187 if (isset($parameters["Collation"])) {
188 $fieldstruct .= " COLLATE " . $parameters["Collation"];
191 if (isset($parameters["not null"])) {
192 $fieldstruct .= " NOT NULL";
195 if (isset($parameters["default"])) {
196 if (strpos(strtolower($parameters["type"]), "int") !== false) {
197 $fieldstruct .= " DEFAULT " . $parameters["default"];
199 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
202 if (isset($parameters["extra"])) {
203 $fieldstruct .= " " . $parameters["extra"];
206 if (isset($parameters["comment"])) {
207 $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
210 /*if (($parameters["primary"] != "") && $create)
211 $fieldstruct .= " PRIMARY KEY";*/
213 return ($fieldstruct);
216 private static function createIndex($indexname, $fieldnames, $method = "ADD")
218 $method = strtoupper(trim($method));
219 if ($method != "" && $method != "ADD") {
220 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
223 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
224 $index_type = array_shift($fieldnames);
225 $method .= " " . $index_type;
229 foreach ($fieldnames AS $fieldname) {
234 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
235 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
237 $names .= "`" . DBA::escape($fieldname) . "`";
241 if ($indexname == "PRIMARY") {
242 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
246 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
251 * Updates DB structure and returns eventual errors messages
253 * @param bool $verbose
254 * @param bool $action Whether to actually apply the update
255 * @param bool $install Is this the initial update during the installation?
256 * @param array $tables An array of the database tables
257 * @param array $definition An array of the definition tables
258 * @return string Empty string if the update is successful, error messages otherwise
260 public static function update($verbose, $action, $install = false, array $tables = null, array $definition = null)
262 if ($action && !$install) {
263 Config::set('system', 'maintenance', 1);
264 Config::set('system', 'maintenance_reason', L10n::t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
269 Logger::log('updating structure', Logger::DEBUG);
271 // Get the current structure
274 if (is_null($tables)) {
275 $tables = q("SHOW TABLES");
278 if (DBA::isResult($tables)) {
279 foreach ($tables AS $table) {
280 $table = current($table);
282 Logger::log(sprintf('updating structure for table %s ...', $table), Logger::DEBUG);
283 $database[$table] = self::tableStructure($table);
287 // Get the definition
288 if (is_null($definition)) {
289 $definition = self::definition();
292 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
293 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
294 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
301 foreach ($definition AS $name => $structure) {
302 $is_new_table = false;
307 if (!isset($database[$name])) {
308 $r = self::createTable($name, $structure, $verbose, $action);
309 if (!DBA::isResult($r)) {
310 $errors .= self::printUpdateError($name);
312 $is_new_table = true;
314 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
315 if (isset($database[$name]["indexes"][$indexname])) {
316 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
318 $current_index_definition = "__NOT_SET__";
320 $new_index_definition = implode(",", $fieldnames);
321 if ($current_index_definition != $new_index_definition) {
322 if ($fieldnames[0] == "UNIQUE") {
325 $temp_name = "temp-" . $name;
332 * Drop the index if it isn't present in the definition
333 * or the definition differ from current status
334 * and index name doesn't start with "local_"
336 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
337 $current_index_definition = implode(",", $fieldnames);
338 if (isset($structure["indexes"][$indexname])) {
339 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
341 $new_index_definition = "__NOT_SET__";
343 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
344 $sql2 = self::dropIndex($indexname);
346 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
348 $sql3 .= ", " . $sql2;
352 // Compare the field structure field by field
353 foreach ($structure["fields"] AS $fieldname => $parameters) {
354 if (!isset($database[$name]["fields"][$fieldname])) {
355 $sql2 = self::addTableField($fieldname, $parameters);
357 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
359 $sql3 .= ", " . $sql2;
362 // Compare the field definition
363 $field_definition = $database[$name]["fields"][$fieldname];
365 // Remove the relation data that is used for the referential integrity
366 unset($parameters['relation']);
368 // We change the collation after the indexes had been changed.
369 // This is done to avoid index length problems.
370 // So here we always ensure that there is no need to change it.
371 unset($parameters['Collation']);
372 unset($field_definition['Collation']);
374 // Only update the comment when it is defined
375 if (!isset($parameters['comment'])) {
376 $parameters['comment'] = "";
379 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
380 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
381 if ($current_field_definition != $new_field_definition) {
382 $sql2 = self::modifyTableField($fieldname, $parameters);
384 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
386 $sql3 .= ", " . $sql2;
394 * Create the index if the index don't exists in database
395 * or the definition differ from the current status.
396 * Don't create keys if table is new
398 if (!$is_new_table) {
399 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
400 if (isset($database[$name]["indexes"][$indexname])) {
401 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
403 $current_index_definition = "__NOT_SET__";
405 $new_index_definition = implode(",", $fieldnames);
406 if ($current_index_definition != $new_index_definition) {
407 $sql2 = self::createIndex($indexname, $fieldnames);
409 // Fetch the "group by" fields for unique indexes
410 $group_by = self::groupBy($fieldnames);
413 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
415 $sql3 .= ", " . $sql2;
421 if (isset($database[$name]["table_status"]["Comment"])) {
422 $structurecomment = defaults($structure, "comment", "");
423 if ($database[$name]["table_status"]["Comment"] != $structurecomment) {
424 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
427 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
429 $sql3 .= ", " . $sql2;
434 if (isset($database[$name]["table_status"]["Engine"]) && isset($structure['engine'])) {
435 if ($database[$name]["table_status"]["Engine"] != $structure['engine']) {
436 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
439 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
441 $sql3 .= ", " . $sql2;
446 if (isset($database[$name]["table_status"]["Collation"])) {
447 if ($database[$name]["table_status"]["Collation"] != 'utf8mb4_general_ci') {
448 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
451 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
453 $sql3 .= ", " . $sql2;
462 // Now have a look at the field collations
463 // Compare the field structure field by field
464 foreach ($structure["fields"] AS $fieldname => $parameters) {
465 // Compare the field definition
466 $field_definition = defaults($database[$name]["fields"], $fieldname, ['Collation' => '']);
468 // Define the default collation if not given
469 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
470 $parameters['Collation'] = 'utf8mb4_general_ci';
472 $parameters['Collation'] = null;
475 if ($field_definition['Collation'] != $parameters['Collation']) {
476 $sql2 = self::modifyTableField($fieldname, $parameters);
477 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
478 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
480 $sql3 .= ", " . $sql2;
487 if (substr($sql3, -2, 2) != "; ") {
492 if ($is_unique && $ignore == '') {
493 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
494 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
496 $field_list = rtrim($field_list, ',');
500 // Ensure index conversion to unique removes duplicates
501 if ($is_unique && ($temp_name != $name)) {
503 echo "SET session old_alter_table=1;\n";
505 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
506 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
512 if ($is_unique && ($temp_name != $name)) {
514 echo "SET session old_alter_table=0;\n";
516 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
517 echo "DROP TABLE `" . $name . "`;\n";
518 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
525 Config::set('system', 'maintenance_reason', L10n::t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
528 // Ensure index conversion to unique removes duplicates
529 if ($is_unique && ($temp_name != $name)) {
531 DBA::e("SET session old_alter_table=1;");
533 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
534 if (!DBA::isResult($r)) {
535 $errors .= self::printUpdateError($sql3);
539 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
540 if (!DBA::isResult($r)) {
541 $errors .= self::printUpdateError($sql3);
548 if (!DBA::isResult($r)) {
549 $errors .= self::printUpdateError($sql3);
551 if ($is_unique && ($temp_name != $name)) {
553 DBA::e("SET session old_alter_table=0;");
555 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
556 if (!DBA::isResult($r)) {
557 $errors .= self::printUpdateError($sql3);
560 $r = DBA::e("DROP TABLE `" . $name . "`;");
561 if (!DBA::isResult($r)) {
562 $errors .= self::printUpdateError($sql3);
565 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
566 if (!DBA::isResult($r)) {
567 $errors .= self::printUpdateError($sql3);
576 if ($action && !$install) {
577 Config::set('system', 'maintenance', 0);
578 Config::set('system', 'maintenance_reason', '');
581 Config::set('system', 'dbupdate', self::UPDATE_FAILED);
583 Config::set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
590 private static function tableStructure($table)
592 $structures = q("DESCRIBE `%s`", $table);
594 $full_columns = q("SHOW FULL COLUMNS FROM `%s`", $table);
596 $indexes = q("SHOW INDEX FROM `%s`", $table);
598 $table_status = q("SHOW TABLE STATUS WHERE `name` = '%s'", $table);
600 if (DBA::isResult($table_status)) {
601 $table_status = $table_status[0];
609 if (DBA::isResult($indexes)) {
610 foreach ($indexes AS $index) {
611 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
612 $indexdata[$index["Key_name"]] = ["UNIQUE"];
615 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
616 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
619 $column = $index["Column_name"];
621 if ($index["Sub_part"] != "") {
622 $column .= "(" . $index["Sub_part"] . ")";
625 $indexdata[$index["Key_name"]][] = $column;
628 if (DBA::isResult($structures)) {
629 foreach ($structures AS $field) {
630 // Replace the default size values so that we don't have to define them
631 $search = ['tinyint(1)', 'tinyint(3) unsigned', 'tinyint(4)', 'smallint(5) unsigned', 'smallint(6)', 'mediumint(8) unsigned', 'mediumint(9)', 'bigint(20)', 'int(10) unsigned', 'int(11)'];
632 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
633 $field["Type"] = str_replace($search, $replace, $field["Type"]);
635 $fielddata[$field["Field"]]["type"] = $field["Type"];
636 if ($field["Null"] == "NO") {
637 $fielddata[$field["Field"]]["not null"] = true;
640 if (isset($field["Default"])) {
641 $fielddata[$field["Field"]]["default"] = $field["Default"];
644 if ($field["Extra"] != "") {
645 $fielddata[$field["Field"]]["extra"] = $field["Extra"];
648 if ($field["Key"] == "PRI") {
649 $fielddata[$field["Field"]]["primary"] = true;
653 if (DBA::isResult($full_columns)) {
654 foreach ($full_columns AS $column) {
655 $fielddata[$column["Field"]]["Collation"] = $column["Collation"];
656 $fielddata[$column["Field"]]["comment"] = $column["Comment"];
660 return ["fields" => $fielddata, "indexes" => $indexdata, "table_status" => $table_status];
663 private static function dropIndex($indexname)
665 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
669 private static function addTableField($fieldname, $parameters)
671 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
675 private static function modifyTableField($fieldname, $parameters)
677 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
682 * Constructs a GROUP BY clause from a UNIQUE index definition.
684 * @param array $fieldnames
687 private static function groupBy(array $fieldnames)
689 if ($fieldnames[0] != "UNIQUE") {
693 array_shift($fieldnames);
696 foreach ($fieldnames AS $fieldname) {
701 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
702 $names .= "`" . DBA::escape($matches[1]) . "`";
704 $names .= "`" . DBA::escape($fieldname) . "`";
708 $sql = sprintf(" GROUP BY %s", $names);
713 * Renames columns or the primary key of a table
715 * @todo You cannot rename a primary key if "auto increment" is set
717 * @param string $table Table name
718 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ] )
719 * Syntax for Primary Key: [ $col1, $col2, ...] )
720 * @param int $type The type of renaming (Default is Column)
722 * @return boolean Was the renaming successful?
725 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
727 if (empty($table) || empty($columns)) {
731 if (!is_array($columns)) {
735 $table = DBA::escape($table);
737 $sql = "ALTER TABLE `" . $table . "`";
739 case self::RENAME_COLUMN:
740 if (!self::existsColumn($table, array_keys($columns))) {
743 $sql .= implode(',', array_map(
744 function ($to, $from) {
745 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
751 case self::RENAME_PRIMARY_KEY:
752 if (!self::existsColumn($table, $columns)) {
755 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
763 $stmt = DBA::p($sql);
765 if (is_bool($stmt)) {
777 * Check if the columns of the table exists
779 * @param string $table Table name
780 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
782 * @return boolean Does the table exist?
784 public static function existsColumn($table, $columns = [])
790 if (is_null($columns) || empty($columns)) {
791 return self::existsTable($table);
794 $table = DBA::escape($table);
796 foreach ($columns AS $column) {
797 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
799 $stmt = DBA::p($sql);
801 if (is_bool($stmt)) {
804 $retval = (DBA::numRows($stmt) > 0);
818 * Check if a table exists
820 * @param string $table Table name
822 * @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);