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.
27 * Database structure definition loaded from config/dbstructure.php
31 private static $definition = [];
34 * Converts all tables from MyISAM to InnoDB
36 public static function convertToInnoDB() {
37 $r = q("SELECT `TABLE_NAME` FROM `information_schema`.`tables` WHERE `engine` = 'MyISAM' AND `table_schema` = '%s'",
38 DBA::escape(DBA::databaseName()));
40 if (!DBA::isResult($r)) {
41 echo L10n::t('There are no tables on MyISAM.')."\n";
45 foreach ($r AS $table) {
46 $sql = sprintf("ALTER TABLE `%s` engine=InnoDB;", DBA::escape($table['TABLE_NAME']));
49 $result = DBA::e($sql);
50 if (!DBA::isResult($result)) {
51 self::printUpdateError($sql);
57 * send the email and do what is needed to do on update fails
59 * @param update_id (int) number of failed update
60 * @param error_message (str) error message
62 public static function updateFail($update_id, $error_message) {
65 //send the administrators an e-mail
66 $admin_mail_list = "'".implode("','", array_map(['Friendica\Database\DBA', 'escape'], explode(",", str_replace(" ", "", Config::get('config', 'admin_email')))))."'";
67 $adminlist = q("SELECT uid, language, email FROM user WHERE email IN (%s)",
72 if (!DBA::isResult($adminlist)) {
73 Logger::log(sprintf('Cannot notify administrators about update_id=%d, error_message=%s', $update_id, $error_message), LOGGER_INFO);
79 // every admin could had different language
80 foreach ($adminlist as $admin) {
81 $lang = (($admin['language'])?$admin['language']:'en');
82 L10n::pushLang($lang);
84 $preamble = deindent(L10n::t("
85 The friendica developers released update %s recently,
86 but when I tried to install it, something went terribly wrong.
87 This needs to be fixed soon and I can't do it alone. Please contact a
88 friendica developer if you can not help me on your own. My database might be invalid.",
90 $body = L10n::t("The error message is\n[pre]%s[/pre]", $error_message);
93 'uid' => $admin['uid'],
94 'type' => SYSTEM_EMAIL,
95 'to_email' => $admin['email'],
96 'preamble' => $preamble,
104 Logger::log("CRITICAL: Database structure update failed: ".$error_message);
108 private static function tableStructure($table) {
109 $structures = q("DESCRIBE `%s`", $table);
111 $full_columns = q("SHOW FULL COLUMNS FROM `%s`", $table);
113 $indexes = q("SHOW INDEX FROM `%s`", $table);
115 $table_status = q("SHOW TABLE STATUS WHERE `name` = '%s'", $table);
117 if (DBA::isResult($table_status)) {
118 $table_status = $table_status[0];
126 if (DBA::isResult($indexes)) {
127 foreach ($indexes AS $index) {
128 if ($index['Key_name'] != 'PRIMARY' && $index['Non_unique'] == '0' && !isset($indexdata[$index["Key_name"]])) {
129 $indexdata[$index["Key_name"]] = ['UNIQUE'];
132 $column = $index["Column_name"];
134 if ($index["Sub_part"] != "") {
135 $column .= "(".$index["Sub_part"].")";
138 $indexdata[$index["Key_name"]][] = $column;
141 if (DBA::isResult($structures)) {
142 foreach ($structures AS $field) {
143 // Replace the default size values so that we don't have to define them
144 $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)'];
145 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
146 $field["Type"] = str_replace($search, $replace, $field["Type"]);
148 $fielddata[$field["Field"]]["type"] = $field["Type"];
149 if ($field["Null"] == "NO") {
150 $fielddata[$field["Field"]]["not null"] = true;
153 if (isset($field["Default"])) {
154 $fielddata[$field["Field"]]["default"] = $field["Default"];
157 if ($field["Extra"] != "") {
158 $fielddata[$field["Field"]]["extra"] = $field["Extra"];
161 if ($field["Key"] == "PRI") {
162 $fielddata[$field["Field"]]["primary"] = true;
166 if (DBA::isResult($full_columns)) {
167 foreach ($full_columns AS $column) {
168 $fielddata[$column["Field"]]["Collation"] = $column["Collation"];
169 $fielddata[$column["Field"]]["comment"] = $column["Comment"];
173 return ["fields" => $fielddata, "indexes" => $indexdata, "table_status" => $table_status];
176 public static function printStructure() {
177 $database = self::definition(false);
179 echo "-- ------------------------------------------\n";
180 echo "-- ".FRIENDICA_PLATFORM." ".FRIENDICA_VERSION." (".FRIENDICA_CODENAME,")\n";
181 echo "-- DB_UPDATE_VERSION ".DB_UPDATE_VERSION."\n";
182 echo "-- ------------------------------------------\n\n\n";
183 foreach ($database AS $name => $structure) {
185 echo "-- TABLE $name\n";
187 self::createTable($name, $structure, true, false);
194 * @brief Print out database error messages
196 * @param string $message Message to be added to the error message
198 * @return string Error message
200 private static function printUpdateError($message) {
201 echo L10n::t("\nError %d occurred during database update:\n%s\n",
202 DBA::errorNo(), DBA::errorMessage());
204 return L10n::t('Errors encountered performing database changes: ').$message.EOL;
208 * Updates DB structure and returns eventual errors messages
210 * @param bool $verbose
211 * @param bool $action Whether to actually apply the update
212 * @param bool $install Is this the initial update during the installation?
213 * @param array $tables An array of the database tables
214 * @param array $definition An array of the definition tables
215 * @return string Empty string if the update is successful, error messages otherwise
217 public static function update($verbose, $action, $install = false, array $tables = null, array $definition = null) {
218 if ($action && !$install) {
219 Config::set('system', 'maintenance', 1);
220 Config::set('system', 'maintenance_reason', L10n::t('%s: Database update', DateTimeFormat::utcNow().' '.date('e')));
225 Logger::log('updating structure', LOGGER_DEBUG);
227 // Get the current structure
230 if (is_null($tables)) {
231 $tables = q("SHOW TABLES");
234 if (DBA::isResult($tables)) {
235 foreach ($tables AS $table) {
236 $table = current($table);
238 Logger::log(sprintf('updating structure for table %s ...', $table), LOGGER_DEBUG);
239 $database[$table] = self::tableStructure($table);
243 // Get the definition
244 if (is_null($definition)) {
245 $definition = self::definition();
248 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
249 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
250 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
257 foreach ($definition AS $name => $structure) {
258 $is_new_table = false;
263 if (!isset($database[$name])) {
264 $r = self::createTable($name, $structure, $verbose, $action);
265 if (!DBA::isResult($r)) {
266 $errors .= self::printUpdateError($name);
268 $is_new_table = true;
270 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
271 if (isset($database[$name]["indexes"][$indexname])) {
272 $current_index_definition = implode(",",$database[$name]["indexes"][$indexname]);
274 $current_index_definition = "__NOT_SET__";
276 $new_index_definition = implode(",",$fieldnames);
277 if ($current_index_definition != $new_index_definition) {
278 if ($fieldnames[0] == "UNIQUE") {
281 $temp_name = "temp-".$name;
288 * Drop the index if it isn't present in the definition
289 * or the definition differ from current status
290 * and index name doesn't start with "local_"
292 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
293 $current_index_definition = implode(",",$fieldnames);
294 if (isset($structure["indexes"][$indexname])) {
295 $new_index_definition = implode(",",$structure["indexes"][$indexname]);
297 $new_index_definition = "__NOT_SET__";
299 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
300 $sql2=self::dropIndex($indexname);
302 $sql3 = "ALTER".$ignore." TABLE `".$temp_name."` ".$sql2;
308 // Compare the field structure field by field
309 foreach ($structure["fields"] AS $fieldname => $parameters) {
310 if (!isset($database[$name]["fields"][$fieldname])) {
311 $sql2=self::addTableField($fieldname, $parameters);
313 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
318 // Compare the field definition
319 $field_definition = $database[$name]["fields"][$fieldname];
321 // Remove the relation data that is used for the referential integrity
322 unset($parameters['relation']);
324 // We change the collation after the indexes had been changed.
325 // This is done to avoid index length problems.
326 // So here we always ensure that there is no need to change it.
327 unset($parameters['Collation']);
328 unset($field_definition['Collation']);
330 // Only update the comment when it is defined
331 if (!isset($parameters['comment'])) {
332 $parameters['comment'] = "";
335 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
336 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
337 if ($current_field_definition != $new_field_definition) {
338 $sql2 = self::modifyTableField($fieldname, $parameters);
340 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
350 * Create the index if the index don't exists in database
351 * or the definition differ from the current status.
352 * Don't create keys if table is new
354 if (!$is_new_table) {
355 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
356 if (isset($database[$name]["indexes"][$indexname])) {
357 $current_index_definition = implode(",",$database[$name]["indexes"][$indexname]);
359 $current_index_definition = "__NOT_SET__";
361 $new_index_definition = implode(",",$fieldnames);
362 if ($current_index_definition != $new_index_definition) {
363 $sql2 = self::createIndex($indexname, $fieldnames);
365 // Fetch the "group by" fields for unique indexes
366 if ($fieldnames[0] == "UNIQUE") {
367 $group_by = self::groupBy($indexname, $fieldnames);
371 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
379 if (isset($database[$name]["table_status"]["Comment"])) {
380 if ($database[$name]["table_status"]["Comment"] != $structure['comment']) {
381 $sql2 = "COMMENT = '".DBA::escape($structure['comment'])."'";
384 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
391 if (isset($database[$name]["table_status"]["Engine"]) && isset($structure['engine'])) {
392 if ($database[$name]["table_status"]["Engine"] != $structure['engine']) {
393 $sql2 = "ENGINE = '".DBA::escape($structure['engine'])."'";
396 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
403 if (isset($database[$name]["table_status"]["Collation"])) {
404 if ($database[$name]["table_status"]["Collation"] != 'utf8mb4_general_ci') {
405 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
408 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
419 // Now have a look at the field collations
420 // Compare the field structure field by field
421 foreach ($structure["fields"] AS $fieldname => $parameters) {
422 // Compare the field definition
423 $field_definition = defaults($database[$name]["fields"], $fieldname, ['Collation' => '']);
425 // Define the default collation if not given
426 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
427 $parameters['Collation'] = 'utf8mb4_general_ci';
429 $parameters['Collation'] = null;
432 if ($field_definition['Collation'] != $parameters['Collation']) {
433 $sql2 = self::modifyTableField($fieldname, $parameters);
434 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
435 $sql3 .= "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
444 if (substr($sql3, -2, 2) != "; ") {
449 if ($is_unique && $ignore == '') {
450 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
451 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
453 $field_list = rtrim($field_list, ',');
457 // Ensure index conversion to unique removes duplicates
458 if ($is_unique && ($temp_name != $name)) {
460 echo "SET session old_alter_table=1;\n";
462 echo "DROP TABLE IF EXISTS `".$temp_name."`;\n";
463 echo "CREATE TABLE `".$temp_name."` LIKE `".$name."`;\n";
469 if ($is_unique && ($temp_name != $name)) {
471 echo "SET session old_alter_table=0;\n";
473 echo "INSERT INTO `".$temp_name."` SELECT ".DBA::anyValueFallback($field_list)." FROM `".$name."`".$group_by.";\n";
474 echo "DROP TABLE `".$name."`;\n";
475 echo "RENAME TABLE `".$temp_name."` TO `".$name."`;\n";
482 Config::set('system', 'maintenance_reason', L10n::t('%s: updating %s table.', DateTimeFormat::utcNow().' '.date('e'), $name));
485 // Ensure index conversion to unique removes duplicates
486 if ($is_unique && ($temp_name != $name)) {
488 DBA::e("SET session old_alter_table=1;");
490 $r = DBA::e("DROP TABLE IF EXISTS `".$temp_name."`;");
491 if (!DBA::isResult($r)) {
492 $errors .= self::printUpdateError($sql3);
496 $r = DBA::e("CREATE TABLE `".$temp_name."` LIKE `".$name."`;");
497 if (!DBA::isResult($r)) {
498 $errors .= self::printUpdateError($sql3);
505 if (!DBA::isResult($r)) {
506 $errors .= self::printUpdateError($sql3);
508 if ($is_unique && ($temp_name != $name)) {
510 DBA::e("SET session old_alter_table=0;");
512 $r = DBA::e("INSERT INTO `".$temp_name."` SELECT ".$field_list." FROM `".$name."`".$group_by.";");
513 if (!DBA::isResult($r)) {
514 $errors .= self::printUpdateError($sql3);
517 $r = DBA::e("DROP TABLE `".$name."`;");
518 if (!DBA::isResult($r)) {
519 $errors .= self::printUpdateError($sql3);
522 $r = DBA::e("RENAME TABLE `".$temp_name."` TO `".$name."`;");
523 if (!DBA::isResult($r)) {
524 $errors .= self::printUpdateError($sql3);
533 if ($action && !$install) {
534 Config::set('system', 'maintenance', 0);
535 Config::set('system', 'maintenance_reason', '');
538 Config::set('system', 'dbupdate', DB_UPDATE_FAILED);
540 Config::set('system', 'dbupdate', DB_UPDATE_SUCCESSFUL);
547 private static function FieldCommand($parameters, $create = true) {
548 $fieldstruct = $parameters["type"];
550 if (isset($parameters["Collation"])) {
551 $fieldstruct .= " COLLATE ".$parameters["Collation"];
554 if (isset($parameters["not null"])) {
555 $fieldstruct .= " NOT NULL";
558 if (isset($parameters["default"])) {
559 if (strpos(strtolower($parameters["type"]),"int")!==false) {
560 $fieldstruct .= " DEFAULT ".$parameters["default"];
562 $fieldstruct .= " DEFAULT '".$parameters["default"]."'";
565 if (isset($parameters["extra"])) {
566 $fieldstruct .= " ".$parameters["extra"];
569 if (isset($parameters["comment"])) {
570 $fieldstruct .= " COMMENT '".DBA::escape($parameters["comment"])."'";
573 /*if (($parameters["primary"] != "") && $create)
574 $fieldstruct .= " PRIMARY KEY";*/
576 return($fieldstruct);
579 private static function createTable($name, $structure, $verbose, $action) {
586 foreach ($structure["fields"] AS $fieldname => $field) {
587 $sql_rows[] = "`".DBA::escape($fieldname)."` ".self::FieldCommand($field);
588 if (x($field,'primary') && $field['primary']!='') {
589 $primary_keys[] = $fieldname;
593 if (!empty($structure["indexes"])) {
594 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
595 $sql_index = self::createIndex($indexname, $fieldnames, "");
596 if (!is_null($sql_index)) {
597 $sql_rows[] = $sql_index;
602 if (isset($structure["engine"])) {
603 $engine = " ENGINE=" . $structure["engine"];
606 if (isset($structure["comment"])) {
607 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
610 $sql = implode(",\n\t", $sql_rows);
612 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)).$sql.
613 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
625 private static function addTableField($fieldname, $parameters) {
626 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
630 private static function modifyTableField($fieldname, $parameters) {
631 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
635 private static function dropIndex($indexname) {
636 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
640 private static function createIndex($indexname, $fieldnames, $method = "ADD") {
641 $method = strtoupper(trim($method));
642 if ($method!="" && $method!="ADD") {
643 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
646 if ($fieldnames[0] == "UNIQUE") {
647 array_shift($fieldnames);
648 $method .= ' UNIQUE';
652 foreach ($fieldnames AS $fieldname) {
657 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
658 $names .= "`".DBA::escape($matches[1])."`(".intval($matches[2]).")";
660 $names .= "`".DBA::escape($fieldname)."`";
664 if ($indexname == "PRIMARY") {
665 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
669 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
673 private static function groupBy($indexname, $fieldnames) {
674 if ($fieldnames[0] != "UNIQUE") {
678 array_shift($fieldnames);
681 foreach ($fieldnames AS $fieldname) {
686 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
687 $names .= "`".DBA::escape($matches[1])."`";
689 $names .= "`".DBA::escape($fieldname)."`";
693 $sql = sprintf(" GROUP BY %s", $names);
698 * Check if a table exists
700 * @param string $table Table name
702 * @return boolean Does the table exist?
704 public static function existsTable($table)
710 $table = DBA::escape($table);
712 $sql = "SHOW TABLES LIKE '" . $table . "';";
714 $stmt = DBA::p($sql);
716 if (is_bool($stmt)) {
719 $retval = (DBA::numRows($stmt) > 0);
728 * Check if the columns of the table exists
730 * @param string $table Table name
731 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
733 * @return boolean Does the table exist?
735 public static function existsColumn($table, $columns = []) {
740 if (is_null($columns) || empty($columns)) {
741 return self::existsTable($table);
744 $table = DBA::escape($table);
746 foreach ($columns AS $column) {
747 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
749 $stmt = DBA::p($sql);
751 if (is_bool($stmt)) {
754 $retval = (DBA::numRows($stmt) > 0);
767 const RENAME_COLUMN = 0;
768 const RENAME_PRIMARY_KEY = 1;
771 * Renames columns or the primary key of a table
772 * @todo You cannot rename a primary key if "auto increment" is set
774 * @param string $table Table name
775 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ] )
776 * Syntax for Primary Key: [ $col1, $col2, ...] )
777 * @param int $type The type of renaming (Default is Column)
779 * @return boolean Was the renaming successful?
782 public static function rename($table, $columns, $type = self::RENAME_COLUMN) {
783 if (empty($table) || empty($columns)) {
787 if (!is_array($columns)) {
791 $table = DBA::escape($table);
793 $sql = "ALTER TABLE `" . $table . "`";
795 case self::RENAME_COLUMN:
796 if (!self::existsColumn($table, array_keys($columns))) {
799 $sql .= implode(',', array_map(
800 function ($to, $from) {
801 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
807 case self::RENAME_PRIMARY_KEY:
808 if (!self::existsColumn($table, $columns)) {
811 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
819 $stmt = DBA::p($sql);
821 if (is_bool($stmt)) {
833 * Loads the database structure definition from the config/dbstructure.php file.
834 * On first pass, defines DB_UPDATE_VERSION constant.
836 * @see config/dbstructure.php
837 * @param boolean $with_addons_structure Whether to tack on addons additional tables
841 public static function definition($with_addons_structure = true)
843 if (!self::$definition) {
844 $a = \Friendica\BaseObject::getApp();
846 $filename = $a->getBasePath() . '/config/dbstructure.php';
848 if (!is_readable($filename)) {
849 throw new Exception('Missing database structure config file config/dbstructure.php');
852 $definition = require $filename;
855 throw new Exception('Corrupted database structure config file config/dbstructure.php');
858 self::$definition = $definition;
860 $definition = self::$definition;
863 if ($with_addons_structure) {
864 Hook::callAll('dbstructure_definition', $definition);