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);
60 private static function tableStructure($table) {
61 $structures = q("DESCRIBE `%s`", $table);
63 $full_columns = q("SHOW FULL COLUMNS FROM `%s`", $table);
65 $indexes = q("SHOW INDEX FROM `%s`", $table);
67 $table_status = q("SHOW TABLE STATUS WHERE `name` = '%s'", $table);
69 if (DBA::isResult($table_status)) {
70 $table_status = $table_status[0];
78 if (DBA::isResult($indexes)) {
79 foreach ($indexes AS $index) {
80 if ($index['Key_name'] != 'PRIMARY' && $index['Non_unique'] == '0' && !isset($indexdata[$index["Key_name"]])) {
81 $indexdata[$index["Key_name"]] = ['UNIQUE'];
84 $column = $index["Column_name"];
86 if ($index["Sub_part"] != "") {
87 $column .= "(".$index["Sub_part"].")";
90 $indexdata[$index["Key_name"]][] = $column;
93 if (DBA::isResult($structures)) {
94 foreach ($structures AS $field) {
95 // Replace the default size values so that we don't have to define them
96 $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)'];
97 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
98 $field["Type"] = str_replace($search, $replace, $field["Type"]);
100 $fielddata[$field["Field"]]["type"] = $field["Type"];
101 if ($field["Null"] == "NO") {
102 $fielddata[$field["Field"]]["not null"] = true;
105 if (isset($field["Default"])) {
106 $fielddata[$field["Field"]]["default"] = $field["Default"];
109 if ($field["Extra"] != "") {
110 $fielddata[$field["Field"]]["extra"] = $field["Extra"];
113 if ($field["Key"] == "PRI") {
114 $fielddata[$field["Field"]]["primary"] = true;
118 if (DBA::isResult($full_columns)) {
119 foreach ($full_columns AS $column) {
120 $fielddata[$column["Field"]]["Collation"] = $column["Collation"];
121 $fielddata[$column["Field"]]["comment"] = $column["Comment"];
125 return ["fields" => $fielddata, "indexes" => $indexdata, "table_status" => $table_status];
128 public static function printStructure() {
129 $database = self::definition(false);
131 echo "-- ------------------------------------------\n";
132 echo "-- ".FRIENDICA_PLATFORM." ".FRIENDICA_VERSION." (".FRIENDICA_CODENAME,")\n";
133 echo "-- DB_UPDATE_VERSION ".DB_UPDATE_VERSION."\n";
134 echo "-- ------------------------------------------\n\n\n";
135 foreach ($database AS $name => $structure) {
137 echo "-- TABLE $name\n";
139 self::createTable($name, $structure, true, false);
146 * @brief Print out database error messages
148 * @param string $message Message to be added to the error message
150 * @return string Error message
152 private static function printUpdateError($message) {
153 echo L10n::t("\nError %d occurred during database update:\n%s\n",
154 DBA::errorNo(), DBA::errorMessage());
156 return L10n::t('Errors encountered performing database changes: ').$message.EOL;
160 * Updates DB structure and returns eventual errors messages
162 * @param bool $verbose
163 * @param bool $action Whether to actually apply the update
164 * @param bool $install Is this the initial update during the installation?
165 * @param array $tables An array of the database tables
166 * @param array $definition An array of the definition tables
167 * @return string Empty string if the update is successful, error messages otherwise
169 public static function update($verbose, $action, $install = false, array $tables = null, array $definition = null) {
170 if ($action && !$install) {
171 Config::set('system', 'maintenance', 1);
172 Config::set('system', 'maintenance_reason', L10n::t('%s: Database update', DateTimeFormat::utcNow().' '.date('e')));
177 Logger::log('updating structure', Logger::DEBUG);
179 // Get the current structure
182 if (is_null($tables)) {
183 $tables = q("SHOW TABLES");
186 if (DBA::isResult($tables)) {
187 foreach ($tables AS $table) {
188 $table = current($table);
190 Logger::log(sprintf('updating structure for table %s ...', $table), Logger::DEBUG);
191 $database[$table] = self::tableStructure($table);
195 // Get the definition
196 if (is_null($definition)) {
197 $definition = self::definition();
200 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
201 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
202 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
209 foreach ($definition AS $name => $structure) {
210 $is_new_table = false;
215 if (!isset($database[$name])) {
216 $r = self::createTable($name, $structure, $verbose, $action);
217 if (!DBA::isResult($r)) {
218 $errors .= self::printUpdateError($name);
220 $is_new_table = true;
222 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
223 if (isset($database[$name]["indexes"][$indexname])) {
224 $current_index_definition = implode(",",$database[$name]["indexes"][$indexname]);
226 $current_index_definition = "__NOT_SET__";
228 $new_index_definition = implode(",",$fieldnames);
229 if ($current_index_definition != $new_index_definition) {
230 if ($fieldnames[0] == "UNIQUE") {
233 $temp_name = "temp-".$name;
240 * Drop the index if it isn't present in the definition
241 * or the definition differ from current status
242 * and index name doesn't start with "local_"
244 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
245 $current_index_definition = implode(",",$fieldnames);
246 if (isset($structure["indexes"][$indexname])) {
247 $new_index_definition = implode(",",$structure["indexes"][$indexname]);
249 $new_index_definition = "__NOT_SET__";
251 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
252 $sql2=self::dropIndex($indexname);
254 $sql3 = "ALTER".$ignore." TABLE `".$temp_name."` ".$sql2;
260 // Compare the field structure field by field
261 foreach ($structure["fields"] AS $fieldname => $parameters) {
262 if (!isset($database[$name]["fields"][$fieldname])) {
263 $sql2=self::addTableField($fieldname, $parameters);
265 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
270 // Compare the field definition
271 $field_definition = $database[$name]["fields"][$fieldname];
273 // Remove the relation data that is used for the referential integrity
274 unset($parameters['relation']);
276 // We change the collation after the indexes had been changed.
277 // This is done to avoid index length problems.
278 // So here we always ensure that there is no need to change it.
279 unset($parameters['Collation']);
280 unset($field_definition['Collation']);
282 // Only update the comment when it is defined
283 if (!isset($parameters['comment'])) {
284 $parameters['comment'] = "";
287 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
288 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
289 if ($current_field_definition != $new_field_definition) {
290 $sql2 = self::modifyTableField($fieldname, $parameters);
292 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
302 * Create the index if the index don't exists in database
303 * or the definition differ from the current status.
304 * Don't create keys if table is new
306 if (!$is_new_table) {
307 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
308 if (isset($database[$name]["indexes"][$indexname])) {
309 $current_index_definition = implode(",",$database[$name]["indexes"][$indexname]);
311 $current_index_definition = "__NOT_SET__";
313 $new_index_definition = implode(",",$fieldnames);
314 if ($current_index_definition != $new_index_definition) {
315 $sql2 = self::createIndex($indexname, $fieldnames);
317 // Fetch the "group by" fields for unique indexes
318 if ($fieldnames[0] == "UNIQUE") {
319 $group_by = self::groupBy($indexname, $fieldnames);
323 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
331 if (isset($database[$name]["table_status"]["Comment"])) {
332 $structurecomment = defaults($structure, "comment", "");
333 if ($database[$name]["table_status"]["Comment"] != $structurecomment) {
334 $sql2 = "COMMENT = '".DBA::escape($structurecomment)."'";
337 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
344 if (isset($database[$name]["table_status"]["Engine"]) && isset($structure['engine'])) {
345 if ($database[$name]["table_status"]["Engine"] != $structure['engine']) {
346 $sql2 = "ENGINE = '".DBA::escape($structure['engine'])."'";
349 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
356 if (isset($database[$name]["table_status"]["Collation"])) {
357 if ($database[$name]["table_status"]["Collation"] != 'utf8mb4_general_ci') {
358 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
361 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
372 // Now have a look at the field collations
373 // Compare the field structure field by field
374 foreach ($structure["fields"] AS $fieldname => $parameters) {
375 // Compare the field definition
376 $field_definition = defaults($database[$name]["fields"], $fieldname, ['Collation' => '']);
378 // Define the default collation if not given
379 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
380 $parameters['Collation'] = 'utf8mb4_general_ci';
382 $parameters['Collation'] = null;
385 if ($field_definition['Collation'] != $parameters['Collation']) {
386 $sql2 = self::modifyTableField($fieldname, $parameters);
387 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
388 $sql3 .= "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
397 if (substr($sql3, -2, 2) != "; ") {
402 if ($is_unique && $ignore == '') {
403 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
404 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
406 $field_list = rtrim($field_list, ',');
410 // Ensure index conversion to unique removes duplicates
411 if ($is_unique && ($temp_name != $name)) {
413 echo "SET session old_alter_table=1;\n";
415 echo "DROP TABLE IF EXISTS `".$temp_name."`;\n";
416 echo "CREATE TABLE `".$temp_name."` LIKE `".$name."`;\n";
422 if ($is_unique && ($temp_name != $name)) {
424 echo "SET session old_alter_table=0;\n";
426 echo "INSERT INTO `".$temp_name."` SELECT ".DBA::anyValueFallback($field_list)." FROM `".$name."`".$group_by.";\n";
427 echo "DROP TABLE `".$name."`;\n";
428 echo "RENAME TABLE `".$temp_name."` TO `".$name."`;\n";
435 Config::set('system', 'maintenance_reason', L10n::t('%s: updating %s table.', DateTimeFormat::utcNow().' '.date('e'), $name));
438 // Ensure index conversion to unique removes duplicates
439 if ($is_unique && ($temp_name != $name)) {
441 DBA::e("SET session old_alter_table=1;");
443 $r = DBA::e("DROP TABLE IF EXISTS `".$temp_name."`;");
444 if (!DBA::isResult($r)) {
445 $errors .= self::printUpdateError($sql3);
449 $r = DBA::e("CREATE TABLE `".$temp_name."` LIKE `".$name."`;");
450 if (!DBA::isResult($r)) {
451 $errors .= self::printUpdateError($sql3);
458 if (!DBA::isResult($r)) {
459 $errors .= self::printUpdateError($sql3);
461 if ($is_unique && ($temp_name != $name)) {
463 DBA::e("SET session old_alter_table=0;");
465 $r = DBA::e("INSERT INTO `".$temp_name."` SELECT ".$field_list." FROM `".$name."`".$group_by.";");
466 if (!DBA::isResult($r)) {
467 $errors .= self::printUpdateError($sql3);
470 $r = DBA::e("DROP TABLE `".$name."`;");
471 if (!DBA::isResult($r)) {
472 $errors .= self::printUpdateError($sql3);
475 $r = DBA::e("RENAME TABLE `".$temp_name."` TO `".$name."`;");
476 if (!DBA::isResult($r)) {
477 $errors .= self::printUpdateError($sql3);
486 if ($action && !$install) {
487 Config::set('system', 'maintenance', 0);
488 Config::set('system', 'maintenance_reason', '');
491 Config::set('system', 'dbupdate', self::UPDATE_FAILED);
493 Config::set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
500 private static function FieldCommand($parameters, $create = true) {
501 $fieldstruct = $parameters["type"];
503 if (isset($parameters["Collation"])) {
504 $fieldstruct .= " COLLATE ".$parameters["Collation"];
507 if (isset($parameters["not null"])) {
508 $fieldstruct .= " NOT NULL";
511 if (isset($parameters["default"])) {
512 if (strpos(strtolower($parameters["type"]),"int")!==false) {
513 $fieldstruct .= " DEFAULT ".$parameters["default"];
515 $fieldstruct .= " DEFAULT '".$parameters["default"]."'";
518 if (isset($parameters["extra"])) {
519 $fieldstruct .= " ".$parameters["extra"];
522 if (isset($parameters["comment"])) {
523 $fieldstruct .= " COMMENT '".DBA::escape($parameters["comment"])."'";
526 /*if (($parameters["primary"] != "") && $create)
527 $fieldstruct .= " PRIMARY KEY";*/
529 return($fieldstruct);
532 private static function createTable($name, $structure, $verbose, $action) {
539 foreach ($structure["fields"] AS $fieldname => $field) {
540 $sql_rows[] = "`".DBA::escape($fieldname)."` ".self::FieldCommand($field);
541 if (x($field,'primary') && $field['primary']!='') {
542 $primary_keys[] = $fieldname;
546 if (!empty($structure["indexes"])) {
547 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
548 $sql_index = self::createIndex($indexname, $fieldnames, "");
549 if (!is_null($sql_index)) {
550 $sql_rows[] = $sql_index;
555 if (isset($structure["engine"])) {
556 $engine = " ENGINE=" . $structure["engine"];
559 if (isset($structure["comment"])) {
560 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
563 $sql = implode(",\n\t", $sql_rows);
565 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)).$sql.
566 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
578 private static function addTableField($fieldname, $parameters) {
579 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
583 private static function modifyTableField($fieldname, $parameters) {
584 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
588 private static function dropIndex($indexname) {
589 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
593 private static function createIndex($indexname, $fieldnames, $method = "ADD") {
594 $method = strtoupper(trim($method));
595 if ($method!="" && $method!="ADD") {
596 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
599 if ($fieldnames[0] == "UNIQUE") {
600 array_shift($fieldnames);
601 $method .= ' UNIQUE';
605 foreach ($fieldnames AS $fieldname) {
610 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
611 $names .= "`".DBA::escape($matches[1])."`(".intval($matches[2]).")";
613 $names .= "`".DBA::escape($fieldname)."`";
617 if ($indexname == "PRIMARY") {
618 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
622 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
626 private static function groupBy($indexname, $fieldnames) {
627 if ($fieldnames[0] != "UNIQUE") {
631 array_shift($fieldnames);
634 foreach ($fieldnames AS $fieldname) {
639 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
640 $names .= "`".DBA::escape($matches[1])."`";
642 $names .= "`".DBA::escape($fieldname)."`";
646 $sql = sprintf(" GROUP BY %s", $names);
651 * Check if a table exists
653 * @param string $table Table name
655 * @return boolean Does the table exist?
657 public static function existsTable($table)
663 $table = DBA::escape($table);
665 $sql = "SHOW TABLES LIKE '" . $table . "';";
667 $stmt = DBA::p($sql);
669 if (is_bool($stmt)) {
672 $retval = (DBA::numRows($stmt) > 0);
681 * Check if the columns of the table exists
683 * @param string $table Table name
684 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
686 * @return boolean Does the table exist?
688 public static function existsColumn($table, $columns = []) {
693 if (is_null($columns) || empty($columns)) {
694 return self::existsTable($table);
697 $table = DBA::escape($table);
699 foreach ($columns AS $column) {
700 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
702 $stmt = DBA::p($sql);
704 if (is_bool($stmt)) {
707 $retval = (DBA::numRows($stmt) > 0);
720 const RENAME_COLUMN = 0;
721 const RENAME_PRIMARY_KEY = 1;
724 * Renames columns or the primary key of a table
725 * @todo You cannot rename a primary key if "auto increment" is set
727 * @param string $table Table name
728 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ] )
729 * Syntax for Primary Key: [ $col1, $col2, ...] )
730 * @param int $type The type of renaming (Default is Column)
732 * @return boolean Was the renaming successful?
735 public static function rename($table, $columns, $type = self::RENAME_COLUMN) {
736 if (empty($table) || empty($columns)) {
740 if (!is_array($columns)) {
744 $table = DBA::escape($table);
746 $sql = "ALTER TABLE `" . $table . "`";
748 case self::RENAME_COLUMN:
749 if (!self::existsColumn($table, array_keys($columns))) {
752 $sql .= implode(',', array_map(
753 function ($to, $from) {
754 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
760 case self::RENAME_PRIMARY_KEY:
761 if (!self::existsColumn($table, $columns)) {
764 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
772 $stmt = DBA::p($sql);
774 if (is_bool($stmt)) {
786 * Loads the database structure definition from the config/dbstructure.php file.
787 * On first pass, defines DB_UPDATE_VERSION constant.
789 * @see config/dbstructure.php
790 * @param boolean $with_addons_structure Whether to tack on addons additional tables
794 public static function definition($with_addons_structure = true)
796 if (!self::$definition) {
797 $a = \Friendica\BaseObject::getApp();
799 $filename = $a->getBasePath() . '/config/dbstructure.php';
801 if (!is_readable($filename)) {
802 throw new Exception('Missing database structure config file config/dbstructure.php');
805 $definition = require $filename;
808 throw new Exception('Corrupted database structure config file config/dbstructure.php');
811 self::$definition = $definition;
813 $definition = self::$definition;
816 if ($with_addons_structure) {
817 Hook::callAll('dbstructure_definition', $definition);