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 'type' => SYSTEM_EMAIL,
87 'to_email' => $admin['email'],
88 'preamble' => $preamble,
95 logger("CRITICAL: Database structure update failed: ".$error_message);
99 private static function tableStructure($table) {
100 $structures = q("DESCRIBE `%s`", $table);
102 $full_columns = q("SHOW FULL COLUMNS FROM `%s`", $table);
104 $indexes = q("SHOW INDEX FROM `%s`", $table);
106 $table_status = q("SHOW TABLE STATUS WHERE `name` = '%s'", $table);
108 if (DBA::isResult($table_status)) {
109 $table_status = $table_status[0];
117 if (DBA::isResult($indexes)) {
118 foreach ($indexes AS $index) {
119 if ($index['Key_name'] != 'PRIMARY' && $index['Non_unique'] == '0' && !isset($indexdata[$index["Key_name"]])) {
120 $indexdata[$index["Key_name"]] = ['UNIQUE'];
123 $column = $index["Column_name"];
125 if ($index["Sub_part"] != "") {
126 $column .= "(".$index["Sub_part"].")";
129 $indexdata[$index["Key_name"]][] = $column;
132 if (DBA::isResult($structures)) {
133 foreach ($structures AS $field) {
134 // Replace the default size values so that we don't have to define them
135 $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)'];
136 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
137 $field["Type"] = str_replace($search, $replace, $field["Type"]);
139 $fielddata[$field["Field"]]["type"] = $field["Type"];
140 if ($field["Null"] == "NO") {
141 $fielddata[$field["Field"]]["not null"] = true;
144 if (isset($field["Default"])) {
145 $fielddata[$field["Field"]]["default"] = $field["Default"];
148 if ($field["Extra"] != "") {
149 $fielddata[$field["Field"]]["extra"] = $field["Extra"];
152 if ($field["Key"] == "PRI") {
153 $fielddata[$field["Field"]]["primary"] = true;
157 if (DBA::isResult($full_columns)) {
158 foreach ($full_columns AS $column) {
159 $fielddata[$column["Field"]]["Collation"] = $column["Collation"];
160 $fielddata[$column["Field"]]["comment"] = $column["Comment"];
164 return ["fields" => $fielddata, "indexes" => $indexdata, "table_status" => $table_status];
167 public static function printStructure() {
168 $database = self::definition();
170 echo "-- ------------------------------------------\n";
171 echo "-- ".FRIENDICA_PLATFORM." ".FRIENDICA_VERSION." (".FRIENDICA_CODENAME,")\n";
172 echo "-- DB_UPDATE_VERSION ".DB_UPDATE_VERSION."\n";
173 echo "-- ------------------------------------------\n\n\n";
174 foreach ($database AS $name => $structure) {
176 echo "-- TABLE $name\n";
178 self::createTable($name, $structure, true, false);
185 * @brief Print out database error messages
187 * @param string $message Message to be added to the error message
189 * @return string Error message
191 private static function printUpdateError($message) {
192 echo L10n::t("\nError %d occurred during database update:\n%s\n",
193 DBA::errorNo(), DBA::errorMessage());
195 return L10n::t('Errors encountered performing database changes: ').$message.EOL;
199 * Updates DB structure and returns eventual errors messages
201 * @param bool $verbose
202 * @param bool $action Whether to actually apply the update
203 * @param bool $install Is this the initial update during the installation?
204 * @param array $tables An array of the database tables
205 * @param array $definition An array of the definition tables
206 * @return string Empty string if the update is successful, error messages otherwise
208 public static function update($verbose, $action, $install = false, array $tables = null, array $definition = null) {
209 if ($action && !$install) {
210 Config::set('system', 'maintenance', 1);
211 Config::set('system', 'maintenance_reason', L10n::t('%s: Database update', DateTimeFormat::utcNow().' '.date('e')));
216 logger('updating structure', LOGGER_DEBUG);
218 // Get the current structure
221 if (is_null($tables)) {
222 $tables = q("SHOW TABLES");
225 if (DBA::isResult($tables)) {
226 foreach ($tables AS $table) {
227 $table = current($table);
229 logger(sprintf('updating structure for table %s ...', $table), LOGGER_DEBUG);
230 $database[$table] = self::tableStructure($table);
234 // Get the definition
235 if (is_null($definition)) {
236 $definition = self::definition();
239 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
240 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
241 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
248 foreach ($definition AS $name => $structure) {
249 $is_new_table = false;
254 if (!isset($database[$name])) {
255 $r = self::createTable($name, $structure, $verbose, $action);
256 if (!DBA::isResult($r)) {
257 $errors .= self::printUpdateError($name);
259 $is_new_table = true;
261 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
262 if (isset($database[$name]["indexes"][$indexname])) {
263 $current_index_definition = implode(",",$database[$name]["indexes"][$indexname]);
265 $current_index_definition = "__NOT_SET__";
267 $new_index_definition = implode(",",$fieldnames);
268 if ($current_index_definition != $new_index_definition) {
269 if ($fieldnames[0] == "UNIQUE") {
272 $temp_name = "temp-".$name;
279 * Drop the index if it isn't present in the definition
280 * or the definition differ from current status
281 * and index name doesn't start with "local_"
283 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
284 $current_index_definition = implode(",",$fieldnames);
285 if (isset($structure["indexes"][$indexname])) {
286 $new_index_definition = implode(",",$structure["indexes"][$indexname]);
288 $new_index_definition = "__NOT_SET__";
290 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
291 $sql2=self::dropIndex($indexname);
293 $sql3 = "ALTER".$ignore." TABLE `".$temp_name."` ".$sql2;
299 // Compare the field structure field by field
300 foreach ($structure["fields"] AS $fieldname => $parameters) {
301 if (!isset($database[$name]["fields"][$fieldname])) {
302 $sql2=self::addTableField($fieldname, $parameters);
304 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
309 // Compare the field definition
310 $field_definition = $database[$name]["fields"][$fieldname];
312 // Remove the relation data that is used for the referential integrity
313 unset($parameters['relation']);
315 // We change the collation after the indexes had been changed.
316 // This is done to avoid index length problems.
317 // So here we always ensure that there is no need to change it.
318 unset($parameters['Collation']);
319 unset($field_definition['Collation']);
321 // Only update the comment when it is defined
322 if (!isset($parameters['comment'])) {
323 $parameters['comment'] = "";
326 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
327 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
328 if ($current_field_definition != $new_field_definition) {
329 $sql2 = self::modifyTableField($fieldname, $parameters);
331 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
341 * Create the index if the index don't exists in database
342 * or the definition differ from the current status.
343 * Don't create keys if table is new
345 if (!$is_new_table) {
346 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
347 if (isset($database[$name]["indexes"][$indexname])) {
348 $current_index_definition = implode(",",$database[$name]["indexes"][$indexname]);
350 $current_index_definition = "__NOT_SET__";
352 $new_index_definition = implode(",",$fieldnames);
353 if ($current_index_definition != $new_index_definition) {
354 $sql2 = self::createIndex($indexname, $fieldnames);
356 // Fetch the "group by" fields for unique indexes
357 if ($fieldnames[0] == "UNIQUE") {
358 $group_by = self::groupBy($indexname, $fieldnames);
362 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
370 if (isset($database[$name]["table_status"]["Comment"])) {
371 if ($database[$name]["table_status"]["Comment"] != $structure['comment']) {
372 $sql2 = "COMMENT = '".DBA::escape($structure['comment'])."'";
375 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
382 if (isset($database[$name]["table_status"]["Engine"]) && isset($structure['engine'])) {
383 if ($database[$name]["table_status"]["Engine"] != $structure['engine']) {
384 $sql2 = "ENGINE = '".DBA::escape($structure['engine'])."'";
387 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
394 if (isset($database[$name]["table_status"]["Collation"])) {
395 if ($database[$name]["table_status"]["Collation"] != 'utf8mb4_general_ci') {
396 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
399 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
410 // Now have a look at the field collations
411 // Compare the field structure field by field
412 foreach ($structure["fields"] AS $fieldname => $parameters) {
413 // Compare the field definition
414 $field_definition = defaults($database[$name]["fields"], $fieldname, ['Collation' => '']);
416 // Define the default collation if not given
417 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
418 $parameters['Collation'] = 'utf8mb4_general_ci';
420 $parameters['Collation'] = null;
423 if ($field_definition['Collation'] != $parameters['Collation']) {
424 $sql2 = self::modifyTableField($fieldname, $parameters);
425 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
426 $sql3 .= "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
435 if (substr($sql3, -2, 2) != "; ") {
440 if ($is_unique && $ignore == '') {
441 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
442 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
444 $field_list = rtrim($field_list, ',');
448 // Ensure index conversion to unique removes duplicates
449 if ($is_unique && ($temp_name != $name)) {
451 echo "SET session old_alter_table=1;\n";
453 echo "DROP TABLE IF EXISTS `".$temp_name."`;\n";
454 echo "CREATE TABLE `".$temp_name."` LIKE `".$name."`;\n";
460 if ($is_unique && ($temp_name != $name)) {
462 echo "SET session old_alter_table=0;\n";
464 echo "INSERT INTO `".$temp_name."` SELECT ".DBA::anyValueFallback($field_list)." FROM `".$name."`".$group_by.";\n";
465 echo "DROP TABLE `".$name."`;\n";
466 echo "RENAME TABLE `".$temp_name."` TO `".$name."`;\n";
473 Config::set('system', 'maintenance_reason', L10n::t('%s: updating %s table.', DateTimeFormat::utcNow().' '.date('e'), $name));
476 // Ensure index conversion to unique removes duplicates
477 if ($is_unique && ($temp_name != $name)) {
479 DBA::e("SET session old_alter_table=1;");
481 $r = DBA::e("DROP TABLE IF EXISTS `".$temp_name."`;");
482 if (!DBA::isResult($r)) {
483 $errors .= self::printUpdateError($sql3);
487 $r = DBA::e("CREATE TABLE `".$temp_name."` LIKE `".$name."`;");
488 if (!DBA::isResult($r)) {
489 $errors .= self::printUpdateError($sql3);
496 if (!DBA::isResult($r)) {
497 $errors .= self::printUpdateError($sql3);
499 if ($is_unique && ($temp_name != $name)) {
501 DBA::e("SET session old_alter_table=0;");
503 $r = DBA::e("INSERT INTO `".$temp_name."` SELECT ".$field_list." FROM `".$name."`".$group_by.";");
504 if (!DBA::isResult($r)) {
505 $errors .= self::printUpdateError($sql3);
508 $r = DBA::e("DROP TABLE `".$name."`;");
509 if (!DBA::isResult($r)) {
510 $errors .= self::printUpdateError($sql3);
513 $r = DBA::e("RENAME TABLE `".$temp_name."` TO `".$name."`;");
514 if (!DBA::isResult($r)) {
515 $errors .= self::printUpdateError($sql3);
524 if ($action && !$install) {
525 Config::set('system', 'maintenance', 0);
526 Config::set('system', 'maintenance_reason', '');
529 Config::set('system', 'dbupdate', DB_UPDATE_FAILED);
531 Config::set('system', 'dbupdate', DB_UPDATE_SUCCESSFUL);
538 private static function FieldCommand($parameters, $create = true) {
539 $fieldstruct = $parameters["type"];
541 if (isset($parameters["Collation"])) {
542 $fieldstruct .= " COLLATE ".$parameters["Collation"];
545 if (isset($parameters["not null"])) {
546 $fieldstruct .= " NOT NULL";
549 if (isset($parameters["default"])) {
550 if (strpos(strtolower($parameters["type"]),"int")!==false) {
551 $fieldstruct .= " DEFAULT ".$parameters["default"];
553 $fieldstruct .= " DEFAULT '".$parameters["default"]."'";
556 if (isset($parameters["extra"])) {
557 $fieldstruct .= " ".$parameters["extra"];
560 if (isset($parameters["comment"])) {
561 $fieldstruct .= " COMMENT '".DBA::escape($parameters["comment"])."'";
564 /*if (($parameters["primary"] != "") && $create)
565 $fieldstruct .= " PRIMARY KEY";*/
567 return($fieldstruct);
570 private static function createTable($name, $structure, $verbose, $action) {
577 foreach ($structure["fields"] AS $fieldname => $field) {
578 $sql_rows[] = "`".DBA::escape($fieldname)."` ".self::FieldCommand($field);
579 if (x($field,'primary') && $field['primary']!='') {
580 $primary_keys[] = $fieldname;
584 if (!empty($structure["indexes"])) {
585 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
586 $sql_index = self::createIndex($indexname, $fieldnames, "");
587 if (!is_null($sql_index)) {
588 $sql_rows[] = $sql_index;
593 if (isset($structure["engine"])) {
594 $engine = " ENGINE=" . $structure["engine"];
597 if (isset($structure["comment"])) {
598 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
601 $sql = implode(",\n\t", $sql_rows);
603 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)).$sql.
604 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
616 private static function addTableField($fieldname, $parameters) {
617 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
621 private static function modifyTableField($fieldname, $parameters) {
622 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
626 private static function dropIndex($indexname) {
627 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
631 private static function createIndex($indexname, $fieldnames, $method = "ADD") {
632 $method = strtoupper(trim($method));
633 if ($method!="" && $method!="ADD") {
634 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
637 if ($fieldnames[0] == "UNIQUE") {
638 array_shift($fieldnames);
639 $method .= ' UNIQUE';
643 foreach ($fieldnames AS $fieldname) {
648 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
649 $names .= "`".DBA::escape($matches[1])."`(".intval($matches[2]).")";
651 $names .= "`".DBA::escape($fieldname)."`";
655 if ($indexname == "PRIMARY") {
656 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
660 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
664 private static function groupBy($indexname, $fieldnames) {
665 if ($fieldnames[0] != "UNIQUE") {
669 array_shift($fieldnames);
672 foreach ($fieldnames AS $fieldname) {
677 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
678 $names .= "`".DBA::escape($matches[1])."`";
680 $names .= "`".DBA::escape($fieldname)."`";
684 $sql = sprintf(" GROUP BY %s", $names);
689 * Check if a table exists
691 * @param string $table Table name
693 * @return boolean Does the table exist?
695 public static function existsTable($table)
701 $table = DBA::escape($table);
703 $sql = "SHOW TABLES LIKE '" . $table . "';";
705 $stmt = DBA::p($sql);
707 if (is_bool($stmt)) {
710 $retval = (DBA::numRows($stmt) > 0);
719 * Check if the columns of the table exists
721 * @param string $table Table name
722 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
724 * @return boolean Does the table exist?
726 public static function existsColumn($table, $columns = []) {
731 if (is_null($columns) || empty($columns)) {
732 return self::existsTable($table);
735 $table = DBA::escape($table);
737 foreach ($columns AS $column) {
738 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
740 $stmt = DBA::p($sql);
742 if (is_bool($stmt)) {
745 $retval = (DBA::numRows($stmt) > 0);
758 const RENAME_COLUMN = 0;
759 const RENAME_PRIMARY_KEY = 1;
762 * Renames columns or the primary key of a table
763 * @todo You cannot rename a primary key if "auto increment" is set
765 * @param string $table Table name
766 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ] )
767 * Syntax for Primary Key: [ $col1, $col2, ...] )
768 * @param int $type The type of renaming (Default is Column)
770 * @return boolean Was the renaming successful?
773 public static function rename($table, $columns, $type = self::RENAME_COLUMN) {
774 if (empty($table) || empty($columns)) {
778 if (!is_array($columns)) {
782 $table = DBA::escape($table);
784 $sql = "ALTER TABLE `" . $table . "`";
786 case self::RENAME_COLUMN:
787 if (!self::existsColumn($table, array_keys($columns))) {
790 $sql .= implode(',', array_map(
791 function ($to, $from) {
792 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
798 case self::RENAME_PRIMARY_KEY:
799 if (!self::existsColumn($table, $columns)) {
802 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
810 $stmt = DBA::p($sql);
812 if (is_bool($stmt)) {
824 * Loads the database structure definition from the /config/dbstructure.json file
828 * "comment": "meaningful table comment",
830 * "field_name1": {"type": "int unsigned", "not null": "1", "extra": "auto_increment", "primary": "1", "comment": "meaningful field comment"},
831 * "field_name2": {"type": "varchar(50)", "not null": "1", "default": "", "comment": "meaningful field comment"},
834 * "PRIMARY": ["field_name1"],
835 * "name": ["UNIQUE", "field_name2"]
842 public static function definition() {
843 $a = \Friendica\BaseObject::getApp();
845 $filename = $a->get_basepath() . '/config/dbstructure.json';
847 if (!is_readable($filename)) {
848 throw new Exception('Missing database structure config file config/dbstructure.json');
851 $json = file_get_contents($filename);
853 $database = json_decode($json, true);
856 throw new Exception('Corrupted database structure config file config/dbstructure.json');
859 Addon::callHooks('dbstructure_definition', $database);