3 * @file src/Database/DBStructure.php
5 namespace Friendica\Database;
8 use Friendica\Core\Config;
9 use Friendica\Core\Hook;
10 use Friendica\Core\L10n;
11 use Friendica\Core\Logger;
12 use Friendica\Util\DateTimeFormat;
14 require_once 'boot.php';
15 require_once 'include/dba.php';
16 require_once 'include/enotify.php';
17 require_once 'include/text.php';
20 * @brief This class contain functions for the database management
22 * This class contains functions that doesn't need to know if pdo, mysqli or whatever is used.
26 const UPDATE_NOT_CHECKED = 0; // Database check wasn't executed before
27 const UPDATE_SUCCESSFUL = 1; // Database check was successful
28 const UPDATE_FAILED = 2; // Database check failed
31 * Database structure definition loaded from config/dbstructure.php
35 private static $definition = [];
38 * Converts all tables from MyISAM to InnoDB
40 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 * send the email and do what is needed to do on update fails
63 * @param update_id (int) number of failed update
64 * @param error_message (str) error message
66 public static function updateFail($update_id, $error_message) {
69 //send the administrators an e-mail
70 $admin_mail_list = "'".implode("','", array_map(['Friendica\Database\DBA', 'escape'], explode(",", str_replace(" ", "", Config::get('config', 'admin_email')))))."'";
71 $adminlist = q("SELECT uid, language, email FROM user WHERE email IN (%s)",
76 if (!DBA::isResult($adminlist)) {
77 Logger::log(sprintf('Cannot notify administrators about update_id=%d, error_message=%s', $update_id, $error_message), Logger::INFO);
83 // every admin could had different language
84 foreach ($adminlist as $admin) {
85 $lang = (($admin['language'])?$admin['language']:'en');
86 L10n::pushLang($lang);
88 $preamble = deindent(L10n::t("
89 The friendica developers released update %s recently,
90 but when I tried to install it, something went terribly wrong.
91 This needs to be fixed soon and I can't do it alone. Please contact a
92 friendica developer if you can not help me on your own. My database might be invalid.",
94 $body = L10n::t("The error message is\n[pre]%s[/pre]", $error_message);
97 'uid' => $admin['uid'],
98 'type' => SYSTEM_EMAIL,
99 'to_email' => $admin['email'],
100 'preamble' => $preamble,
108 Logger::log("CRITICAL: Database structure update failed: ".$error_message);
112 private static function tableStructure($table) {
113 $structures = q("DESCRIBE `%s`", $table);
115 $full_columns = q("SHOW FULL COLUMNS FROM `%s`", $table);
117 $indexes = q("SHOW INDEX FROM `%s`", $table);
119 $table_status = q("SHOW TABLE STATUS WHERE `name` = '%s'", $table);
121 if (DBA::isResult($table_status)) {
122 $table_status = $table_status[0];
130 if (DBA::isResult($indexes)) {
131 foreach ($indexes AS $index) {
132 if ($index['Key_name'] != 'PRIMARY' && $index['Non_unique'] == '0' && !isset($indexdata[$index["Key_name"]])) {
133 $indexdata[$index["Key_name"]] = ['UNIQUE'];
136 $column = $index["Column_name"];
138 if ($index["Sub_part"] != "") {
139 $column .= "(".$index["Sub_part"].")";
142 $indexdata[$index["Key_name"]][] = $column;
145 if (DBA::isResult($structures)) {
146 foreach ($structures AS $field) {
147 // Replace the default size values so that we don't have to define them
148 $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)'];
149 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
150 $field["Type"] = str_replace($search, $replace, $field["Type"]);
152 $fielddata[$field["Field"]]["type"] = $field["Type"];
153 if ($field["Null"] == "NO") {
154 $fielddata[$field["Field"]]["not null"] = true;
157 if (isset($field["Default"])) {
158 $fielddata[$field["Field"]]["default"] = $field["Default"];
161 if ($field["Extra"] != "") {
162 $fielddata[$field["Field"]]["extra"] = $field["Extra"];
165 if ($field["Key"] == "PRI") {
166 $fielddata[$field["Field"]]["primary"] = true;
170 if (DBA::isResult($full_columns)) {
171 foreach ($full_columns AS $column) {
172 $fielddata[$column["Field"]]["Collation"] = $column["Collation"];
173 $fielddata[$column["Field"]]["comment"] = $column["Comment"];
177 return ["fields" => $fielddata, "indexes" => $indexdata, "table_status" => $table_status];
180 public static function printStructure() {
181 $database = self::definition(false);
183 echo "-- ------------------------------------------\n";
184 echo "-- ".FRIENDICA_PLATFORM." ".FRIENDICA_VERSION." (".FRIENDICA_CODENAME,")\n";
185 echo "-- DB_UPDATE_VERSION ".DB_UPDATE_VERSION."\n";
186 echo "-- ------------------------------------------\n\n\n";
187 foreach ($database AS $name => $structure) {
189 echo "-- TABLE $name\n";
191 self::createTable($name, $structure, true, false);
198 * @brief Print out database error messages
200 * @param string $message Message to be added to the error message
202 * @return string Error message
204 private static function printUpdateError($message) {
205 echo L10n::t("\nError %d occurred during database update:\n%s\n",
206 DBA::errorNo(), DBA::errorMessage());
208 return L10n::t('Errors encountered performing database changes: ').$message.EOL;
212 * Updates DB structure and returns eventual errors messages
214 * @param bool $verbose
215 * @param bool $action Whether to actually apply the update
216 * @param bool $install Is this the initial update during the installation?
217 * @param array $tables An array of the database tables
218 * @param array $definition An array of the definition tables
219 * @return string Empty string if the update is successful, error messages otherwise
221 public static function update($verbose, $action, $install = false, array $tables = null, array $definition = null) {
222 if ($action && !$install) {
223 Config::set('system', 'maintenance', 1);
224 Config::set('system', 'maintenance_reason', L10n::t('%s: Database update', DateTimeFormat::utcNow().' '.date('e')));
229 Logger::log('updating structure', Logger::DEBUG);
231 // Get the current structure
234 if (is_null($tables)) {
235 $tables = q("SHOW TABLES");
238 if (DBA::isResult($tables)) {
239 foreach ($tables AS $table) {
240 $table = current($table);
242 Logger::log(sprintf('updating structure for table %s ...', $table), Logger::DEBUG);
243 $database[$table] = self::tableStructure($table);
247 // Get the definition
248 if (is_null($definition)) {
249 $definition = self::definition();
252 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
253 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
254 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
261 foreach ($definition AS $name => $structure) {
262 $is_new_table = false;
267 if (!isset($database[$name])) {
268 $r = self::createTable($name, $structure, $verbose, $action);
269 if (!DBA::isResult($r)) {
270 $errors .= self::printUpdateError($name);
272 $is_new_table = true;
274 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
275 if (isset($database[$name]["indexes"][$indexname])) {
276 $current_index_definition = implode(",",$database[$name]["indexes"][$indexname]);
278 $current_index_definition = "__NOT_SET__";
280 $new_index_definition = implode(",",$fieldnames);
281 if ($current_index_definition != $new_index_definition) {
282 if ($fieldnames[0] == "UNIQUE") {
285 $temp_name = "temp-".$name;
292 * Drop the index if it isn't present in the definition
293 * or the definition differ from current status
294 * and index name doesn't start with "local_"
296 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
297 $current_index_definition = implode(",",$fieldnames);
298 if (isset($structure["indexes"][$indexname])) {
299 $new_index_definition = implode(",",$structure["indexes"][$indexname]);
301 $new_index_definition = "__NOT_SET__";
303 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
304 $sql2=self::dropIndex($indexname);
306 $sql3 = "ALTER".$ignore." TABLE `".$temp_name."` ".$sql2;
312 // Compare the field structure field by field
313 foreach ($structure["fields"] AS $fieldname => $parameters) {
314 if (!isset($database[$name]["fields"][$fieldname])) {
315 $sql2=self::addTableField($fieldname, $parameters);
317 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
322 // Compare the field definition
323 $field_definition = $database[$name]["fields"][$fieldname];
325 // Remove the relation data that is used for the referential integrity
326 unset($parameters['relation']);
328 // We change the collation after the indexes had been changed.
329 // This is done to avoid index length problems.
330 // So here we always ensure that there is no need to change it.
331 unset($parameters['Collation']);
332 unset($field_definition['Collation']);
334 // Only update the comment when it is defined
335 if (!isset($parameters['comment'])) {
336 $parameters['comment'] = "";
339 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
340 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
341 if ($current_field_definition != $new_field_definition) {
342 $sql2 = self::modifyTableField($fieldname, $parameters);
344 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
354 * Create the index if the index don't exists in database
355 * or the definition differ from the current status.
356 * Don't create keys if table is new
358 if (!$is_new_table) {
359 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
360 if (isset($database[$name]["indexes"][$indexname])) {
361 $current_index_definition = implode(",",$database[$name]["indexes"][$indexname]);
363 $current_index_definition = "__NOT_SET__";
365 $new_index_definition = implode(",",$fieldnames);
366 if ($current_index_definition != $new_index_definition) {
367 $sql2 = self::createIndex($indexname, $fieldnames);
369 // Fetch the "group by" fields for unique indexes
370 if ($fieldnames[0] == "UNIQUE") {
371 $group_by = self::groupBy($indexname, $fieldnames);
375 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
383 if (isset($database[$name]["table_status"]["Comment"])) {
384 if ($database[$name]["table_status"]["Comment"] != $structure['comment']) {
385 $sql2 = "COMMENT = '".DBA::escape($structure['comment'])."'";
388 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
395 if (isset($database[$name]["table_status"]["Engine"]) && isset($structure['engine'])) {
396 if ($database[$name]["table_status"]["Engine"] != $structure['engine']) {
397 $sql2 = "ENGINE = '".DBA::escape($structure['engine'])."'";
400 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
407 if (isset($database[$name]["table_status"]["Collation"])) {
408 if ($database[$name]["table_status"]["Collation"] != 'utf8mb4_general_ci') {
409 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
412 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
423 // Now have a look at the field collations
424 // Compare the field structure field by field
425 foreach ($structure["fields"] AS $fieldname => $parameters) {
426 // Compare the field definition
427 $field_definition = defaults($database[$name]["fields"], $fieldname, ['Collation' => '']);
429 // Define the default collation if not given
430 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
431 $parameters['Collation'] = 'utf8mb4_general_ci';
433 $parameters['Collation'] = null;
436 if ($field_definition['Collation'] != $parameters['Collation']) {
437 $sql2 = self::modifyTableField($fieldname, $parameters);
438 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
439 $sql3 .= "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
448 if (substr($sql3, -2, 2) != "; ") {
453 if ($is_unique && $ignore == '') {
454 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
455 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
457 $field_list = rtrim($field_list, ',');
461 // Ensure index conversion to unique removes duplicates
462 if ($is_unique && ($temp_name != $name)) {
464 echo "SET session old_alter_table=1;\n";
466 echo "DROP TABLE IF EXISTS `".$temp_name."`;\n";
467 echo "CREATE TABLE `".$temp_name."` LIKE `".$name."`;\n";
473 if ($is_unique && ($temp_name != $name)) {
475 echo "SET session old_alter_table=0;\n";
477 echo "INSERT INTO `".$temp_name."` SELECT ".DBA::anyValueFallback($field_list)." FROM `".$name."`".$group_by.";\n";
478 echo "DROP TABLE `".$name."`;\n";
479 echo "RENAME TABLE `".$temp_name."` TO `".$name."`;\n";
486 Config::set('system', 'maintenance_reason', L10n::t('%s: updating %s table.', DateTimeFormat::utcNow().' '.date('e'), $name));
489 // Ensure index conversion to unique removes duplicates
490 if ($is_unique && ($temp_name != $name)) {
492 DBA::e("SET session old_alter_table=1;");
494 $r = DBA::e("DROP TABLE IF EXISTS `".$temp_name."`;");
495 if (!DBA::isResult($r)) {
496 $errors .= self::printUpdateError($sql3);
500 $r = DBA::e("CREATE TABLE `".$temp_name."` LIKE `".$name."`;");
501 if (!DBA::isResult($r)) {
502 $errors .= self::printUpdateError($sql3);
509 if (!DBA::isResult($r)) {
510 $errors .= self::printUpdateError($sql3);
512 if ($is_unique && ($temp_name != $name)) {
514 DBA::e("SET session old_alter_table=0;");
516 $r = DBA::e("INSERT INTO `".$temp_name."` SELECT ".$field_list." FROM `".$name."`".$group_by.";");
517 if (!DBA::isResult($r)) {
518 $errors .= self::printUpdateError($sql3);
521 $r = DBA::e("DROP TABLE `".$name."`;");
522 if (!DBA::isResult($r)) {
523 $errors .= self::printUpdateError($sql3);
526 $r = DBA::e("RENAME TABLE `".$temp_name."` TO `".$name."`;");
527 if (!DBA::isResult($r)) {
528 $errors .= self::printUpdateError($sql3);
537 if ($action && !$install) {
538 Config::set('system', 'maintenance', 0);
539 Config::set('system', 'maintenance_reason', '');
542 Config::set('system', 'dbupdate', self::UPDATE_FAILED);
544 Config::set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
551 private static function FieldCommand($parameters, $create = true) {
552 $fieldstruct = $parameters["type"];
554 if (isset($parameters["Collation"])) {
555 $fieldstruct .= " COLLATE ".$parameters["Collation"];
558 if (isset($parameters["not null"])) {
559 $fieldstruct .= " NOT NULL";
562 if (isset($parameters["default"])) {
563 if (strpos(strtolower($parameters["type"]),"int")!==false) {
564 $fieldstruct .= " DEFAULT ".$parameters["default"];
566 $fieldstruct .= " DEFAULT '".$parameters["default"]."'";
569 if (isset($parameters["extra"])) {
570 $fieldstruct .= " ".$parameters["extra"];
573 if (isset($parameters["comment"])) {
574 $fieldstruct .= " COMMENT '".DBA::escape($parameters["comment"])."'";
577 /*if (($parameters["primary"] != "") && $create)
578 $fieldstruct .= " PRIMARY KEY";*/
580 return($fieldstruct);
583 private static function createTable($name, $structure, $verbose, $action) {
590 foreach ($structure["fields"] AS $fieldname => $field) {
591 $sql_rows[] = "`".DBA::escape($fieldname)."` ".self::FieldCommand($field);
592 if (x($field,'primary') && $field['primary']!='') {
593 $primary_keys[] = $fieldname;
597 if (!empty($structure["indexes"])) {
598 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
599 $sql_index = self::createIndex($indexname, $fieldnames, "");
600 if (!is_null($sql_index)) {
601 $sql_rows[] = $sql_index;
606 if (isset($structure["engine"])) {
607 $engine = " ENGINE=" . $structure["engine"];
610 if (isset($structure["comment"])) {
611 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
614 $sql = implode(",\n\t", $sql_rows);
616 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)).$sql.
617 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
629 private static function addTableField($fieldname, $parameters) {
630 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
634 private static function modifyTableField($fieldname, $parameters) {
635 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
639 private static function dropIndex($indexname) {
640 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
644 private static function createIndex($indexname, $fieldnames, $method = "ADD") {
645 $method = strtoupper(trim($method));
646 if ($method!="" && $method!="ADD") {
647 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
650 if ($fieldnames[0] == "UNIQUE") {
651 array_shift($fieldnames);
652 $method .= ' UNIQUE';
656 foreach ($fieldnames AS $fieldname) {
661 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
662 $names .= "`".DBA::escape($matches[1])."`(".intval($matches[2]).")";
664 $names .= "`".DBA::escape($fieldname)."`";
668 if ($indexname == "PRIMARY") {
669 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
673 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
677 private static function groupBy($indexname, $fieldnames) {
678 if ($fieldnames[0] != "UNIQUE") {
682 array_shift($fieldnames);
685 foreach ($fieldnames AS $fieldname) {
690 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
691 $names .= "`".DBA::escape($matches[1])."`";
693 $names .= "`".DBA::escape($fieldname)."`";
697 $sql = sprintf(" GROUP BY %s", $names);
702 * Check if a table exists
704 * @param string $table Table name
706 * @return boolean Does the table exist?
708 public static function existsTable($table)
714 $table = DBA::escape($table);
716 $sql = "SHOW TABLES LIKE '" . $table . "';";
718 $stmt = DBA::p($sql);
720 if (is_bool($stmt)) {
723 $retval = (DBA::numRows($stmt) > 0);
732 * Check if the columns of the table exists
734 * @param string $table Table name
735 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
737 * @return boolean Does the table exist?
739 public static function existsColumn($table, $columns = []) {
744 if (is_null($columns) || empty($columns)) {
745 return self::existsTable($table);
748 $table = DBA::escape($table);
750 foreach ($columns AS $column) {
751 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
753 $stmt = DBA::p($sql);
755 if (is_bool($stmt)) {
758 $retval = (DBA::numRows($stmt) > 0);
771 const RENAME_COLUMN = 0;
772 const RENAME_PRIMARY_KEY = 1;
775 * Renames columns or the primary key of a table
776 * @todo You cannot rename a primary key if "auto increment" is set
778 * @param string $table Table name
779 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ] )
780 * Syntax for Primary Key: [ $col1, $col2, ...] )
781 * @param int $type The type of renaming (Default is Column)
783 * @return boolean Was the renaming successful?
786 public static function rename($table, $columns, $type = self::RENAME_COLUMN) {
787 if (empty($table) || empty($columns)) {
791 if (!is_array($columns)) {
795 $table = DBA::escape($table);
797 $sql = "ALTER TABLE `" . $table . "`";
799 case self::RENAME_COLUMN:
800 if (!self::existsColumn($table, array_keys($columns))) {
803 $sql .= implode(',', array_map(
804 function ($to, $from) {
805 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
811 case self::RENAME_PRIMARY_KEY:
812 if (!self::existsColumn($table, $columns)) {
815 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
823 $stmt = DBA::p($sql);
825 if (is_bool($stmt)) {
837 * Loads the database structure definition from the config/dbstructure.php file.
838 * On first pass, defines DB_UPDATE_VERSION constant.
840 * @see config/dbstructure.php
841 * @param boolean $with_addons_structure Whether to tack on addons additional tables
845 public static function definition($with_addons_structure = true)
847 if (!self::$definition) {
848 $a = \Friendica\BaseObject::getApp();
850 $filename = $a->getBasePath() . '/config/dbstructure.php';
852 if (!is_readable($filename)) {
853 throw new Exception('Missing database structure config file config/dbstructure.php');
856 $definition = require $filename;
859 throw new Exception('Corrupted database structure config file config/dbstructure.php');
862 self::$definition = $definition;
864 $definition = self::$definition;
867 if ($with_addons_structure) {
868 Hook::callAll('dbstructure_definition', $definition);