3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Database;
25 use Friendica\Core\Hook;
26 use Friendica\Core\Logger;
28 use Friendica\Util\DateTimeFormat;
30 require_once __DIR__ . '/../../include/dba.php';
33 * This class contains functions that doesn't need to know if pdo, mysqli or whatever is used.
37 const UPDATE_NOT_CHECKED = 0; // Database check wasn't executed before
38 const UPDATE_SUCCESSFUL = 1; // Database check was successful
39 const UPDATE_FAILED = 2; // Database check failed
41 const RENAME_COLUMN = 0;
42 const RENAME_PRIMARY_KEY = 1;
45 * Database structure definition loaded from config/dbstructure.config.php
49 private static $definition = [];
52 * Converts all tables from MyISAM/InnoDB Antelope to InnoDB Barracuda
54 public static function convertToInnoDB()
56 $tables = DBA::selectToArray(
57 ['information_schema' => 'tables'],
59 ['engine' => 'MyISAM', 'table_schema' => DBA::databaseName()]
62 $tables = array_merge($tables, DBA::selectToArray(
63 ['information_schema' => 'tables'],
65 ['engine' => 'InnoDB', 'ROW_FORMAT' => ['COMPACT', 'REDUNDANT'], 'table_schema' => DBA::databaseName()]
68 if (!DBA::isResult($tables)) {
69 echo DI::l10n()->t('There are no tables on MyISAM or InnoDB with the Antelope file format.') . "\n";
73 foreach ($tables AS $table) {
74 $sql = "ALTER TABLE " . DBA::quoteIdentifier($table['table_name']) . " ENGINE=InnoDB ROW_FORMAT=DYNAMIC;";
77 $result = DBA::e($sql);
78 if (!DBA::isResult($result)) {
79 self::printUpdateError($sql);
85 * Print out database error messages
87 * @param string $message Message to be added to the error message
89 * @return string Error message
91 private static function printUpdateError($message)
93 echo DI::l10n()->t("\nError %d occurred during database update:\n%s\n",
94 DBA::errorNo(), DBA::errorMessage());
96 return DI::l10n()->t('Errors encountered performing database changes: ') . $message . EOL;
99 public static function printStructure($basePath)
101 $database = self::definition($basePath, false);
103 echo "-- ------------------------------------------\n";
104 echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n";
105 echo "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
106 echo "-- ------------------------------------------\n\n\n";
107 foreach ($database AS $name => $structure) {
109 echo "-- TABLE $name\n";
111 self::createTable($name, $structure, true, false);
116 View::printStructure($basePath);
120 * Loads the database structure definition from the static/dbstructure.config.php file.
121 * On first pass, defines DB_UPDATE_VERSION constant.
123 * @see static/dbstructure.config.php
124 * @param boolean $with_addons_structure Whether to tack on addons additional tables
125 * @param string $basePath The base path of this application
129 public static function definition($basePath, $with_addons_structure = true)
131 if (!self::$definition) {
133 $filename = $basePath . '/static/dbstructure.config.php';
135 if (!is_readable($filename)) {
136 throw new Exception('Missing database structure config file static/dbstructure.config.php');
139 $definition = require $filename;
142 throw new Exception('Corrupted database structure config file static/dbstructure.config.php');
145 self::$definition = $definition;
147 $definition = self::$definition;
150 if ($with_addons_structure) {
151 Hook::callAll('dbstructure_definition', $definition);
157 private static function createTable($name, $structure, $verbose, $action)
165 foreach ($structure["fields"] AS $fieldname => $field) {
166 $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
167 if (!empty($field['primary'])) {
168 $primary_keys[] = $fieldname;
172 if (!empty($structure["indexes"])) {
173 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
174 $sql_index = self::createIndex($indexname, $fieldnames, "");
175 if (!is_null($sql_index)) {
176 $sql_rows[] = $sql_index;
181 if (isset($structure["engine"])) {
182 $engine = " ENGINE=" . $structure["engine"];
185 if (isset($structure["comment"])) {
186 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
189 $sql = implode(",\n\t", $sql_rows);
191 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
192 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
204 private static function FieldCommand($parameters, $create = true)
206 $fieldstruct = $parameters["type"];
208 if (isset($parameters["Collation"])) {
209 $fieldstruct .= " COLLATE " . $parameters["Collation"];
212 if (isset($parameters["not null"])) {
213 $fieldstruct .= " NOT NULL";
216 if (isset($parameters["default"])) {
217 if (strpos(strtolower($parameters["type"]), "int") !== false) {
218 $fieldstruct .= " DEFAULT " . $parameters["default"];
220 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
223 if (isset($parameters["extra"])) {
224 $fieldstruct .= " " . $parameters["extra"];
227 if (isset($parameters["comment"])) {
228 $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
231 /*if (($parameters["primary"] != "") && $create)
232 $fieldstruct .= " PRIMARY KEY";*/
234 return ($fieldstruct);
237 private static function createIndex($indexname, $fieldnames, $method = "ADD")
239 $method = strtoupper(trim($method));
240 if ($method != "" && $method != "ADD") {
241 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
244 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
245 $index_type = array_shift($fieldnames);
246 $method .= " " . $index_type;
250 foreach ($fieldnames AS $fieldname) {
255 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
256 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
258 $names .= "`" . DBA::escape($fieldname) . "`";
262 if ($indexname == "PRIMARY") {
263 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
267 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
272 * Updates DB structure and returns eventual errors messages
274 * @param string $basePath The base path of this application
275 * @param bool $verbose
276 * @param bool $action Whether to actually apply the update
277 * @param bool $install Is this the initial update during the installation?
278 * @param array $tables An array of the database tables
279 * @param array $definition An array of the definition tables
280 * @return string Empty string if the update is successful, error messages otherwise
283 public static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
285 if ($action && !$install) {
286 DI::config()->set('system', 'maintenance', 1);
287 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
292 Logger::log('updating structure', Logger::DEBUG);
294 // Get the current structure
297 if (is_null($tables)) {
298 $tables = q("SHOW TABLES");
301 if (DBA::isResult($tables)) {
302 foreach ($tables AS $table) {
303 $table = current($table);
305 Logger::log(sprintf('updating structure for table %s ...', $table), Logger::DEBUG);
306 $database[$table] = self::tableStructure($table);
310 // Get the definition
311 if (is_null($definition)) {
312 $definition = self::definition($basePath);
315 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
316 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
317 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
324 foreach ($definition AS $name => $structure) {
325 $is_new_table = false;
330 if (!isset($database[$name])) {
331 $r = self::createTable($name, $structure, $verbose, $action);
332 if (!DBA::isResult($r)) {
333 $errors .= self::printUpdateError($name);
335 $is_new_table = true;
337 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
338 if (isset($database[$name]["indexes"][$indexname])) {
339 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
341 $current_index_definition = "__NOT_SET__";
343 $new_index_definition = implode(",", $fieldnames);
344 if ($current_index_definition != $new_index_definition) {
345 if ($fieldnames[0] == "UNIQUE") {
348 $temp_name = "temp-" . $name;
355 * Drop the index if it isn't present in the definition
356 * or the definition differ from current status
357 * and index name doesn't start with "local_"
359 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
360 $current_index_definition = implode(",", $fieldnames);
361 if (isset($structure["indexes"][$indexname])) {
362 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
364 $new_index_definition = "__NOT_SET__";
366 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
367 $sql2 = self::dropIndex($indexname);
369 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
371 $sql3 .= ", " . $sql2;
375 // Compare the field structure field by field
376 foreach ($structure["fields"] AS $fieldname => $parameters) {
377 if (!isset($database[$name]["fields"][$fieldname])) {
378 $sql2 = self::addTableField($fieldname, $parameters);
380 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
382 $sql3 .= ", " . $sql2;
385 // Compare the field definition
386 $field_definition = $database[$name]["fields"][$fieldname];
388 // Remove the relation data that is used for the referential integrity
389 unset($parameters['relation']);
391 // We change the collation after the indexes had been changed.
392 // This is done to avoid index length problems.
393 // So here we always ensure that there is no need to change it.
394 unset($parameters['Collation']);
395 unset($field_definition['Collation']);
397 // Only update the comment when it is defined
398 if (!isset($parameters['comment'])) {
399 $parameters['comment'] = "";
402 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
403 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
404 if ($current_field_definition != $new_field_definition) {
405 $sql2 = self::modifyTableField($fieldname, $parameters);
407 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
409 $sql3 .= ", " . $sql2;
417 * Create the index if the index don't exists in database
418 * or the definition differ from the current status.
419 * Don't create keys if table is new
421 if (!$is_new_table) {
422 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
423 if (isset($database[$name]["indexes"][$indexname])) {
424 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
426 $current_index_definition = "__NOT_SET__";
428 $new_index_definition = implode(",", $fieldnames);
429 if ($current_index_definition != $new_index_definition) {
430 $sql2 = self::createIndex($indexname, $fieldnames);
432 // Fetch the "group by" fields for unique indexes
433 $group_by = self::groupBy($fieldnames);
436 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
438 $sql3 .= ", " . $sql2;
444 if (isset($database[$name]["table_status"]["Comment"])) {
445 $structurecomment = $structure["comment"] ?? '';
446 if ($database[$name]["table_status"]["Comment"] != $structurecomment) {
447 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
450 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
452 $sql3 .= ", " . $sql2;
457 if (isset($database[$name]["table_status"]["Engine"]) && isset($structure['engine'])) {
458 if ($database[$name]["table_status"]["Engine"] != $structure['engine']) {
459 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
462 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
464 $sql3 .= ", " . $sql2;
469 if (isset($database[$name]["table_status"]["Collation"])) {
470 if ($database[$name]["table_status"]["Collation"] != 'utf8mb4_general_ci') {
471 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
474 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
476 $sql3 .= ", " . $sql2;
485 // Now have a look at the field collations
486 // Compare the field structure field by field
487 foreach ($structure["fields"] AS $fieldname => $parameters) {
488 // Compare the field definition
489 $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
491 // Define the default collation if not given
492 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
493 $parameters['Collation'] = 'utf8mb4_general_ci';
495 $parameters['Collation'] = null;
498 if ($field_definition['Collation'] != $parameters['Collation']) {
499 $sql2 = self::modifyTableField($fieldname, $parameters);
500 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
501 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
503 $sql3 .= ", " . $sql2;
510 if (substr($sql3, -2, 2) != "; ") {
515 if ($is_unique && $ignore == '') {
516 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
517 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
519 $field_list = rtrim($field_list, ',');
523 // Ensure index conversion to unique removes duplicates
524 if ($is_unique && ($temp_name != $name)) {
526 echo "SET session old_alter_table=1;\n";
528 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
529 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
535 if ($is_unique && ($temp_name != $name)) {
537 echo "SET session old_alter_table=0;\n";
539 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
540 echo "DROP TABLE `" . $name . "`;\n";
541 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
548 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
551 // Ensure index conversion to unique removes duplicates
552 if ($is_unique && ($temp_name != $name)) {
554 DBA::e("SET session old_alter_table=1;");
556 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
557 if (!DBA::isResult($r)) {
558 $errors .= self::printUpdateError($sql3);
562 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
563 if (!DBA::isResult($r)) {
564 $errors .= self::printUpdateError($sql3);
571 if (!DBA::isResult($r)) {
572 $errors .= self::printUpdateError($sql3);
574 if ($is_unique && ($temp_name != $name)) {
576 DBA::e("SET session old_alter_table=0;");
578 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
579 if (!DBA::isResult($r)) {
580 $errors .= self::printUpdateError($sql3);
583 $r = DBA::e("DROP TABLE `" . $name . "`;");
584 if (!DBA::isResult($r)) {
585 $errors .= self::printUpdateError($sql3);
588 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
589 if (!DBA::isResult($r)) {
590 $errors .= self::printUpdateError($sql3);
599 View::create($verbose, $action);
601 if ($action && !$install) {
602 DI::config()->set('system', 'maintenance', 0);
603 DI::config()->set('system', 'maintenance_reason', '');
606 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
608 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
615 private static function tableStructure($table)
617 $structures = q("DESCRIBE `%s`", $table);
619 $full_columns = q("SHOW FULL COLUMNS FROM `%s`", $table);
621 $indexes = q("SHOW INDEX FROM `%s`", $table);
623 $table_status = q("SHOW TABLE STATUS WHERE `name` = '%s'", $table);
625 if (DBA::isResult($table_status)) {
626 $table_status = $table_status[0];
634 if (DBA::isResult($indexes)) {
635 foreach ($indexes AS $index) {
636 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
637 $indexdata[$index["Key_name"]] = ["UNIQUE"];
640 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
641 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
644 $column = $index["Column_name"];
646 if ($index["Sub_part"] != "") {
647 $column .= "(" . $index["Sub_part"] . ")";
650 $indexdata[$index["Key_name"]][] = $column;
653 if (DBA::isResult($structures)) {
654 foreach ($structures AS $field) {
655 // Replace the default size values so that we don't have to define them
656 $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)'];
657 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
658 $field["Type"] = str_replace($search, $replace, $field["Type"]);
660 $fielddata[$field["Field"]]["type"] = $field["Type"];
661 if ($field["Null"] == "NO") {
662 $fielddata[$field["Field"]]["not null"] = true;
665 if (isset($field["Default"])) {
666 $fielddata[$field["Field"]]["default"] = $field["Default"];
669 if ($field["Extra"] != "") {
670 $fielddata[$field["Field"]]["extra"] = $field["Extra"];
673 if ($field["Key"] == "PRI") {
674 $fielddata[$field["Field"]]["primary"] = true;
678 if (DBA::isResult($full_columns)) {
679 foreach ($full_columns AS $column) {
680 $fielddata[$column["Field"]]["Collation"] = $column["Collation"];
681 $fielddata[$column["Field"]]["comment"] = $column["Comment"];
685 return ["fields" => $fielddata, "indexes" => $indexdata, "table_status" => $table_status];
688 private static function dropIndex($indexname)
690 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
694 private static function addTableField($fieldname, $parameters)
696 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
700 private static function modifyTableField($fieldname, $parameters)
702 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
707 * Constructs a GROUP BY clause from a UNIQUE index definition.
709 * @param array $fieldnames
712 private static function groupBy(array $fieldnames)
714 if ($fieldnames[0] != "UNIQUE") {
718 array_shift($fieldnames);
721 foreach ($fieldnames AS $fieldname) {
726 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
727 $names .= "`" . DBA::escape($matches[1]) . "`";
729 $names .= "`" . DBA::escape($fieldname) . "`";
733 $sql = sprintf(" GROUP BY %s", $names);
738 * Renames columns or the primary key of a table
740 * @todo You cannot rename a primary key if "auto increment" is set
742 * @param string $table Table name
743 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
744 * Syntax for Primary Key: [ $col1, $col2, ...]
745 * @param int $type The type of renaming (Default is Column)
747 * @return boolean Was the renaming successful?
750 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
752 if (empty($table) || empty($columns)) {
756 if (!is_array($columns)) {
760 $table = DBA::escape($table);
762 $sql = "ALTER TABLE `" . $table . "`";
764 case self::RENAME_COLUMN:
765 if (!self::existsColumn($table, array_keys($columns))) {
768 $sql .= implode(',', array_map(
769 function ($to, $from) {
770 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
776 case self::RENAME_PRIMARY_KEY:
777 if (!self::existsColumn($table, $columns)) {
780 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
788 $stmt = DBA::p($sql);
790 if (is_bool($stmt)) {
802 * Check if the columns of the table exists
804 * @param string $table Table name
805 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
807 * @return boolean Does the table exist?
810 public static function existsColumn($table, $columns = [])
816 if (is_null($columns) || empty($columns)) {
817 return self::existsTable($table);
820 $table = DBA::escape($table);
822 foreach ($columns AS $column) {
823 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
825 $stmt = DBA::p($sql);
827 if (is_bool($stmt)) {
830 $retval = (DBA::numRows($stmt) > 0);
844 * Check if a table exists
846 * @param string|array $table Table name
848 * @return boolean Does the table exist?
851 public static function existsTable($table)
857 if (is_array($table)) {
858 $condition = ['table_schema' => key($table), 'table_name' => current($table)];
860 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
863 $result = DBA::exists(['information_schema' => 'tables'], $condition);
869 * Returns the columns of a table
871 * @param string $table Table name
873 * @return array An array of the table columns
876 public static function getColumns($table)
878 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
879 return DBA::toArray($stmtColumns);