3 * @file src/Database/DBStructure.php
5 namespace Friendica\Database;
8 use Friendica\Core\Addon;
9 use Friendica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Util\DateTimeFormat;
13 require_once 'boot.php';
14 require_once 'include/dba.php';
15 require_once 'include/enotify.php';
16 require_once 'include/text.php';
19 * @brief This class contain functions for the database management
21 * This class contains functions that doesn't need to know if pdo, mysqli or whatever is used.
26 * Converts all tables from MyISAM to InnoDB
28 public static function convertToInnoDB() {
29 $r = q("SELECT `TABLE_NAME` FROM `information_schema`.`tables` WHERE `engine` = 'MyISAM' AND `table_schema` = '%s'",
30 DBA::escape(DBA::databaseName()));
32 if (!DBA::isResult($r)) {
33 echo L10n::t('There are no tables on MyISAM.')."\n";
37 foreach ($r AS $table) {
38 $sql = sprintf("ALTER TABLE `%s` engine=InnoDB;", DBA::escape($table['TABLE_NAME']));
41 $result = DBA::e($sql);
42 if (!DBA::isResult($result)) {
43 self::printUpdateError($sql);
49 * send the email and do what is needed to do on update fails
51 * @param update_id (int) number of failed update
52 * @param error_message (str) error message
54 public static function updateFail($update_id, $error_message) {
57 //send the administrators an e-mail
58 $admin_mail_list = "'".implode("','", array_map(['Friendica\Database\DBA', 'escape'], explode(",", str_replace(" ", "", Config::get('config', 'admin_email')))))."'";
59 $adminlist = q("SELECT uid, language, email FROM user WHERE email IN (%s)",
64 if (!DBA::isResult($adminlist)) {
65 logger(sprintf('Cannot notify administrators about update_id=%d, error_message=%s', $update_id, $error_message), LOGGER_INFO);
71 // every admin could had different language
72 foreach ($adminlist as $admin) {
73 $lang = (($admin['language'])?$admin['language']:'en');
74 L10n::pushLang($lang);
76 $preamble = deindent(L10n::t("
77 The friendica developers released update %s recently,
78 but when I tried to install it, something went terribly wrong.
79 This needs to be fixed soon and I can't do it alone. Please contact a
80 friendica developer if you can not help me on your own. My database might be invalid."));
81 $body = L10n::t("The error message is\n[pre]%s[/pre]");
82 $preamble = sprintf($preamble, $update_id);
83 $body = sprintf($body, $error_message);
86 'uid' => $admin['uid'],
87 'type' => SYSTEM_EMAIL,
88 'to_email' => $admin['email'],
89 'preamble' => $preamble,
97 logger("CRITICAL: Database structure update failed: ".$error_message);
101 private static function tableStructure($table) {
102 $structures = q("DESCRIBE `%s`", $table);
104 $full_columns = q("SHOW FULL COLUMNS FROM `%s`", $table);
106 $indexes = q("SHOW INDEX FROM `%s`", $table);
108 $table_status = q("SHOW TABLE STATUS WHERE `name` = '%s'", $table);
110 if (DBA::isResult($table_status)) {
111 $table_status = $table_status[0];
119 if (DBA::isResult($indexes)) {
120 foreach ($indexes AS $index) {
121 if ($index['Key_name'] != 'PRIMARY' && $index['Non_unique'] == '0' && !isset($indexdata[$index["Key_name"]])) {
122 $indexdata[$index["Key_name"]] = ['UNIQUE'];
125 $column = $index["Column_name"];
127 if ($index["Sub_part"] != "") {
128 $column .= "(".$index["Sub_part"].")";
131 $indexdata[$index["Key_name"]][] = $column;
134 if (DBA::isResult($structures)) {
135 foreach ($structures AS $field) {
136 // Replace the default size values so that we don't have to define them
137 $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)'];
138 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
139 $field["Type"] = str_replace($search, $replace, $field["Type"]);
141 $fielddata[$field["Field"]]["type"] = $field["Type"];
142 if ($field["Null"] == "NO") {
143 $fielddata[$field["Field"]]["not null"] = true;
146 if (isset($field["Default"])) {
147 $fielddata[$field["Field"]]["default"] = $field["Default"];
150 if ($field["Extra"] != "") {
151 $fielddata[$field["Field"]]["extra"] = $field["Extra"];
154 if ($field["Key"] == "PRI") {
155 $fielddata[$field["Field"]]["primary"] = true;
159 if (DBA::isResult($full_columns)) {
160 foreach ($full_columns AS $column) {
161 $fielddata[$column["Field"]]["Collation"] = $column["Collation"];
162 $fielddata[$column["Field"]]["comment"] = $column["Comment"];
166 return ["fields" => $fielddata, "indexes" => $indexdata, "table_status" => $table_status];
169 public static function printStructure() {
170 $database = self::definition();
172 echo "-- ------------------------------------------\n";
173 echo "-- ".FRIENDICA_PLATFORM." ".FRIENDICA_VERSION." (".FRIENDICA_CODENAME,")\n";
174 echo "-- DB_UPDATE_VERSION ".DB_UPDATE_VERSION."\n";
175 echo "-- ------------------------------------------\n\n\n";
176 foreach ($database AS $name => $structure) {
178 echo "-- TABLE $name\n";
180 self::createTable($name, $structure, true, false);
187 * @brief Print out database error messages
189 * @param string $message Message to be added to the error message
191 * @return string Error message
193 private static function printUpdateError($message) {
194 echo L10n::t("\nError %d occurred during database update:\n%s\n",
195 DBA::errorNo(), DBA::errorMessage());
197 return L10n::t('Errors encountered performing database changes: ').$message.EOL;
201 * Updates DB structure and returns eventual errors messages
203 * @param bool $verbose
204 * @param bool $action Whether to actually apply the update
205 * @param bool $install Is this the initial update during the installation?
206 * @param array $tables An array of the database tables
207 * @param array $definition An array of the definition tables
208 * @return string Empty string if the update is successful, error messages otherwise
210 public static function update($verbose, $action, $install = false, array $tables = null, array $definition = null) {
211 if ($action && !$install) {
212 Config::set('system', 'maintenance', 1);
213 Config::set('system', 'maintenance_reason', L10n::t('%s: Database update', DateTimeFormat::utcNow().' '.date('e')));
218 logger('updating structure', LOGGER_DEBUG);
220 // Get the current structure
223 if (is_null($tables)) {
224 $tables = q("SHOW TABLES");
227 if (DBA::isResult($tables)) {
228 foreach ($tables AS $table) {
229 $table = current($table);
231 logger(sprintf('updating structure for table %s ...', $table), LOGGER_DEBUG);
232 $database[$table] = self::tableStructure($table);
236 // Get the definition
237 if (is_null($definition)) {
238 $definition = self::definition();
241 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
242 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
243 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
250 foreach ($definition AS $name => $structure) {
251 $is_new_table = false;
256 if (!isset($database[$name])) {
257 $r = self::createTable($name, $structure, $verbose, $action);
258 if (!DBA::isResult($r)) {
259 $errors .= self::printUpdateError($name);
261 $is_new_table = true;
263 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
264 if (isset($database[$name]["indexes"][$indexname])) {
265 $current_index_definition = implode(",",$database[$name]["indexes"][$indexname]);
267 $current_index_definition = "__NOT_SET__";
269 $new_index_definition = implode(",",$fieldnames);
270 if ($current_index_definition != $new_index_definition) {
271 if ($fieldnames[0] == "UNIQUE") {
274 $temp_name = "temp-".$name;
281 * Drop the index if it isn't present in the definition
282 * or the definition differ from current status
283 * and index name doesn't start with "local_"
285 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
286 $current_index_definition = implode(",",$fieldnames);
287 if (isset($structure["indexes"][$indexname])) {
288 $new_index_definition = implode(",",$structure["indexes"][$indexname]);
290 $new_index_definition = "__NOT_SET__";
292 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
293 $sql2=self::dropIndex($indexname);
295 $sql3 = "ALTER".$ignore." TABLE `".$temp_name."` ".$sql2;
301 // Compare the field structure field by field
302 foreach ($structure["fields"] AS $fieldname => $parameters) {
303 if (!isset($database[$name]["fields"][$fieldname])) {
304 $sql2=self::addTableField($fieldname, $parameters);
306 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
311 // Compare the field definition
312 $field_definition = $database[$name]["fields"][$fieldname];
314 // Remove the relation data that is used for the referential integrity
315 unset($parameters['relation']);
317 // We change the collation after the indexes had been changed.
318 // This is done to avoid index length problems.
319 // So here we always ensure that there is no need to change it.
320 unset($parameters['Collation']);
321 unset($field_definition['Collation']);
323 // Only update the comment when it is defined
324 if (!isset($parameters['comment'])) {
325 $parameters['comment'] = "";
328 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
329 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
330 if ($current_field_definition != $new_field_definition) {
331 $sql2 = self::modifyTableField($fieldname, $parameters);
333 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
343 * Create the index if the index don't exists in database
344 * or the definition differ from the current status.
345 * Don't create keys if table is new
347 if (!$is_new_table) {
348 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
349 if (isset($database[$name]["indexes"][$indexname])) {
350 $current_index_definition = implode(",",$database[$name]["indexes"][$indexname]);
352 $current_index_definition = "__NOT_SET__";
354 $new_index_definition = implode(",",$fieldnames);
355 if ($current_index_definition != $new_index_definition) {
356 $sql2 = self::createIndex($indexname, $fieldnames);
358 // Fetch the "group by" fields for unique indexes
359 if ($fieldnames[0] == "UNIQUE") {
360 $group_by = self::groupBy($indexname, $fieldnames);
364 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
372 if (isset($database[$name]["table_status"]["Comment"])) {
373 if ($database[$name]["table_status"]["Comment"] != $structure['comment']) {
374 $sql2 = "COMMENT = '".DBA::escape($structure['comment'])."'";
377 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
384 if (isset($database[$name]["table_status"]["Engine"]) && isset($structure['engine'])) {
385 if ($database[$name]["table_status"]["Engine"] != $structure['engine']) {
386 $sql2 = "ENGINE = '".DBA::escape($structure['engine'])."'";
389 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
396 if (isset($database[$name]["table_status"]["Collation"])) {
397 if ($database[$name]["table_status"]["Collation"] != 'utf8mb4_general_ci') {
398 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
401 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
412 // Now have a look at the field collations
413 // Compare the field structure field by field
414 foreach ($structure["fields"] AS $fieldname => $parameters) {
415 // Compare the field definition
416 $field_definition = defaults($database[$name]["fields"], $fieldname, ['Collation' => '']);
418 // Define the default collation if not given
419 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
420 $parameters['Collation'] = 'utf8mb4_general_ci';
422 $parameters['Collation'] = null;
425 if ($field_definition['Collation'] != $parameters['Collation']) {
426 $sql2 = self::modifyTableField($fieldname, $parameters);
427 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
428 $sql3 .= "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
437 if (substr($sql3, -2, 2) != "; ") {
442 if ($is_unique && $ignore == '') {
443 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
444 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
446 $field_list = rtrim($field_list, ',');
450 // Ensure index conversion to unique removes duplicates
451 if ($is_unique && ($temp_name != $name)) {
453 echo "SET session old_alter_table=1;\n";
455 echo "DROP TABLE IF EXISTS `".$temp_name."`;\n";
456 echo "CREATE TABLE `".$temp_name."` LIKE `".$name."`;\n";
462 if ($is_unique && ($temp_name != $name)) {
464 echo "SET session old_alter_table=0;\n";
466 echo "INSERT INTO `".$temp_name."` SELECT ".DBA::anyValueFallback($field_list)." FROM `".$name."`".$group_by.";\n";
467 echo "DROP TABLE `".$name."`;\n";
468 echo "RENAME TABLE `".$temp_name."` TO `".$name."`;\n";
475 Config::set('system', 'maintenance_reason', L10n::t('%s: updating %s table.', DateTimeFormat::utcNow().' '.date('e'), $name));
478 // Ensure index conversion to unique removes duplicates
479 if ($is_unique && ($temp_name != $name)) {
481 DBA::e("SET session old_alter_table=1;");
483 $r = DBA::e("DROP TABLE IF EXISTS `".$temp_name."`;");
484 if (!DBA::isResult($r)) {
485 $errors .= self::printUpdateError($sql3);
489 $r = DBA::e("CREATE TABLE `".$temp_name."` LIKE `".$name."`;");
490 if (!DBA::isResult($r)) {
491 $errors .= self::printUpdateError($sql3);
498 if (!DBA::isResult($r)) {
499 $errors .= self::printUpdateError($sql3);
501 if ($is_unique && ($temp_name != $name)) {
503 DBA::e("SET session old_alter_table=0;");
505 $r = DBA::e("INSERT INTO `".$temp_name."` SELECT ".$field_list." FROM `".$name."`".$group_by.";");
506 if (!DBA::isResult($r)) {
507 $errors .= self::printUpdateError($sql3);
510 $r = DBA::e("DROP TABLE `".$name."`;");
511 if (!DBA::isResult($r)) {
512 $errors .= self::printUpdateError($sql3);
515 $r = DBA::e("RENAME TABLE `".$temp_name."` TO `".$name."`;");
516 if (!DBA::isResult($r)) {
517 $errors .= self::printUpdateError($sql3);
526 if ($action && !$install) {
527 Config::set('system', 'maintenance', 0);
528 Config::set('system', 'maintenance_reason', '');
531 Config::set('system', 'dbupdate', DB_UPDATE_FAILED);
533 Config::set('system', 'dbupdate', DB_UPDATE_SUCCESSFUL);
540 private static function FieldCommand($parameters, $create = true) {
541 $fieldstruct = $parameters["type"];
543 if (isset($parameters["Collation"])) {
544 $fieldstruct .= " COLLATE ".$parameters["Collation"];
547 if (isset($parameters["not null"])) {
548 $fieldstruct .= " NOT NULL";
551 if (isset($parameters["default"])) {
552 if (strpos(strtolower($parameters["type"]),"int")!==false) {
553 $fieldstruct .= " DEFAULT ".$parameters["default"];
555 $fieldstruct .= " DEFAULT '".$parameters["default"]."'";
558 if (isset($parameters["extra"])) {
559 $fieldstruct .= " ".$parameters["extra"];
562 if (isset($parameters["comment"])) {
563 $fieldstruct .= " COMMENT '".DBA::escape($parameters["comment"])."'";
566 /*if (($parameters["primary"] != "") && $create)
567 $fieldstruct .= " PRIMARY KEY";*/
569 return($fieldstruct);
572 private static function createTable($name, $structure, $verbose, $action) {
579 foreach ($structure["fields"] AS $fieldname => $field) {
580 $sql_rows[] = "`".DBA::escape($fieldname)."` ".self::FieldCommand($field);
581 if (x($field,'primary') && $field['primary']!='') {
582 $primary_keys[] = $fieldname;
586 if (!empty($structure["indexes"])) {
587 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
588 $sql_index = self::createIndex($indexname, $fieldnames, "");
589 if (!is_null($sql_index)) {
590 $sql_rows[] = $sql_index;
595 if (isset($structure["engine"])) {
596 $engine = " ENGINE=" . $structure["engine"];
599 if (isset($structure["comment"])) {
600 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
603 $sql = implode(",\n\t", $sql_rows);
605 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)).$sql.
606 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
618 private static function addTableField($fieldname, $parameters) {
619 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
623 private static function modifyTableField($fieldname, $parameters) {
624 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
628 private static function dropIndex($indexname) {
629 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
633 private static function createIndex($indexname, $fieldnames, $method = "ADD") {
634 $method = strtoupper(trim($method));
635 if ($method!="" && $method!="ADD") {
636 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
639 if ($fieldnames[0] == "UNIQUE") {
640 array_shift($fieldnames);
641 $method .= ' UNIQUE';
645 foreach ($fieldnames AS $fieldname) {
650 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
651 $names .= "`".DBA::escape($matches[1])."`(".intval($matches[2]).")";
653 $names .= "`".DBA::escape($fieldname)."`";
657 if ($indexname == "PRIMARY") {
658 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
662 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
666 private static function groupBy($indexname, $fieldnames) {
667 if ($fieldnames[0] != "UNIQUE") {
671 array_shift($fieldnames);
674 foreach ($fieldnames AS $fieldname) {
679 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
680 $names .= "`".DBA::escape($matches[1])."`";
682 $names .= "`".DBA::escape($fieldname)."`";
686 $sql = sprintf(" GROUP BY %s", $names);
691 * Check if a table exists
693 * @param string $table Table name
695 * @return boolean Does the table exist?
697 public static function existsTable($table)
703 $table = DBA::escape($table);
705 $sql = "SHOW TABLES LIKE '" . $table . "';";
707 $stmt = DBA::p($sql);
709 if (is_bool($stmt)) {
712 $retval = (DBA::numRows($stmt) > 0);
721 * Check if the columns of the table exists
723 * @param string $table Table name
724 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
726 * @return boolean Does the table exist?
728 public static function existsColumn($table, $columns = []) {
733 if (is_null($columns) || empty($columns)) {
734 return self::existsTable($table);
737 $table = DBA::escape($table);
739 foreach ($columns AS $column) {
740 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
742 $stmt = DBA::p($sql);
744 if (is_bool($stmt)) {
747 $retval = (DBA::numRows($stmt) > 0);
760 const RENAME_COLUMN = 0;
761 const RENAME_PRIMARY_KEY = 1;
764 * Renames columns or the primary key of a table
765 * @todo You cannot rename a primary key if "auto increment" is set
767 * @param string $table Table name
768 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ] )
769 * Syntax for Primary Key: [ $col1, $col2, ...] )
770 * @param int $type The type of renaming (Default is Column)
772 * @return boolean Was the renaming successful?
775 public static function rename($table, $columns, $type = self::RENAME_COLUMN) {
776 if (empty($table) || empty($columns)) {
780 if (!is_array($columns)) {
784 $table = DBA::escape($table);
786 $sql = "ALTER TABLE `" . $table . "`";
788 case self::RENAME_COLUMN:
789 if (!self::existsColumn($table, array_keys($columns))) {
792 $sql .= implode(',', array_map(
793 function ($to, $from) {
794 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
800 case self::RENAME_PRIMARY_KEY:
801 if (!self::existsColumn($table, $columns)) {
804 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
812 $stmt = DBA::p($sql);
814 if (is_bool($stmt)) {
826 * Loads the database structure definition from the /config/dbstructure.json file
830 * "comment": "meaningful table comment",
832 * "field_name1": {"type": "int unsigned", "not null": "1", "extra": "auto_increment", "primary": "1", "comment": "meaningful field comment"},
833 * "field_name2": {"type": "varchar(50)", "not null": "1", "default": "", "comment": "meaningful field comment"},
836 * "PRIMARY": ["field_name1"],
837 * "name": ["UNIQUE", "field_name2"]
844 public static function definition() {
845 $a = \Friendica\BaseObject::getApp();
847 $filename = $a->getBasePath() . '/config/dbstructure.json';
849 if (!is_readable($filename)) {
850 throw new Exception('Missing database structure config file config/dbstructure.json');
853 $json = file_get_contents($filename);
855 $database = json_decode($json, true);
858 throw new Exception('Corrupted database structure config file config/dbstructure.json');
861 Addon::callHooks('dbstructure_definition', $database);