3 * @file src/Database/DBStructure.php
5 namespace Friendica\Database;
8 use Friendica\Core\Hook;
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 * Database structure definition loaded from config/dbstructure.php
30 private static $definition = [];
33 * Converts all tables from MyISAM to InnoDB
35 public static function convertToInnoDB() {
36 $r = q("SELECT `TABLE_NAME` FROM `information_schema`.`tables` WHERE `engine` = 'MyISAM' AND `table_schema` = '%s'",
37 DBA::escape(DBA::databaseName()));
39 if (!DBA::isResult($r)) {
40 echo L10n::t('There are no tables on MyISAM.')."\n";
44 foreach ($r AS $table) {
45 $sql = sprintf("ALTER TABLE `%s` engine=InnoDB;", DBA::escape($table['TABLE_NAME']));
48 $result = DBA::e($sql);
49 if (!DBA::isResult($result)) {
50 self::printUpdateError($sql);
56 * send the email and do what is needed to do on update fails
58 * @param update_id (int) number of failed update
59 * @param error_message (str) error message
61 public static function updateFail($update_id, $error_message) {
64 //send the administrators an e-mail
65 $admin_mail_list = "'".implode("','", array_map(['Friendica\Database\DBA', 'escape'], explode(",", str_replace(" ", "", Config::get('config', 'admin_email')))))."'";
66 $adminlist = q("SELECT uid, language, email FROM user WHERE email IN (%s)",
71 if (!DBA::isResult($adminlist)) {
72 logger(sprintf('Cannot notify administrators about update_id=%d, error_message=%s', $update_id, $error_message), LOGGER_INFO);
78 // every admin could had different language
79 foreach ($adminlist as $admin) {
80 $lang = (($admin['language'])?$admin['language']:'en');
81 L10n::pushLang($lang);
83 $preamble = deindent(L10n::t("
84 The friendica developers released update %s recently,
85 but when I tried to install it, something went terribly wrong.
86 This needs to be fixed soon and I can't do it alone. Please contact a
87 friendica developer if you can not help me on your own. My database might be invalid.",
89 $body = L10n::t("The error message is\n[pre]%s[/pre]", $error_message);
92 'uid' => $admin['uid'],
93 'type' => SYSTEM_EMAIL,
94 'to_email' => $admin['email'],
95 'preamble' => $preamble,
103 logger("CRITICAL: Database structure update failed: ".$error_message);
107 private static function tableStructure($table) {
108 $structures = q("DESCRIBE `%s`", $table);
110 $full_columns = q("SHOW FULL COLUMNS FROM `%s`", $table);
112 $indexes = q("SHOW INDEX FROM `%s`", $table);
114 $table_status = q("SHOW TABLE STATUS WHERE `name` = '%s'", $table);
116 if (DBA::isResult($table_status)) {
117 $table_status = $table_status[0];
125 if (DBA::isResult($indexes)) {
126 foreach ($indexes AS $index) {
127 if ($index['Key_name'] != 'PRIMARY' && $index['Non_unique'] == '0' && !isset($indexdata[$index["Key_name"]])) {
128 $indexdata[$index["Key_name"]] = ['UNIQUE'];
131 $column = $index["Column_name"];
133 if ($index["Sub_part"] != "") {
134 $column .= "(".$index["Sub_part"].")";
137 $indexdata[$index["Key_name"]][] = $column;
140 if (DBA::isResult($structures)) {
141 foreach ($structures AS $field) {
142 // Replace the default size values so that we don't have to define them
143 $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)'];
144 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
145 $field["Type"] = str_replace($search, $replace, $field["Type"]);
147 $fielddata[$field["Field"]]["type"] = $field["Type"];
148 if ($field["Null"] == "NO") {
149 $fielddata[$field["Field"]]["not null"] = true;
152 if (isset($field["Default"])) {
153 $fielddata[$field["Field"]]["default"] = $field["Default"];
156 if ($field["Extra"] != "") {
157 $fielddata[$field["Field"]]["extra"] = $field["Extra"];
160 if ($field["Key"] == "PRI") {
161 $fielddata[$field["Field"]]["primary"] = true;
165 if (DBA::isResult($full_columns)) {
166 foreach ($full_columns AS $column) {
167 $fielddata[$column["Field"]]["Collation"] = $column["Collation"];
168 $fielddata[$column["Field"]]["comment"] = $column["Comment"];
172 return ["fields" => $fielddata, "indexes" => $indexdata, "table_status" => $table_status];
175 public static function printStructure() {
176 $database = self::definition();
178 echo "-- ------------------------------------------\n";
179 echo "-- ".FRIENDICA_PLATFORM." ".FRIENDICA_VERSION." (".FRIENDICA_CODENAME,")\n";
180 echo "-- DB_UPDATE_VERSION ".DB_UPDATE_VERSION."\n";
181 echo "-- ------------------------------------------\n\n\n";
182 foreach ($database AS $name => $structure) {
184 echo "-- TABLE $name\n";
186 self::createTable($name, $structure, true, false);
193 * @brief Print out database error messages
195 * @param string $message Message to be added to the error message
197 * @return string Error message
199 private static function printUpdateError($message) {
200 echo L10n::t("\nError %d occurred during database update:\n%s\n",
201 DBA::errorNo(), DBA::errorMessage());
203 return L10n::t('Errors encountered performing database changes: ').$message.EOL;
207 * Updates DB structure and returns eventual errors messages
209 * @param bool $verbose
210 * @param bool $action Whether to actually apply the update
211 * @param bool $install Is this the initial update during the installation?
212 * @param array $tables An array of the database tables
213 * @param array $definition An array of the definition tables
214 * @return string Empty string if the update is successful, error messages otherwise
216 public static function update($verbose, $action, $install = false, array $tables = null, array $definition = null) {
217 if ($action && !$install) {
218 Config::set('system', 'maintenance', 1);
219 Config::set('system', 'maintenance_reason', L10n::t('%s: Database update', DateTimeFormat::utcNow().' '.date('e')));
224 logger('updating structure', LOGGER_DEBUG);
226 // Get the current structure
229 if (is_null($tables)) {
230 $tables = q("SHOW TABLES");
233 if (DBA::isResult($tables)) {
234 foreach ($tables AS $table) {
235 $table = current($table);
237 logger(sprintf('updating structure for table %s ...', $table), LOGGER_DEBUG);
238 $database[$table] = self::tableStructure($table);
242 // Get the definition
243 if (is_null($definition)) {
244 $definition = self::definition();
247 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
248 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
249 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
256 foreach ($definition AS $name => $structure) {
257 $is_new_table = false;
262 if (!isset($database[$name])) {
263 $r = self::createTable($name, $structure, $verbose, $action);
264 if (!DBA::isResult($r)) {
265 $errors .= self::printUpdateError($name);
267 $is_new_table = true;
269 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
270 if (isset($database[$name]["indexes"][$indexname])) {
271 $current_index_definition = implode(",",$database[$name]["indexes"][$indexname]);
273 $current_index_definition = "__NOT_SET__";
275 $new_index_definition = implode(",",$fieldnames);
276 if ($current_index_definition != $new_index_definition) {
277 if ($fieldnames[0] == "UNIQUE") {
280 $temp_name = "temp-".$name;
287 * Drop the index if it isn't present in the definition
288 * or the definition differ from current status
289 * and index name doesn't start with "local_"
291 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
292 $current_index_definition = implode(",",$fieldnames);
293 if (isset($structure["indexes"][$indexname])) {
294 $new_index_definition = implode(",",$structure["indexes"][$indexname]);
296 $new_index_definition = "__NOT_SET__";
298 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
299 $sql2=self::dropIndex($indexname);
301 $sql3 = "ALTER".$ignore." TABLE `".$temp_name."` ".$sql2;
307 // Compare the field structure field by field
308 foreach ($structure["fields"] AS $fieldname => $parameters) {
309 if (!isset($database[$name]["fields"][$fieldname])) {
310 $sql2=self::addTableField($fieldname, $parameters);
312 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
317 // Compare the field definition
318 $field_definition = $database[$name]["fields"][$fieldname];
320 // Remove the relation data that is used for the referential integrity
321 unset($parameters['relation']);
323 // We change the collation after the indexes had been changed.
324 // This is done to avoid index length problems.
325 // So here we always ensure that there is no need to change it.
326 unset($parameters['Collation']);
327 unset($field_definition['Collation']);
329 // Only update the comment when it is defined
330 if (!isset($parameters['comment'])) {
331 $parameters['comment'] = "";
334 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
335 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
336 if ($current_field_definition != $new_field_definition) {
337 $sql2 = self::modifyTableField($fieldname, $parameters);
339 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
349 * Create the index if the index don't exists in database
350 * or the definition differ from the current status.
351 * Don't create keys if table is new
353 if (!$is_new_table) {
354 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
355 if (isset($database[$name]["indexes"][$indexname])) {
356 $current_index_definition = implode(",",$database[$name]["indexes"][$indexname]);
358 $current_index_definition = "__NOT_SET__";
360 $new_index_definition = implode(",",$fieldnames);
361 if ($current_index_definition != $new_index_definition) {
362 $sql2 = self::createIndex($indexname, $fieldnames);
364 // Fetch the "group by" fields for unique indexes
365 if ($fieldnames[0] == "UNIQUE") {
366 $group_by = self::groupBy($indexname, $fieldnames);
370 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
378 if (isset($database[$name]["table_status"]["Comment"])) {
379 if ($database[$name]["table_status"]["Comment"] != $structure['comment']) {
380 $sql2 = "COMMENT = '".DBA::escape($structure['comment'])."'";
383 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
390 if (isset($database[$name]["table_status"]["Engine"]) && isset($structure['engine'])) {
391 if ($database[$name]["table_status"]["Engine"] != $structure['engine']) {
392 $sql2 = "ENGINE = '".DBA::escape($structure['engine'])."'";
395 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
402 if (isset($database[$name]["table_status"]["Collation"])) {
403 if ($database[$name]["table_status"]["Collation"] != 'utf8mb4_general_ci') {
404 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
407 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
418 // Now have a look at the field collations
419 // Compare the field structure field by field
420 foreach ($structure["fields"] AS $fieldname => $parameters) {
421 // Compare the field definition
422 $field_definition = defaults($database[$name]["fields"], $fieldname, ['Collation' => '']);
424 // Define the default collation if not given
425 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
426 $parameters['Collation'] = 'utf8mb4_general_ci';
428 $parameters['Collation'] = null;
431 if ($field_definition['Collation'] != $parameters['Collation']) {
432 $sql2 = self::modifyTableField($fieldname, $parameters);
433 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
434 $sql3 .= "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
443 if (substr($sql3, -2, 2) != "; ") {
448 if ($is_unique && $ignore == '') {
449 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
450 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
452 $field_list = rtrim($field_list, ',');
456 // Ensure index conversion to unique removes duplicates
457 if ($is_unique && ($temp_name != $name)) {
459 echo "SET session old_alter_table=1;\n";
461 echo "DROP TABLE IF EXISTS `".$temp_name."`;\n";
462 echo "CREATE TABLE `".$temp_name."` LIKE `".$name."`;\n";
468 if ($is_unique && ($temp_name != $name)) {
470 echo "SET session old_alter_table=0;\n";
472 echo "INSERT INTO `".$temp_name."` SELECT ".DBA::anyValueFallback($field_list)." FROM `".$name."`".$group_by.";\n";
473 echo "DROP TABLE `".$name."`;\n";
474 echo "RENAME TABLE `".$temp_name."` TO `".$name."`;\n";
481 Config::set('system', 'maintenance_reason', L10n::t('%s: updating %s table.', DateTimeFormat::utcNow().' '.date('e'), $name));
484 // Ensure index conversion to unique removes duplicates
485 if ($is_unique && ($temp_name != $name)) {
487 DBA::e("SET session old_alter_table=1;");
489 $r = DBA::e("DROP TABLE IF EXISTS `".$temp_name."`;");
490 if (!DBA::isResult($r)) {
491 $errors .= self::printUpdateError($sql3);
495 $r = DBA::e("CREATE TABLE `".$temp_name."` LIKE `".$name."`;");
496 if (!DBA::isResult($r)) {
497 $errors .= self::printUpdateError($sql3);
504 if (!DBA::isResult($r)) {
505 $errors .= self::printUpdateError($sql3);
507 if ($is_unique && ($temp_name != $name)) {
509 DBA::e("SET session old_alter_table=0;");
511 $r = DBA::e("INSERT INTO `".$temp_name."` SELECT ".$field_list." FROM `".$name."`".$group_by.";");
512 if (!DBA::isResult($r)) {
513 $errors .= self::printUpdateError($sql3);
516 $r = DBA::e("DROP TABLE `".$name."`;");
517 if (!DBA::isResult($r)) {
518 $errors .= self::printUpdateError($sql3);
521 $r = DBA::e("RENAME TABLE `".$temp_name."` TO `".$name."`;");
522 if (!DBA::isResult($r)) {
523 $errors .= self::printUpdateError($sql3);
532 if ($action && !$install) {
533 Config::set('system', 'maintenance', 0);
534 Config::set('system', 'maintenance_reason', '');
537 Config::set('system', 'dbupdate', DB_UPDATE_FAILED);
539 Config::set('system', 'dbupdate', DB_UPDATE_SUCCESSFUL);
546 private static function FieldCommand($parameters, $create = true) {
547 $fieldstruct = $parameters["type"];
549 if (isset($parameters["Collation"])) {
550 $fieldstruct .= " COLLATE ".$parameters["Collation"];
553 if (isset($parameters["not null"])) {
554 $fieldstruct .= " NOT NULL";
557 if (isset($parameters["default"])) {
558 if (strpos(strtolower($parameters["type"]),"int")!==false) {
559 $fieldstruct .= " DEFAULT ".$parameters["default"];
561 $fieldstruct .= " DEFAULT '".$parameters["default"]."'";
564 if (isset($parameters["extra"])) {
565 $fieldstruct .= " ".$parameters["extra"];
568 if (isset($parameters["comment"])) {
569 $fieldstruct .= " COMMENT '".DBA::escape($parameters["comment"])."'";
572 /*if (($parameters["primary"] != "") && $create)
573 $fieldstruct .= " PRIMARY KEY";*/
575 return($fieldstruct);
578 private static function createTable($name, $structure, $verbose, $action) {
585 foreach ($structure["fields"] AS $fieldname => $field) {
586 $sql_rows[] = "`".DBA::escape($fieldname)."` ".self::FieldCommand($field);
587 if (x($field,'primary') && $field['primary']!='') {
588 $primary_keys[] = $fieldname;
592 if (!empty($structure["indexes"])) {
593 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
594 $sql_index = self::createIndex($indexname, $fieldnames, "");
595 if (!is_null($sql_index)) {
596 $sql_rows[] = $sql_index;
601 if (isset($structure["engine"])) {
602 $engine = " ENGINE=" . $structure["engine"];
605 if (isset($structure["comment"])) {
606 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
609 $sql = implode(",\n\t", $sql_rows);
611 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)).$sql.
612 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
624 private static function addTableField($fieldname, $parameters) {
625 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
629 private static function modifyTableField($fieldname, $parameters) {
630 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
634 private static function dropIndex($indexname) {
635 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
639 private static function createIndex($indexname, $fieldnames, $method = "ADD") {
640 $method = strtoupper(trim($method));
641 if ($method!="" && $method!="ADD") {
642 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
645 if ($fieldnames[0] == "UNIQUE") {
646 array_shift($fieldnames);
647 $method .= ' UNIQUE';
651 foreach ($fieldnames AS $fieldname) {
656 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
657 $names .= "`".DBA::escape($matches[1])."`(".intval($matches[2]).")";
659 $names .= "`".DBA::escape($fieldname)."`";
663 if ($indexname == "PRIMARY") {
664 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
668 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
672 private static function groupBy($indexname, $fieldnames) {
673 if ($fieldnames[0] != "UNIQUE") {
677 array_shift($fieldnames);
680 foreach ($fieldnames AS $fieldname) {
685 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
686 $names .= "`".DBA::escape($matches[1])."`";
688 $names .= "`".DBA::escape($fieldname)."`";
692 $sql = sprintf(" GROUP BY %s", $names);
697 * Check if a table exists
699 * @param string $table Table name
701 * @return boolean Does the table exist?
703 public static function existsTable($table)
709 $table = DBA::escape($table);
711 $sql = "SHOW TABLES LIKE '" . $table . "';";
713 $stmt = DBA::p($sql);
715 if (is_bool($stmt)) {
718 $retval = (DBA::numRows($stmt) > 0);
727 * Check if the columns of the table exists
729 * @param string $table Table name
730 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
732 * @return boolean Does the table exist?
734 public static function existsColumn($table, $columns = []) {
739 if (is_null($columns) || empty($columns)) {
740 return self::existsTable($table);
743 $table = DBA::escape($table);
745 foreach ($columns AS $column) {
746 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
748 $stmt = DBA::p($sql);
750 if (is_bool($stmt)) {
753 $retval = (DBA::numRows($stmt) > 0);
766 const RENAME_COLUMN = 0;
767 const RENAME_PRIMARY_KEY = 1;
770 * Renames columns or the primary key of a table
771 * @todo You cannot rename a primary key if "auto increment" is set
773 * @param string $table Table name
774 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ] )
775 * Syntax for Primary Key: [ $col1, $col2, ...] )
776 * @param int $type The type of renaming (Default is Column)
778 * @return boolean Was the renaming successful?
781 public static function rename($table, $columns, $type = self::RENAME_COLUMN) {
782 if (empty($table) || empty($columns)) {
786 if (!is_array($columns)) {
790 $table = DBA::escape($table);
792 $sql = "ALTER TABLE `" . $table . "`";
794 case self::RENAME_COLUMN:
795 if (!self::existsColumn($table, array_keys($columns))) {
798 $sql .= implode(',', array_map(
799 function ($to, $from) {
800 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
806 case self::RENAME_PRIMARY_KEY:
807 if (!self::existsColumn($table, $columns)) {
810 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
818 $stmt = DBA::p($sql);
820 if (is_bool($stmt)) {
832 * Loads the database structure definition from the config/dbstructure.php file.
834 * @see config/dbstructure.php
838 public static function definition()
840 if (!self::$definition) {
841 $a = \Friendica\BaseObject::getApp();
843 $filename = $a->getBasePath() . '/config/dbstructure.php';
845 if (!is_readable($filename)) {
846 throw new Exception('Missing database structure config file config/dbstructure.php');
849 $definition = require $filename;
852 throw new Exception('Corrupted database structure config file config/dbstructure.php');
855 self::$definition = $definition;
857 $definition = self::$definition;
860 Hook::callAll('dbstructure_definition', $definition);