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);
118 * Loads the database structure definition from the config/dbstructure.config.php file.
119 * On first pass, defines DB_UPDATE_VERSION constant.
121 * @see static/dbstructure.config.php
122 * @param boolean $with_addons_structure Whether to tack on addons additional tables
123 * @param string $basePath The base path of this application
127 public static function definition($basePath, $with_addons_structure = true)
129 if (!self::$definition) {
131 $filename = $basePath . '/static/dbstructure.config.php';
133 if (!is_readable($filename)) {
134 throw new Exception('Missing database structure config file static/dbstructure.config.php');
137 $definition = require $filename;
140 throw new Exception('Corrupted database structure config file static/dbstructure.config.php');
143 self::$definition = $definition;
145 $definition = self::$definition;
148 if ($with_addons_structure) {
149 Hook::callAll('dbstructure_definition', $definition);
155 private static function createTable($name, $structure, $verbose, $action)
163 foreach ($structure["fields"] AS $fieldname => $field) {
164 $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
165 if (!empty($field['primary'])) {
166 $primary_keys[] = $fieldname;
170 if (!empty($structure["indexes"])) {
171 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
172 $sql_index = self::createIndex($indexname, $fieldnames, "");
173 if (!is_null($sql_index)) {
174 $sql_rows[] = $sql_index;
179 if (isset($structure["engine"])) {
180 $engine = " ENGINE=" . $structure["engine"];
183 if (isset($structure["comment"])) {
184 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
187 $sql = implode(",\n\t", $sql_rows);
189 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
190 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
202 private static function FieldCommand($parameters, $create = true)
204 $fieldstruct = $parameters["type"];
206 if (isset($parameters["Collation"])) {
207 $fieldstruct .= " COLLATE " . $parameters["Collation"];
210 if (isset($parameters["not null"])) {
211 $fieldstruct .= " NOT NULL";
214 if (isset($parameters["default"])) {
215 if (strpos(strtolower($parameters["type"]), "int") !== false) {
216 $fieldstruct .= " DEFAULT " . $parameters["default"];
218 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
221 if (isset($parameters["extra"])) {
222 $fieldstruct .= " " . $parameters["extra"];
225 if (isset($parameters["comment"])) {
226 $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
229 /*if (($parameters["primary"] != "") && $create)
230 $fieldstruct .= " PRIMARY KEY";*/
232 return ($fieldstruct);
235 private static function createIndex($indexname, $fieldnames, $method = "ADD")
237 $method = strtoupper(trim($method));
238 if ($method != "" && $method != "ADD") {
239 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
242 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
243 $index_type = array_shift($fieldnames);
244 $method .= " " . $index_type;
248 foreach ($fieldnames AS $fieldname) {
253 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
254 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
256 $names .= "`" . DBA::escape($fieldname) . "`";
260 if ($indexname == "PRIMARY") {
261 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
265 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
270 * Updates DB structure and returns eventual errors messages
272 * @param string $basePath The base path of this application
273 * @param bool $verbose
274 * @param bool $action Whether to actually apply the update
275 * @param bool $install Is this the initial update during the installation?
276 * @param array $tables An array of the database tables
277 * @param array $definition An array of the definition tables
278 * @return string Empty string if the update is successful, error messages otherwise
281 public static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
283 if ($action && !$install) {
284 DI::config()->set('system', 'maintenance', 1);
285 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
290 Logger::log('updating structure', Logger::DEBUG);
292 // Get the current structure
295 if (is_null($tables)) {
296 $tables = q("SHOW TABLES");
299 if (DBA::isResult($tables)) {
300 foreach ($tables AS $table) {
301 $table = current($table);
303 Logger::log(sprintf('updating structure for table %s ...', $table), Logger::DEBUG);
304 $database[$table] = self::tableStructure($table);
308 // Get the definition
309 if (is_null($definition)) {
310 $definition = self::definition($basePath);
313 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
314 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
315 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
322 foreach ($definition AS $name => $structure) {
323 $is_new_table = false;
328 if (!isset($database[$name])) {
329 $r = self::createTable($name, $structure, $verbose, $action);
330 if (!DBA::isResult($r)) {
331 $errors .= self::printUpdateError($name);
333 $is_new_table = true;
335 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
336 if (isset($database[$name]["indexes"][$indexname])) {
337 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
339 $current_index_definition = "__NOT_SET__";
341 $new_index_definition = implode(",", $fieldnames);
342 if ($current_index_definition != $new_index_definition) {
343 if ($fieldnames[0] == "UNIQUE") {
346 $temp_name = "temp-" . $name;
353 * Drop the index if it isn't present in the definition
354 * or the definition differ from current status
355 * and index name doesn't start with "local_"
357 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
358 $current_index_definition = implode(",", $fieldnames);
359 if (isset($structure["indexes"][$indexname])) {
360 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
362 $new_index_definition = "__NOT_SET__";
364 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
365 $sql2 = self::dropIndex($indexname);
367 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
369 $sql3 .= ", " . $sql2;
373 // Compare the field structure field by field
374 foreach ($structure["fields"] AS $fieldname => $parameters) {
375 if (!isset($database[$name]["fields"][$fieldname])) {
376 $sql2 = self::addTableField($fieldname, $parameters);
378 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
380 $sql3 .= ", " . $sql2;
383 // Compare the field definition
384 $field_definition = $database[$name]["fields"][$fieldname];
386 // Remove the relation data that is used for the referential integrity
387 unset($parameters['relation']);
389 // We change the collation after the indexes had been changed.
390 // This is done to avoid index length problems.
391 // So here we always ensure that there is no need to change it.
392 unset($parameters['Collation']);
393 unset($field_definition['Collation']);
395 // Only update the comment when it is defined
396 if (!isset($parameters['comment'])) {
397 $parameters['comment'] = "";
400 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
401 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
402 if ($current_field_definition != $new_field_definition) {
403 $sql2 = self::modifyTableField($fieldname, $parameters);
405 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
407 $sql3 .= ", " . $sql2;
415 * Create the index if the index don't exists in database
416 * or the definition differ from the current status.
417 * Don't create keys if table is new
419 if (!$is_new_table) {
420 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
421 if (isset($database[$name]["indexes"][$indexname])) {
422 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
424 $current_index_definition = "__NOT_SET__";
426 $new_index_definition = implode(",", $fieldnames);
427 if ($current_index_definition != $new_index_definition) {
428 $sql2 = self::createIndex($indexname, $fieldnames);
430 // Fetch the "group by" fields for unique indexes
431 $group_by = self::groupBy($fieldnames);
434 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
436 $sql3 .= ", " . $sql2;
442 if (isset($database[$name]["table_status"]["Comment"])) {
443 $structurecomment = $structure["comment"] ?? '';
444 if ($database[$name]["table_status"]["Comment"] != $structurecomment) {
445 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
448 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
450 $sql3 .= ", " . $sql2;
455 if (isset($database[$name]["table_status"]["Engine"]) && isset($structure['engine'])) {
456 if ($database[$name]["table_status"]["Engine"] != $structure['engine']) {
457 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
460 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
462 $sql3 .= ", " . $sql2;
467 if (isset($database[$name]["table_status"]["Collation"])) {
468 if ($database[$name]["table_status"]["Collation"] != 'utf8mb4_general_ci') {
469 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
472 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
474 $sql3 .= ", " . $sql2;
483 // Now have a look at the field collations
484 // Compare the field structure field by field
485 foreach ($structure["fields"] AS $fieldname => $parameters) {
486 // Compare the field definition
487 $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
489 // Define the default collation if not given
490 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
491 $parameters['Collation'] = 'utf8mb4_general_ci';
493 $parameters['Collation'] = null;
496 if ($field_definition['Collation'] != $parameters['Collation']) {
497 $sql2 = self::modifyTableField($fieldname, $parameters);
498 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
499 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
501 $sql3 .= ", " . $sql2;
508 if (substr($sql3, -2, 2) != "; ") {
513 if ($is_unique && $ignore == '') {
514 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
515 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
517 $field_list = rtrim($field_list, ',');
521 // Ensure index conversion to unique removes duplicates
522 if ($is_unique && ($temp_name != $name)) {
524 echo "SET session old_alter_table=1;\n";
526 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
527 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
533 if ($is_unique && ($temp_name != $name)) {
535 echo "SET session old_alter_table=0;\n";
537 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
538 echo "DROP TABLE `" . $name . "`;\n";
539 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
546 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
549 // Ensure index conversion to unique removes duplicates
550 if ($is_unique && ($temp_name != $name)) {
552 DBA::e("SET session old_alter_table=1;");
554 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
555 if (!DBA::isResult($r)) {
556 $errors .= self::printUpdateError($sql3);
560 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
561 if (!DBA::isResult($r)) {
562 $errors .= self::printUpdateError($sql3);
569 if (!DBA::isResult($r)) {
570 $errors .= self::printUpdateError($sql3);
572 if ($is_unique && ($temp_name != $name)) {
574 DBA::e("SET session old_alter_table=0;");
576 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
577 if (!DBA::isResult($r)) {
578 $errors .= self::printUpdateError($sql3);
581 $r = DBA::e("DROP TABLE `" . $name . "`;");
582 if (!DBA::isResult($r)) {
583 $errors .= self::printUpdateError($sql3);
586 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
587 if (!DBA::isResult($r)) {
588 $errors .= self::printUpdateError($sql3);
597 if ($action && !$install) {
598 DI::config()->set('system', 'maintenance', 0);
599 DI::config()->set('system', 'maintenance_reason', '');
602 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
604 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
611 private static function tableStructure($table)
613 $structures = q("DESCRIBE `%s`", $table);
615 $full_columns = q("SHOW FULL COLUMNS FROM `%s`", $table);
617 $indexes = q("SHOW INDEX FROM `%s`", $table);
619 $table_status = q("SHOW TABLE STATUS WHERE `name` = '%s'", $table);
621 if (DBA::isResult($table_status)) {
622 $table_status = $table_status[0];
630 if (DBA::isResult($indexes)) {
631 foreach ($indexes AS $index) {
632 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
633 $indexdata[$index["Key_name"]] = ["UNIQUE"];
636 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
637 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
640 $column = $index["Column_name"];
642 if ($index["Sub_part"] != "") {
643 $column .= "(" . $index["Sub_part"] . ")";
646 $indexdata[$index["Key_name"]][] = $column;
649 if (DBA::isResult($structures)) {
650 foreach ($structures AS $field) {
651 // Replace the default size values so that we don't have to define them
652 $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)'];
653 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
654 $field["Type"] = str_replace($search, $replace, $field["Type"]);
656 $fielddata[$field["Field"]]["type"] = $field["Type"];
657 if ($field["Null"] == "NO") {
658 $fielddata[$field["Field"]]["not null"] = true;
661 if (isset($field["Default"])) {
662 $fielddata[$field["Field"]]["default"] = $field["Default"];
665 if ($field["Extra"] != "") {
666 $fielddata[$field["Field"]]["extra"] = $field["Extra"];
669 if ($field["Key"] == "PRI") {
670 $fielddata[$field["Field"]]["primary"] = true;
674 if (DBA::isResult($full_columns)) {
675 foreach ($full_columns AS $column) {
676 $fielddata[$column["Field"]]["Collation"] = $column["Collation"];
677 $fielddata[$column["Field"]]["comment"] = $column["Comment"];
681 return ["fields" => $fielddata, "indexes" => $indexdata, "table_status" => $table_status];
684 private static function dropIndex($indexname)
686 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
690 private static function addTableField($fieldname, $parameters)
692 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
696 private static function modifyTableField($fieldname, $parameters)
698 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
703 * Constructs a GROUP BY clause from a UNIQUE index definition.
705 * @param array $fieldnames
708 private static function groupBy(array $fieldnames)
710 if ($fieldnames[0] != "UNIQUE") {
714 array_shift($fieldnames);
717 foreach ($fieldnames AS $fieldname) {
722 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
723 $names .= "`" . DBA::escape($matches[1]) . "`";
725 $names .= "`" . DBA::escape($fieldname) . "`";
729 $sql = sprintf(" GROUP BY %s", $names);
734 * Renames columns or the primary key of a table
736 * @todo You cannot rename a primary key if "auto increment" is set
738 * @param string $table Table name
739 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
740 * Syntax for Primary Key: [ $col1, $col2, ...]
741 * @param int $type The type of renaming (Default is Column)
743 * @return boolean Was the renaming successful?
746 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
748 if (empty($table) || empty($columns)) {
752 if (!is_array($columns)) {
756 $table = DBA::escape($table);
758 $sql = "ALTER TABLE `" . $table . "`";
760 case self::RENAME_COLUMN:
761 if (!self::existsColumn($table, array_keys($columns))) {
764 $sql .= implode(',', array_map(
765 function ($to, $from) {
766 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
772 case self::RENAME_PRIMARY_KEY:
773 if (!self::existsColumn($table, $columns)) {
776 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
784 $stmt = DBA::p($sql);
786 if (is_bool($stmt)) {
798 * Check if the columns of the table exists
800 * @param string $table Table name
801 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
803 * @return boolean Does the table exist?
806 public static function existsColumn($table, $columns = [])
812 if (is_null($columns) || empty($columns)) {
813 return self::existsTable($table);
816 $table = DBA::escape($table);
818 foreach ($columns AS $column) {
819 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
821 $stmt = DBA::p($sql);
823 if (is_bool($stmt)) {
826 $retval = (DBA::numRows($stmt) > 0);
840 * Check if a table exists
842 * @param string|array $table Table name
844 * @return boolean Does the table exist?
847 public static function existsTable($table)
853 if (is_array($table)) {
854 $condition = ['table_schema' => key($table), 'table_name' => current($table)];
856 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
859 $result = DBA::exists(['information_schema' => 'tables'], $condition);
865 * Returns the columns of a table
867 * @param string $table Table name
869 * @return array An array of the table columns
872 public static function getColumns($table)
874 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
875 return DBA::toArray($stmtColumns);