3 * @copyright Copyright (C) 2010-2021, the Friendica project
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;
27 use Friendica\Core\Renderer;
29 use Friendica\Model\Item;
30 use Friendica\Model\User;
31 use Friendica\Util\DateTimeFormat;
34 * This class contains functions that doesn't need to know if pdo, mysqli or whatever is used.
38 const UPDATE_NOT_CHECKED = 0; // Database check wasn't executed before
39 const UPDATE_SUCCESSFUL = 1; // Database check was successful
40 const UPDATE_FAILED = 2; // Database check failed
42 const RENAME_COLUMN = 0;
43 const RENAME_PRIMARY_KEY = 1;
46 * Database structure definition loaded from config/dbstructure.config.php
50 private static $definition = [];
53 * Set a database version to trigger update functions
55 * @param string $version
58 public static function setDatabaseVersion(string $version)
60 if (!is_numeric($version)) {
61 throw new \Asika\SimpleConsole\CommandArgsException('The version number must be numeric');
64 DI::config()->set('system', 'build', $version);
65 echo DI::l10n()->t('The database version had been set to %s.', $version);
71 * @param boolean $execute
74 public static function dropTables(bool $execute)
76 $postupdate = DI::config()->get("system", "post_update_version", PostUpdate::VERSION);
77 if ($postupdate < PostUpdate::VERSION) {
78 echo DI::l10n()->t('The post update is at version %d, it has to be at %d to safely drop the tables.', $postupdate, PostUpdate::VERSION);
82 $old_tables = ['fserver', 'gcign', 'gcontact', 'gcontact-relation', 'gfollower' ,'glink', 'item-delivery-data',
83 'item-activity', 'item-content', 'item_id', 'participation', 'poll', 'poll_result', 'queue', 'retriever_rule',
84 'deliverq', 'dsprphotoq', 'ffinder', 'sign', 'spam', 'term', 'user-item', 'thread', 'item'];
86 $tables = DBA::selectToArray(['INFORMATION_SCHEMA' => 'TABLES'], ['TABLE_NAME'],
87 ['TABLE_SCHEMA' => DBA::databaseName(), 'TABLE_TYPE' => 'BASE TABLE']);
90 echo DI::l10n()->t('No unused tables found.');
95 echo DI::l10n()->t('These tables are not used for friendica and will be deleted when you execute "dbstructure drop -e":') . "\n\n";
98 foreach ($tables as $table) {
99 if (in_array($table['TABLE_NAME'], $old_tables)) {
101 $sql = 'DROP TABLE ' . DBA::quoteIdentifier($table['TABLE_NAME']) . ';';
104 $result = DBA::e($sql);
105 if (!DBA::isResult($result)) {
106 self::printUpdateError($sql);
109 echo $table['TABLE_NAME'] . "\n";
116 * Converts all tables from MyISAM/InnoDB Antelope to InnoDB Barracuda
118 public static function convertToInnoDB()
120 $tables = DBA::selectToArray(
121 ['information_schema' => 'tables'],
123 ['engine' => 'MyISAM', 'table_schema' => DBA::databaseName()]
126 $tables = array_merge($tables, DBA::selectToArray(
127 ['information_schema' => 'tables'],
129 ['engine' => 'InnoDB', 'ROW_FORMAT' => ['COMPACT', 'REDUNDANT'], 'table_schema' => DBA::databaseName()]
132 if (!DBA::isResult($tables)) {
133 echo DI::l10n()->t('There are no tables on MyISAM or InnoDB with the Antelope file format.') . "\n";
137 foreach ($tables AS $table) {
138 $sql = "ALTER TABLE " . DBA::quoteIdentifier($table['table_name']) . " ENGINE=InnoDB ROW_FORMAT=DYNAMIC;";
141 $result = DBA::e($sql);
142 if (!DBA::isResult($result)) {
143 self::printUpdateError($sql);
149 * Print out database error messages
151 * @param string $message Message to be added to the error message
153 * @return string Error message
155 private static function printUpdateError($message)
157 echo DI::l10n()->t("\nError %d occurred during database update:\n%s\n",
158 DBA::errorNo(), DBA::errorMessage());
160 return DI::l10n()->t('Errors encountered performing database changes: ') . $message . EOL;
163 public static function writeStructure()
166 foreach (self::definition(null) as $name => $definition) {
169 'fields' => 'Fields',
176 $lengths = ['name' => 4, 'fields' => 6];
177 foreach ($definition['indexes'] as $key => $value) {
178 $fieldlist = implode(', ', $value);
179 $indexes[] = ['name' => $key, 'fields' => $fieldlist];
180 $lengths['name'] = max($lengths['name'], strlen($key));
181 $lengths['fields'] = max($lengths['fields'], strlen($fieldlist));
184 array_walk_recursive($indexes, function(&$value, $key) use ($lengths)
186 $value = str_pad($value, $lengths[$key], $value === '-' ? '-' : ' ');
192 'comment' => 'Description',
196 'default' => 'Default',
217 foreach ($definition['fields'] as $key => $value) {
219 $field['name'] = $key;
220 $field['comment'] = $value['comment'] ?? '';
221 $field['type'] = $value['type'];
222 $field['null'] = ($value['not null'] ?? false) ? 'NO' : 'YES';
223 $field['primary'] = ($value['primary'] ?? false) ? 'PRI' : '';
224 $field['default'] = $value['default'] ?? 'NULL';
225 $field['extra'] = $value['extra'] ?? '';
227 foreach ($field as $fieldname => $fieldvalue) {
228 $lengths[$fieldname] = max($lengths[$fieldname] ?? 0, strlen($fieldvalue));
232 if (!empty($value['foreign'])) {
235 'targettable' => array_keys($value['foreign'])[0],
236 'targetfield' => array_values($value['foreign'])[0]
241 array_walk_recursive($fields, function(&$value, $key) use ($lengths)
243 $value = str_pad($value, $lengths[$key], $value === '-' ? '-' : ' ');
246 $tables[] = ['name' => $name, 'comment' => $definition['comment']];
247 $content = Renderer::replaceMacros(Renderer::getMarkupTemplate('structure.tpl'), [
249 '$comment' => $definition['comment'],
250 '$fields' => $fields,
251 '$indexes' => $indexes,
252 '$foreign' => $foreign,
254 $filename = DI::basePath() . '/doc/database/db_' . $name . '.md';
255 file_put_contents($filename, $content);
258 $content = Renderer::replaceMacros(Renderer::getMarkupTemplate('tables.tpl'), [
259 '$tables' => $tables,
261 $filename = DI::basePath() . '/doc/database.md';
262 file_put_contents($filename, $content);
265 public static function printStructure($basePath)
267 $database = self::definition($basePath, false);
269 echo "-- ------------------------------------------\n";
270 echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n";
271 echo "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
272 echo "-- ------------------------------------------\n\n\n";
273 foreach ($database AS $name => $structure) {
275 echo "-- TABLE $name\n";
277 self::createTable($name, $structure, true, false);
282 View::printStructure($basePath);
286 * Loads the database structure definition from the static/dbstructure.config.php file.
287 * On first pass, defines DB_UPDATE_VERSION constant.
289 * @see static/dbstructure.config.php
290 * @param boolean $with_addons_structure Whether to tack on addons additional tables
291 * @param string $basePath The base path of this application
295 public static function definition($basePath, $with_addons_structure = true)
297 if (!self::$definition) {
298 if (empty($basePath)) {
299 $basePath = DI::app()->getBasePath();
302 $filename = $basePath . '/static/dbstructure.config.php';
304 if (!is_readable($filename)) {
305 throw new Exception('Missing database structure config file static/dbstructure.config.php');
308 $definition = require $filename;
311 throw new Exception('Corrupted database structure config file static/dbstructure.config.php');
314 self::$definition = $definition;
316 $definition = self::$definition;
319 if ($with_addons_structure) {
320 Hook::callAll('dbstructure_definition', $definition);
327 * Get field data for the given table
329 * @param string $table
330 * @param array $data data fields
331 * @return array fields for the given
333 public static function getFieldsForTable(string $table, array $data = [])
335 $definition = DBStructure::definition('', false);
336 if (empty($definition[$table])) {
340 $fieldnames = array_keys($definition[$table]['fields']);
344 // Assign all field that are present in the table
345 foreach ($fieldnames as $field) {
346 if (isset($data[$field])) {
347 // Limit the length of varchar, varbinary, char and binrary fields
348 if (is_string($data[$field]) && preg_match("/char\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
349 $data[$field] = mb_substr($data[$field], 0, $result[1]);
350 } elseif (is_string($data[$field]) && preg_match("/binary\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
351 $data[$field] = substr($data[$field], 0, $result[1]);
353 $fields[$field] = $data[$field];
360 private static function createTable($name, $structure, $verbose, $action)
370 foreach ($structure["fields"] AS $fieldname => $field) {
371 $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
372 if (!empty($field['primary'])) {
373 $primary_keys[] = $fieldname;
375 if (!empty($field['foreign'])) {
376 $foreign_keys[$fieldname] = $field;
380 if (!empty($structure["indexes"])) {
381 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
382 $sql_index = self::createIndex($indexname, $fieldnames, "");
383 if (!is_null($sql_index)) {
384 $sql_rows[] = $sql_index;
389 foreach ($foreign_keys AS $fieldname => $parameters) {
390 $sql_rows[] = self::foreignCommand($name, $fieldname, $parameters);
393 if (isset($structure["engine"])) {
394 $engine = " ENGINE=" . $structure["engine"];
397 if (isset($structure["comment"])) {
398 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
401 $sql = implode(",\n\t", $sql_rows);
403 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
404 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
416 private static function FieldCommand($parameters, $create = true)
418 $fieldstruct = $parameters["type"];
420 if (isset($parameters["Collation"])) {
421 $fieldstruct .= " COLLATE " . $parameters["Collation"];
424 if (isset($parameters["not null"])) {
425 $fieldstruct .= " NOT NULL";
428 if (isset($parameters["default"])) {
429 if (strpos(strtolower($parameters["type"]), "int") !== false) {
430 $fieldstruct .= " DEFAULT " . $parameters["default"];
432 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
435 if (isset($parameters["extra"])) {
436 $fieldstruct .= " " . $parameters["extra"];
439 if (isset($parameters["comment"])) {
440 $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
443 /*if (($parameters["primary"] != "") && $create)
444 $fieldstruct .= " PRIMARY KEY";*/
446 return ($fieldstruct);
449 private static function createIndex($indexname, $fieldnames, $method = "ADD")
451 $method = strtoupper(trim($method));
452 if ($method != "" && $method != "ADD") {
453 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
456 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
457 $index_type = array_shift($fieldnames);
458 $method .= " " . $index_type;
462 foreach ($fieldnames AS $fieldname) {
467 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
468 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
470 $names .= "`" . DBA::escape($fieldname) . "`";
474 if ($indexname == "PRIMARY") {
475 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
479 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
484 * Perform a database structure dryrun (means: just simulating)
488 public static function dryRun()
490 self::update(DI::app()->getBasePath(), true, false);
494 * Updates DB structure and returns eventual errors messages
496 * @param bool $enable_maintenance_mode Set the maintenance mode
497 * @param bool $verbose Display the SQL commands
499 * @return string Empty string if the update is successful, error messages otherwise
502 public static function performUpdate(bool $enable_maintenance_mode = true, bool $verbose = false)
504 if ($enable_maintenance_mode) {
505 DI::config()->set('system', 'maintenance', 1);
508 $status = self::update(DI::app()->getBasePath(), $verbose, true);
510 if ($enable_maintenance_mode) {
511 DI::config()->set('system', 'maintenance', 0);
512 DI::config()->set('system', 'maintenance_reason', '');
519 * Updates DB structure from the installation and returns eventual errors messages
521 * @param string $basePath The base path of this application
523 * @return string Empty string if the update is successful, error messages otherwise
526 public static function install(string $basePath)
528 return self::update($basePath, false, true, true);
532 * Updates DB structure and returns eventual errors messages
534 * @param string $basePath The base path of this application
535 * @param bool $verbose
536 * @param bool $action Whether to actually apply the update
537 * @param bool $install Is this the initial update during the installation?
538 * @param array $tables An array of the database tables
539 * @param array $definition An array of the definition tables
540 * @return string Empty string if the update is successful, error messages otherwise
543 private static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
545 $in_maintenance_mode = DI::config()->get('system', 'maintenance');
547 if ($action && !$install && self::isUpdating()) {
548 return DI::l10n()->t('Another database update is currently running.');
551 if ($in_maintenance_mode) {
552 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
555 // ensure that all initial values exist. This test has to be done prior and after the structure check.
556 // Prior is needed if the specific tables already exists - after is needed when they had been created.
557 self::checkInitialValues();
561 Logger::info('updating structure');
563 // Get the current structure
566 if (is_null($tables)) {
567 $tables = DBA::toArray(DBA::p("SHOW TABLES"));
570 if (DBA::isResult($tables)) {
571 foreach ($tables AS $table) {
572 $table = current($table);
574 Logger::info('updating structure', ['table' => $table]);
575 $database[$table] = self::tableStructure($table);
579 // Get the definition
580 if (is_null($definition)) {
581 $definition = self::definition($basePath);
584 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
585 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
586 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
593 foreach ($definition AS $name => $structure) {
594 $is_new_table = false;
599 if (!isset($database[$name])) {
600 $r = self::createTable($name, $structure, $verbose, $action);
601 if (!DBA::isResult($r)) {
602 $errors .= self::printUpdateError($name);
604 $is_new_table = true;
606 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
607 if (isset($database[$name]["indexes"][$indexname])) {
608 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
610 $current_index_definition = "__NOT_SET__";
612 $new_index_definition = implode(",", $fieldnames);
613 if ($current_index_definition != $new_index_definition) {
614 if ($fieldnames[0] == "UNIQUE") {
617 $temp_name = "temp-" . $name;
624 * Drop the index if it isn't present in the definition
625 * or the definition differ from current status
626 * and index name doesn't start with "local_"
628 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
629 $current_index_definition = implode(",", $fieldnames);
630 if (isset($structure["indexes"][$indexname])) {
631 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
633 $new_index_definition = "__NOT_SET__";
635 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
636 $sql2 = self::dropIndex($indexname);
638 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
640 $sql3 .= ", " . $sql2;
644 // Compare the field structure field by field
645 foreach ($structure["fields"] AS $fieldname => $parameters) {
646 if (!isset($database[$name]["fields"][$fieldname])) {
647 $sql2 = self::addTableField($fieldname, $parameters);
649 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
651 $sql3 .= ", " . $sql2;
654 // Compare the field definition
655 $field_definition = $database[$name]["fields"][$fieldname];
657 // Remove the relation data that is used for the referential integrity
658 unset($parameters['relation']);
659 unset($parameters['foreign']);
661 // We change the collation after the indexes had been changed.
662 // This is done to avoid index length problems.
663 // So here we always ensure that there is no need to change it.
664 unset($parameters['Collation']);
665 unset($field_definition['Collation']);
667 // Only update the comment when it is defined
668 if (!isset($parameters['comment'])) {
669 $parameters['comment'] = "";
672 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
673 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
674 if ($current_field_definition != $new_field_definition) {
675 $sql2 = self::modifyTableField($fieldname, $parameters);
677 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
679 $sql3 .= ", " . $sql2;
687 * Create the index if the index don't exists in database
688 * or the definition differ from the current status.
689 * Don't create keys if table is new
691 if (!$is_new_table) {
692 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
693 if (isset($database[$name]["indexes"][$indexname])) {
694 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
696 $current_index_definition = "__NOT_SET__";
698 $new_index_definition = implode(",", $fieldnames);
699 if ($current_index_definition != $new_index_definition) {
700 $sql2 = self::createIndex($indexname, $fieldnames);
702 // Fetch the "group by" fields for unique indexes
703 $group_by = self::groupBy($fieldnames);
706 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
708 $sql3 .= ", " . $sql2;
714 $existing_foreign_keys = $database[$name]['foreign_keys'];
717 // Compare the field structure field by field
718 foreach ($structure["fields"] AS $fieldname => $parameters) {
719 if (empty($parameters['foreign'])) {
723 $constraint = self::getConstraintName($name, $fieldname, $parameters);
725 unset($existing_foreign_keys[$constraint]);
727 if (empty($database[$name]['foreign_keys'][$constraint])) {
728 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
731 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
733 $sql3 .= ", " . $sql2;
738 foreach ($existing_foreign_keys as $param) {
739 $sql2 = self::dropForeignKey($param['CONSTRAINT_NAME']);
742 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
744 $sql3 .= ", " . $sql2;
748 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
749 $structurecomment = $structure["comment"] ?? '';
750 if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
751 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
754 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
756 $sql3 .= ", " . $sql2;
761 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
762 if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
763 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
766 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
768 $sql3 .= ", " . $sql2;
773 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
774 if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
775 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
778 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
780 $sql3 .= ", " . $sql2;
789 // Now have a look at the field collations
790 // Compare the field structure field by field
791 foreach ($structure["fields"] AS $fieldname => $parameters) {
792 // Compare the field definition
793 $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
795 // Define the default collation if not given
796 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
797 $parameters['Collation'] = 'utf8mb4_general_ci';
799 $parameters['Collation'] = null;
802 if ($field_definition['Collation'] != $parameters['Collation']) {
803 $sql2 = self::modifyTableField($fieldname, $parameters);
804 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
805 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
807 $sql3 .= ", " . $sql2;
814 if (substr($sql3, -2, 2) != "; ") {
819 if ($is_unique && $ignore == '') {
820 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
821 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
823 $field_list = rtrim($field_list, ',');
827 // Ensure index conversion to unique removes duplicates
828 if ($is_unique && ($temp_name != $name)) {
830 echo "SET session old_alter_table=1;\n";
832 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
833 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
839 if ($is_unique && ($temp_name != $name)) {
841 echo "SET session old_alter_table=0;\n";
843 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
844 echo "DROP TABLE `" . $name . "`;\n";
845 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
851 if ($in_maintenance_mode) {
852 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
855 // Ensure index conversion to unique removes duplicates
856 if ($is_unique && ($temp_name != $name)) {
858 DBA::e("SET session old_alter_table=1;");
860 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
861 if (!DBA::isResult($r)) {
862 $errors .= self::printUpdateError($sql3);
866 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
867 if (!DBA::isResult($r)) {
868 $errors .= self::printUpdateError($sql3);
875 if (!DBA::isResult($r)) {
876 $errors .= self::printUpdateError($sql3);
878 if ($is_unique && ($temp_name != $name)) {
880 DBA::e("SET session old_alter_table=0;");
882 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
883 if (!DBA::isResult($r)) {
884 $errors .= self::printUpdateError($sql3);
887 $r = DBA::e("DROP TABLE `" . $name . "`;");
888 if (!DBA::isResult($r)) {
889 $errors .= self::printUpdateError($sql3);
892 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
893 if (!DBA::isResult($r)) {
894 $errors .= self::printUpdateError($sql3);
903 View::create(false, $action);
905 self::checkInitialValues();
907 if ($action && !$install) {
909 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
911 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
918 private static function tableStructure($table)
920 // This query doesn't seem to be executable as a prepared statement
921 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
923 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
924 ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
925 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
926 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
927 DBA::databaseName(), $table]);
929 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
930 ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
931 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
932 DBA::databaseName(), $table]);
934 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
935 ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
936 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
937 DBA::databaseName(), $table]);
943 if (DBA::isResult($foreign_keys)) {
944 foreach ($foreign_keys as $foreign_key) {
945 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
946 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
947 $foreigndata[$constraint] = $foreign_key;
951 if (DBA::isResult($indexes)) {
952 foreach ($indexes AS $index) {
953 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
954 $indexdata[$index["Key_name"]] = ["UNIQUE"];
957 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
958 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
961 $column = $index["Column_name"];
963 if ($index["Sub_part"] != "") {
964 $column .= "(" . $index["Sub_part"] . ")";
967 $indexdata[$index["Key_name"]][] = $column;
972 if (DBA::isResult($fields)) {
973 foreach ($fields AS $field) {
974 $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)'];
975 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
976 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
978 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
980 if ($field['IS_NULLABLE'] == 'NO') {
981 $fielddata[$field['COLUMN_NAME']]['not null'] = true;
984 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
985 $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
988 if (!empty($field['EXTRA'])) {
989 $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
992 if ($field['COLUMN_KEY'] == 'PRI') {
993 $fielddata[$field['COLUMN_NAME']]['primary'] = true;
996 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
997 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
1001 return ["fields" => $fielddata, "indexes" => $indexdata,
1002 "foreign_keys" => $foreigndata, "table_status" => $table_status];
1005 private static function dropIndex($indexname)
1007 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
1011 private static function addTableField($fieldname, $parameters)
1013 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
1017 private static function modifyTableField($fieldname, $parameters)
1019 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
1023 private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
1025 $foreign_table = array_keys($parameters['foreign'])[0];
1026 $foreign_field = array_values($parameters['foreign'])[0];
1028 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
1031 private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
1032 $foreign_table = array_keys($parameters['foreign'])[0];
1033 $foreign_field = array_values($parameters['foreign'])[0];
1035 $sql = "FOREIGN KEY (`" . $fieldname . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
1037 if (!empty($parameters['foreign']['on update'])) {
1038 $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
1040 $sql .= " ON UPDATE RESTRICT";
1043 if (!empty($parameters['foreign']['on delete'])) {
1044 $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
1046 $sql .= " ON DELETE CASCADE";
1052 private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
1054 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
1057 private static function dropForeignKey(string $constraint)
1059 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
1063 * Constructs a GROUP BY clause from a UNIQUE index definition.
1065 * @param array $fieldnames
1068 private static function groupBy(array $fieldnames)
1070 if ($fieldnames[0] != "UNIQUE") {
1074 array_shift($fieldnames);
1077 foreach ($fieldnames AS $fieldname) {
1082 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
1083 $names .= "`" . DBA::escape($matches[1]) . "`";
1085 $names .= "`" . DBA::escape($fieldname) . "`";
1089 $sql = sprintf(" GROUP BY %s", $names);
1094 * Renames columns or the primary key of a table
1096 * @todo You cannot rename a primary key if "auto increment" is set
1098 * @param string $table Table name
1099 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
1100 * Syntax for Primary Key: [ $col1, $col2, ...]
1101 * @param int $type The type of renaming (Default is Column)
1103 * @return boolean Was the renaming successful?
1106 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
1108 if (empty($table) || empty($columns)) {
1112 if (!is_array($columns)) {
1116 $table = DBA::escape($table);
1118 $sql = "ALTER TABLE `" . $table . "`";
1120 case self::RENAME_COLUMN:
1121 if (!self::existsColumn($table, array_keys($columns))) {
1124 $sql .= implode(',', array_map(
1125 function ($to, $from) {
1126 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
1129 array_keys($columns)
1132 case self::RENAME_PRIMARY_KEY:
1133 if (!self::existsColumn($table, $columns)) {
1136 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
1144 $stmt = DBA::p($sql);
1146 if (is_bool($stmt)) {
1158 * Check if the columns of the table exists
1160 * @param string $table Table name
1161 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
1163 * @return boolean Does the table exist?
1166 public static function existsColumn($table, $columns = [])
1168 if (empty($table)) {
1172 if (is_null($columns) || empty($columns)) {
1173 return self::existsTable($table);
1176 $table = DBA::escape($table);
1178 foreach ($columns AS $column) {
1179 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
1181 $stmt = DBA::p($sql);
1183 if (is_bool($stmt)) {
1186 $retval = (DBA::numRows($stmt) > 0);
1200 * Check if a foreign key exists for the given table field
1202 * @param string $table
1203 * @param string $field
1206 public static function existsForeignKeyForField(string $table, string $field)
1208 return DBA::exists(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
1209 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
1210 DBA::databaseName(), $table, $field]);
1213 * Check if a table exists
1215 * @param string|array $table Table name
1217 * @return boolean Does the table exist?
1220 public static function existsTable($table)
1222 if (empty($table)) {
1226 if (is_array($table)) {
1227 $condition = ['table_schema' => key($table), 'table_name' => current($table)];
1229 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
1232 $result = DBA::exists(['information_schema' => 'tables'], $condition);
1238 * Returns the columns of a table
1240 * @param string $table Table name
1242 * @return array An array of the table columns
1245 public static function getColumns($table)
1247 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
1248 return DBA::toArray($stmtColumns);
1252 * Check if initial database values do exist - or create them
1254 public static function checkInitialValues(bool $verbose = false)
1256 if (self::existsTable('verb')) {
1257 if (!DBA::exists('verb', ['id' => 1])) {
1258 foreach (Item::ACTIVITIES as $index => $activity) {
1259 DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], Database::INSERT_IGNORE);
1262 echo "verb: activities added\n";
1264 } elseif ($verbose) {
1265 echo "verb: activities already added\n";
1268 if (!DBA::exists('verb', ['id' => 0])) {
1269 DBA::insert('verb', ['name' => '']);
1270 $lastid = DBA::lastInsertId();
1272 DBA::update('verb', ['id' => 0], ['id' => $lastid]);
1274 echo "Zero verb added\n";
1277 } elseif ($verbose) {
1278 echo "Zero verb already added\n";
1280 } elseif ($verbose) {
1281 echo "verb: Table not found\n";
1284 if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) {
1287 "page-flags" => User::PAGE_FLAGS_SOAPBOX,
1288 "account-type" => User::ACCOUNT_TYPE_RELAY,
1290 DBA::insert('user', $user);
1291 $lastid = DBA::lastInsertId();
1293 DBA::update('user', ['uid' => 0], ['uid' => $lastid]);
1295 echo "Zero user added\n";
1298 } elseif (self::existsTable('user') && $verbose) {
1299 echo "Zero user already added\n";
1300 } elseif ($verbose) {
1301 echo "user: Table not found\n";
1304 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
1305 DBA::insert('contact', ['nurl' => '']);
1306 $lastid = DBA::lastInsertId();
1308 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
1310 echo "Zero contact added\n";
1313 } elseif (self::existsTable('contact') && $verbose) {
1314 echo "Zero contact already added\n";
1315 } elseif ($verbose) {
1316 echo "contact: Table not found\n";
1319 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
1320 DBA::insert('tag', ['name' => '']);
1321 $lastid = DBA::lastInsertId();
1323 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
1325 echo "Zero tag added\n";
1328 } elseif (self::existsTable('tag') && $verbose) {
1329 echo "Zero tag already added\n";
1330 } elseif ($verbose) {
1331 echo "tag: Table not found\n";
1334 if (self::existsTable('permissionset')) {
1335 if (!DBA::exists('permissionset', ['id' => 0])) {
1336 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
1337 $lastid = DBA::lastInsertId();
1339 DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
1341 echo "Zero permissionset added\n";
1344 } elseif ($verbose) {
1345 echo "Zero permissionset already added\n";
1347 if (self::existsTable('item') && !self::existsForeignKeyForField('item', 'psid')) {
1348 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
1349 LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
1350 WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
1351 while ($set = DBA::fetch($sets)) {
1352 if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
1353 $owner = User::getOwnerDataById($set['uid']);
1355 $permission = '<' . $owner['id'] . '>';
1362 $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
1363 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
1364 DBA::insert('permissionset', $fields);
1368 } elseif ($verbose) {
1369 echo "permissionset: Table not found\n";
1372 if (!self::existsForeignKeyForField('tokens', 'client_id')) {
1373 $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
1374 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
1375 WHERE `clients`.`client_id` IS NULL");
1376 while ($token = DBA::fetch($tokens)) {
1377 DBA::delete('tokens', ['id' => $token['id']]);
1379 DBA::close($tokens);
1384 * Checks if a database update is currently running
1388 private static function isUpdating()
1392 $processes = DBA::select(['information_schema' => 'processlist'], ['info'],
1393 ['db' => DBA::databaseName(), 'command' => ['Query', 'Execute']]);
1395 while ($process = DBA::fetch($processes)) {
1396 $parts = explode(' ', $process['info']);
1397 if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
1402 DBA::close($processes);