3 * @file src/Database/DBStructure.php
6 namespace Friendica\Database;
9 use Friendica\Core\Hook;
10 use Friendica\Core\Logger;
12 use Friendica\Util\DateTimeFormat;
14 require_once __DIR__ . '/../../include/dba.php';
17 * This class contains functions that doesn't need to know if pdo, mysqli or whatever is used.
21 const UPDATE_NOT_CHECKED = 0; // Database check wasn't executed before
22 const UPDATE_SUCCESSFUL = 1; // Database check was successful
23 const UPDATE_FAILED = 2; // Database check failed
25 const RENAME_COLUMN = 0;
26 const RENAME_PRIMARY_KEY = 1;
29 * Database structure definition loaded from config/dbstructure.config.php
33 private static $definition = [];
36 * Converts all tables from MyISAM to InnoDB
38 public static function convertToInnoDB()
40 $tables = DBA::selectToArray(
41 ['information_schema' => 'tables'],
43 ['engine' => 'MyISAM', 'table_schema' => DBA::databaseName()]
46 if (!DBA::isResult($tables)) {
47 echo DI::l10n()->t('There are no tables on MyISAM.') . "\n";
51 foreach ($tables AS $table) {
52 $sql = "ALTER TABLE " . DBA::quoteIdentifier($table['table_name']) . " engine=InnoDB;";
55 $result = DBA::e($sql);
56 if (!DBA::isResult($result)) {
57 self::printUpdateError($sql);
63 * Print out database error messages
65 * @param string $message Message to be added to the error message
67 * @return string Error message
69 private static function printUpdateError($message)
71 echo DI::l10n()->t("\nError %d occurred during database update:\n%s\n",
72 DBA::errorNo(), DBA::errorMessage());
74 return DI::l10n()->t('Errors encountered performing database changes: ') . $message . EOL;
77 public static function printStructure($basePath)
79 $database = self::definition($basePath, false);
81 echo "-- ------------------------------------------\n";
82 echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n";
83 echo "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
84 echo "-- ------------------------------------------\n\n\n";
85 foreach ($database AS $name => $structure) {
87 echo "-- TABLE $name\n";
89 self::createTable($name, $structure, true, false);
96 * Loads the database structure definition from the config/dbstructure.config.php file.
97 * On first pass, defines DB_UPDATE_VERSION constant.
99 * @see static/dbstructure.config.php
100 * @param boolean $with_addons_structure Whether to tack on addons additional tables
101 * @param string $basePath The base path of this application
105 public static function definition($basePath, $with_addons_structure = true)
107 if (!self::$definition) {
109 $filename = $basePath . '/static/dbstructure.config.php';
111 if (!is_readable($filename)) {
112 throw new Exception('Missing database structure config file static/dbstructure.config.php');
115 $definition = require $filename;
118 throw new Exception('Corrupted database structure config file static/dbstructure.config.php');
121 self::$definition = $definition;
123 $definition = self::$definition;
126 if ($with_addons_structure) {
127 Hook::callAll('dbstructure_definition', $definition);
133 private static function createTable($name, $structure, $verbose, $action)
141 foreach ($structure["fields"] AS $fieldname => $field) {
142 $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
143 if (!empty($field['primary'])) {
144 $primary_keys[] = $fieldname;
148 if (!empty($structure["indexes"])) {
149 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
150 $sql_index = self::createIndex($indexname, $fieldnames, "");
151 if (!is_null($sql_index)) {
152 $sql_rows[] = $sql_index;
157 if (isset($structure["engine"])) {
158 $engine = " ENGINE=" . $structure["engine"];
161 if (isset($structure["comment"])) {
162 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
165 $sql = implode(",\n\t", $sql_rows);
167 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
168 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
180 private static function FieldCommand($parameters, $create = true)
182 $fieldstruct = $parameters["type"];
184 if (isset($parameters["Collation"])) {
185 $fieldstruct .= " COLLATE " . $parameters["Collation"];
188 if (isset($parameters["not null"])) {
189 $fieldstruct .= " NOT NULL";
192 if (isset($parameters["default"])) {
193 if (strpos(strtolower($parameters["type"]), "int") !== false) {
194 $fieldstruct .= " DEFAULT " . $parameters["default"];
196 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
199 if (isset($parameters["extra"])) {
200 $fieldstruct .= " " . $parameters["extra"];
203 if (isset($parameters["comment"])) {
204 $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
207 /*if (($parameters["primary"] != "") && $create)
208 $fieldstruct .= " PRIMARY KEY";*/
210 return ($fieldstruct);
213 private static function createIndex($indexname, $fieldnames, $method = "ADD")
215 $method = strtoupper(trim($method));
216 if ($method != "" && $method != "ADD") {
217 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
220 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
221 $index_type = array_shift($fieldnames);
222 $method .= " " . $index_type;
226 foreach ($fieldnames AS $fieldname) {
231 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
232 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
234 $names .= "`" . DBA::escape($fieldname) . "`";
238 if ($indexname == "PRIMARY") {
239 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
243 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
248 * Updates DB structure and returns eventual errors messages
250 * @param string $basePath The base path of this application
251 * @param bool $verbose
252 * @param bool $action Whether to actually apply the update
253 * @param bool $install Is this the initial update during the installation?
254 * @param array $tables An array of the database tables
255 * @param array $definition An array of the definition tables
256 * @return string Empty string if the update is successful, error messages otherwise
259 public static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
261 if ($action && !$install) {
262 DI::config()->set('system', 'maintenance', 1);
263 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
268 Logger::log('updating structure', Logger::DEBUG);
270 // Get the current structure
273 if (is_null($tables)) {
274 $tables = q("SHOW TABLES");
277 if (DBA::isResult($tables)) {
278 foreach ($tables AS $table) {
279 $table = current($table);
281 Logger::log(sprintf('updating structure for table %s ...', $table), Logger::DEBUG);
282 $database[$table] = self::tableStructure($table);
286 // Get the definition
287 if (is_null($definition)) {
288 $definition = self::definition($basePath);
291 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
292 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
293 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
300 foreach ($definition AS $name => $structure) {
301 $is_new_table = false;
306 if (!isset($database[$name])) {
307 $r = self::createTable($name, $structure, $verbose, $action);
308 if (!DBA::isResult($r)) {
309 $errors .= self::printUpdateError($name);
311 $is_new_table = true;
313 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
314 if (isset($database[$name]["indexes"][$indexname])) {
315 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
317 $current_index_definition = "__NOT_SET__";
319 $new_index_definition = implode(",", $fieldnames);
320 if ($current_index_definition != $new_index_definition) {
321 if ($fieldnames[0] == "UNIQUE") {
324 $temp_name = "temp-" . $name;
331 * Drop the index if it isn't present in the definition
332 * or the definition differ from current status
333 * and index name doesn't start with "local_"
335 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
336 $current_index_definition = implode(",", $fieldnames);
337 if (isset($structure["indexes"][$indexname])) {
338 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
340 $new_index_definition = "__NOT_SET__";
342 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
343 $sql2 = self::dropIndex($indexname);
345 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
347 $sql3 .= ", " . $sql2;
351 // Compare the field structure field by field
352 foreach ($structure["fields"] AS $fieldname => $parameters) {
353 if (!isset($database[$name]["fields"][$fieldname])) {
354 $sql2 = self::addTableField($fieldname, $parameters);
356 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
358 $sql3 .= ", " . $sql2;
361 // Compare the field definition
362 $field_definition = $database[$name]["fields"][$fieldname];
364 // Remove the relation data that is used for the referential integrity
365 unset($parameters['relation']);
367 // We change the collation after the indexes had been changed.
368 // This is done to avoid index length problems.
369 // So here we always ensure that there is no need to change it.
370 unset($parameters['Collation']);
371 unset($field_definition['Collation']);
373 // Only update the comment when it is defined
374 if (!isset($parameters['comment'])) {
375 $parameters['comment'] = "";
378 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
379 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
380 if ($current_field_definition != $new_field_definition) {
381 $sql2 = self::modifyTableField($fieldname, $parameters);
383 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
385 $sql3 .= ", " . $sql2;
393 * Create the index if the index don't exists in database
394 * or the definition differ from the current status.
395 * Don't create keys if table is new
397 if (!$is_new_table) {
398 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
399 if (isset($database[$name]["indexes"][$indexname])) {
400 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
402 $current_index_definition = "__NOT_SET__";
404 $new_index_definition = implode(",", $fieldnames);
405 if ($current_index_definition != $new_index_definition) {
406 $sql2 = self::createIndex($indexname, $fieldnames);
408 // Fetch the "group by" fields for unique indexes
409 $group_by = self::groupBy($fieldnames);
412 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
414 $sql3 .= ", " . $sql2;
420 if (isset($database[$name]["table_status"]["Comment"])) {
421 $structurecomment = $structure["comment"] ?? '';
422 if ($database[$name]["table_status"]["Comment"] != $structurecomment) {
423 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
426 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
428 $sql3 .= ", " . $sql2;
433 if (isset($database[$name]["table_status"]["Engine"]) && isset($structure['engine'])) {
434 if ($database[$name]["table_status"]["Engine"] != $structure['engine']) {
435 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
438 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
440 $sql3 .= ", " . $sql2;
445 if (isset($database[$name]["table_status"]["Collation"])) {
446 if ($database[$name]["table_status"]["Collation"] != 'utf8mb4_general_ci') {
447 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
450 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
452 $sql3 .= ", " . $sql2;
461 // Now have a look at the field collations
462 // Compare the field structure field by field
463 foreach ($structure["fields"] AS $fieldname => $parameters) {
464 // Compare the field definition
465 $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
467 // Define the default collation if not given
468 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
469 $parameters['Collation'] = 'utf8mb4_general_ci';
471 $parameters['Collation'] = null;
474 if ($field_definition['Collation'] != $parameters['Collation']) {
475 $sql2 = self::modifyTableField($fieldname, $parameters);
476 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
477 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
479 $sql3 .= ", " . $sql2;
486 if (substr($sql3, -2, 2) != "; ") {
491 if ($is_unique && $ignore == '') {
492 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
493 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
495 $field_list = rtrim($field_list, ',');
499 // Ensure index conversion to unique removes duplicates
500 if ($is_unique && ($temp_name != $name)) {
502 echo "SET session old_alter_table=1;\n";
504 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
505 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
511 if ($is_unique && ($temp_name != $name)) {
513 echo "SET session old_alter_table=0;\n";
515 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
516 echo "DROP TABLE `" . $name . "`;\n";
517 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
524 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
527 // Ensure index conversion to unique removes duplicates
528 if ($is_unique && ($temp_name != $name)) {
530 DBA::e("SET session old_alter_table=1;");
532 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
533 if (!DBA::isResult($r)) {
534 $errors .= self::printUpdateError($sql3);
538 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
539 if (!DBA::isResult($r)) {
540 $errors .= self::printUpdateError($sql3);
547 if (!DBA::isResult($r)) {
548 $errors .= self::printUpdateError($sql3);
550 if ($is_unique && ($temp_name != $name)) {
552 DBA::e("SET session old_alter_table=0;");
554 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
555 if (!DBA::isResult($r)) {
556 $errors .= self::printUpdateError($sql3);
559 $r = DBA::e("DROP TABLE `" . $name . "`;");
560 if (!DBA::isResult($r)) {
561 $errors .= self::printUpdateError($sql3);
564 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
565 if (!DBA::isResult($r)) {
566 $errors .= self::printUpdateError($sql3);
575 if ($action && !$install) {
576 DI::config()->set('system', 'maintenance', 0);
577 DI::config()->set('system', 'maintenance_reason', '');
580 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
582 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
589 private static function tableStructure($table)
591 $structures = q("DESCRIBE `%s`", $table);
593 $full_columns = q("SHOW FULL COLUMNS FROM `%s`", $table);
595 $indexes = q("SHOW INDEX FROM `%s`", $table);
597 $table_status = q("SHOW TABLE STATUS WHERE `name` = '%s'", $table);
599 if (DBA::isResult($table_status)) {
600 $table_status = $table_status[0];
608 if (DBA::isResult($indexes)) {
609 foreach ($indexes AS $index) {
610 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
611 $indexdata[$index["Key_name"]] = ["UNIQUE"];
614 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
615 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
618 $column = $index["Column_name"];
620 if ($index["Sub_part"] != "") {
621 $column .= "(" . $index["Sub_part"] . ")";
624 $indexdata[$index["Key_name"]][] = $column;
627 if (DBA::isResult($structures)) {
628 foreach ($structures AS $field) {
629 // Replace the default size values so that we don't have to define them
630 $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)'];
631 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
632 $field["Type"] = str_replace($search, $replace, $field["Type"]);
634 $fielddata[$field["Field"]]["type"] = $field["Type"];
635 if ($field["Null"] == "NO") {
636 $fielddata[$field["Field"]]["not null"] = true;
639 if (isset($field["Default"])) {
640 $fielddata[$field["Field"]]["default"] = $field["Default"];
643 if ($field["Extra"] != "") {
644 $fielddata[$field["Field"]]["extra"] = $field["Extra"];
647 if ($field["Key"] == "PRI") {
648 $fielddata[$field["Field"]]["primary"] = true;
652 if (DBA::isResult($full_columns)) {
653 foreach ($full_columns AS $column) {
654 $fielddata[$column["Field"]]["Collation"] = $column["Collation"];
655 $fielddata[$column["Field"]]["comment"] = $column["Comment"];
659 return ["fields" => $fielddata, "indexes" => $indexdata, "table_status" => $table_status];
662 private static function dropIndex($indexname)
664 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
668 private static function addTableField($fieldname, $parameters)
670 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
674 private static function modifyTableField($fieldname, $parameters)
676 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
681 * Constructs a GROUP BY clause from a UNIQUE index definition.
683 * @param array $fieldnames
686 private static function groupBy(array $fieldnames)
688 if ($fieldnames[0] != "UNIQUE") {
692 array_shift($fieldnames);
695 foreach ($fieldnames AS $fieldname) {
700 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
701 $names .= "`" . DBA::escape($matches[1]) . "`";
703 $names .= "`" . DBA::escape($fieldname) . "`";
707 $sql = sprintf(" GROUP BY %s", $names);
712 * Renames columns or the primary key of a table
714 * @todo You cannot rename a primary key if "auto increment" is set
716 * @param string $table Table name
717 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
718 * Syntax for Primary Key: [ $col1, $col2, ...]
719 * @param int $type The type of renaming (Default is Column)
721 * @return boolean Was the renaming successful?
724 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
726 if (empty($table) || empty($columns)) {
730 if (!is_array($columns)) {
734 $table = DBA::escape($table);
736 $sql = "ALTER TABLE `" . $table . "`";
738 case self::RENAME_COLUMN:
739 if (!self::existsColumn($table, array_keys($columns))) {
742 $sql .= implode(',', array_map(
743 function ($to, $from) {
744 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
750 case self::RENAME_PRIMARY_KEY:
751 if (!self::existsColumn($table, $columns)) {
754 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
762 $stmt = DBA::p($sql);
764 if (is_bool($stmt)) {
776 * Check if the columns of the table exists
778 * @param string $table Table name
779 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
781 * @return boolean Does the table exist?
784 public static function existsColumn($table, $columns = [])
790 if (is_null($columns) || empty($columns)) {
791 return self::existsTable($table);
794 $table = DBA::escape($table);
796 foreach ($columns AS $column) {
797 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
799 $stmt = DBA::p($sql);
801 if (is_bool($stmt)) {
804 $retval = (DBA::numRows($stmt) > 0);
818 * Check if a table exists
820 * @param string|array $table Table name
822 * @return boolean Does the table exist?
825 public static function existsTable($table)
831 if (is_array($table)) {
832 $condition = ['table_schema' => key($table), 'table_name' => current($table)];
834 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
837 $result = DBA::exists(['information_schema' => 'tables'], $condition);
843 * Returns the columns of a table
845 * @param string $table Table name
847 * @return array An array of the table columns
850 public static function getColumns($table)
852 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
853 return DBA::toArray($stmtColumns);