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', 'challenge',
85 'auth_codes', 'clients', 'tokens', 'profile_check'];
87 $tables = DBA::selectToArray(['INFORMATION_SCHEMA' => 'TABLES'], ['TABLE_NAME'],
88 ['TABLE_SCHEMA' => DBA::databaseName(), 'TABLE_TYPE' => 'BASE TABLE']);
91 echo DI::l10n()->t('No unused tables found.');
96 echo DI::l10n()->t('These tables are not used for friendica and will be deleted when you execute "dbstructure drop -e":') . "\n\n";
99 foreach ($tables as $table) {
100 if (in_array($table['TABLE_NAME'], $old_tables)) {
102 $sql = 'DROP TABLE ' . DBA::quoteIdentifier($table['TABLE_NAME']) . ';';
105 $result = DBA::e($sql);
106 if (!DBA::isResult($result)) {
107 self::printUpdateError($sql);
110 echo $table['TABLE_NAME'] . "\n";
117 * Converts all tables from MyISAM/InnoDB Antelope to InnoDB Barracuda
119 public static function convertToInnoDB()
121 $tables = DBA::selectToArray(
122 ['information_schema' => 'tables'],
124 ['engine' => 'MyISAM', 'table_schema' => DBA::databaseName()]
127 $tables = array_merge($tables, DBA::selectToArray(
128 ['information_schema' => 'tables'],
130 ['engine' => 'InnoDB', 'ROW_FORMAT' => ['COMPACT', 'REDUNDANT'], 'table_schema' => DBA::databaseName()]
133 if (!DBA::isResult($tables)) {
134 echo DI::l10n()->t('There are no tables on MyISAM or InnoDB with the Antelope file format.') . "\n";
138 foreach ($tables AS $table) {
139 $sql = "ALTER TABLE " . DBA::quoteIdentifier($table['table_name']) . " ENGINE=InnoDB ROW_FORMAT=DYNAMIC;";
142 $result = DBA::e($sql);
143 if (!DBA::isResult($result)) {
144 self::printUpdateError($sql);
150 * Print out database error messages
152 * @param string $message Message to be added to the error message
154 * @return string Error message
156 private static function printUpdateError($message)
158 echo DI::l10n()->t("\nError %d occurred during database update:\n%s\n",
159 DBA::errorNo(), DBA::errorMessage());
161 return DI::l10n()->t('Errors encountered performing database changes: ') . $message . EOL;
164 public static function writeStructure()
167 foreach (self::definition(null) as $name => $definition) {
170 'fields' => 'Fields',
177 $lengths = ['name' => 4, 'fields' => 6];
178 foreach ($definition['indexes'] as $key => $value) {
179 $fieldlist = implode(', ', $value);
180 $indexes[] = ['name' => $key, 'fields' => $fieldlist];
181 $lengths['name'] = max($lengths['name'], strlen($key));
182 $lengths['fields'] = max($lengths['fields'], strlen($fieldlist));
185 array_walk_recursive($indexes, function(&$value, $key) use ($lengths)
187 $value = str_pad($value, $lengths[$key], $value === '-' ? '-' : ' ');
193 'comment' => 'Description',
197 'default' => 'Default',
218 foreach ($definition['fields'] as $key => $value) {
220 $field['name'] = $key;
221 $field['comment'] = $value['comment'] ?? '';
222 $field['type'] = $value['type'];
223 $field['null'] = ($value['not null'] ?? false) ? 'NO' : 'YES';
224 $field['primary'] = ($value['primary'] ?? false) ? 'PRI' : '';
225 $field['default'] = $value['default'] ?? 'NULL';
226 $field['extra'] = $value['extra'] ?? '';
228 foreach ($field as $fieldname => $fieldvalue) {
229 $lengths[$fieldname] = max($lengths[$fieldname] ?? 0, strlen($fieldvalue));
233 if (!empty($value['foreign'])) {
236 'targettable' => array_keys($value['foreign'])[0],
237 'targetfield' => array_values($value['foreign'])[0]
242 array_walk_recursive($fields, function(&$value, $key) use ($lengths)
244 $value = str_pad($value, $lengths[$key], $value === '-' ? '-' : ' ');
247 $tables[] = ['name' => $name, 'comment' => $definition['comment']];
248 $content = Renderer::replaceMacros(Renderer::getMarkupTemplate('structure.tpl'), [
250 '$comment' => $definition['comment'],
251 '$fields' => $fields,
252 '$indexes' => $indexes,
253 '$foreign' => $foreign,
255 $filename = DI::basePath() . '/doc/database/db_' . $name . '.md';
256 file_put_contents($filename, $content);
259 $content = Renderer::replaceMacros(Renderer::getMarkupTemplate('tables.tpl'), [
260 '$tables' => $tables,
262 $filename = DI::basePath() . '/doc/database.md';
263 file_put_contents($filename, $content);
266 public static function printStructure($basePath)
268 $database = self::definition($basePath, false);
270 echo "-- ------------------------------------------\n";
271 echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n";
272 echo "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
273 echo "-- ------------------------------------------\n\n\n";
274 foreach ($database AS $name => $structure) {
276 echo "-- TABLE $name\n";
278 self::createTable($name, $structure, true, false);
283 View::printStructure($basePath);
287 * Loads the database structure definition from the static/dbstructure.config.php file.
288 * On first pass, defines DB_UPDATE_VERSION constant.
290 * @see static/dbstructure.config.php
291 * @param boolean $with_addons_structure Whether to tack on addons additional tables
292 * @param string $basePath The base path of this application
296 public static function definition($basePath, $with_addons_structure = true)
298 if (!self::$definition) {
299 if (empty($basePath)) {
300 $basePath = DI::app()->getBasePath();
303 $filename = $basePath . '/static/dbstructure.config.php';
305 if (!is_readable($filename)) {
306 throw new Exception('Missing database structure config file static/dbstructure.config.php');
309 $definition = require $filename;
312 throw new Exception('Corrupted database structure config file static/dbstructure.config.php');
315 self::$definition = $definition;
317 $definition = self::$definition;
320 if ($with_addons_structure) {
321 Hook::callAll('dbstructure_definition', $definition);
328 * Get field data for the given table
330 * @param string $table
331 * @param array $data data fields
332 * @return array fields for the given
334 public static function getFieldsForTable(string $table, array $data = [])
336 $definition = DBStructure::definition('', false);
337 if (empty($definition[$table])) {
341 $fieldnames = array_keys($definition[$table]['fields']);
345 // Assign all field that are present in the table
346 foreach ($fieldnames as $field) {
347 if (isset($data[$field])) {
348 // Limit the length of varchar, varbinary, char and binrary fields
349 if (is_string($data[$field]) && preg_match("/char\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
350 $data[$field] = mb_substr($data[$field], 0, $result[1]);
351 } elseif (is_string($data[$field]) && preg_match("/binary\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
352 $data[$field] = substr($data[$field], 0, $result[1]);
354 $fields[$field] = $data[$field];
361 private static function createTable($name, $structure, $verbose, $action)
371 foreach ($structure["fields"] AS $fieldname => $field) {
372 $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
373 if (!empty($field['primary'])) {
374 $primary_keys[] = $fieldname;
376 if (!empty($field['foreign'])) {
377 $foreign_keys[$fieldname] = $field;
381 if (!empty($structure["indexes"])) {
382 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
383 $sql_index = self::createIndex($indexname, $fieldnames, "");
384 if (!is_null($sql_index)) {
385 $sql_rows[] = $sql_index;
390 foreach ($foreign_keys AS $fieldname => $parameters) {
391 $sql_rows[] = self::foreignCommand($name, $fieldname, $parameters);
394 if (isset($structure["engine"])) {
395 $engine = " ENGINE=" . $structure["engine"];
398 if (isset($structure["comment"])) {
399 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
402 $sql = implode(",\n\t", $sql_rows);
404 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
405 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
417 private static function FieldCommand($parameters, $create = true)
419 $fieldstruct = $parameters["type"];
421 if (isset($parameters["Collation"])) {
422 $fieldstruct .= " COLLATE " . $parameters["Collation"];
425 if (isset($parameters["not null"])) {
426 $fieldstruct .= " NOT NULL";
429 if (isset($parameters["default"])) {
430 if (strpos(strtolower($parameters["type"]), "int") !== false) {
431 $fieldstruct .= " DEFAULT " . $parameters["default"];
433 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
436 if (isset($parameters["extra"])) {
437 $fieldstruct .= " " . $parameters["extra"];
440 if (isset($parameters["comment"])) {
441 $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
444 /*if (($parameters["primary"] != "") && $create)
445 $fieldstruct .= " PRIMARY KEY";*/
447 return ($fieldstruct);
450 private static function createIndex($indexname, $fieldnames, $method = "ADD")
452 $method = strtoupper(trim($method));
453 if ($method != "" && $method != "ADD") {
454 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
457 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
458 $index_type = array_shift($fieldnames);
459 $method .= " " . $index_type;
463 foreach ($fieldnames AS $fieldname) {
468 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
469 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
471 $names .= "`" . DBA::escape($fieldname) . "`";
475 if ($indexname == "PRIMARY") {
476 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
480 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
485 * Perform a database structure dryrun (means: just simulating)
489 public static function dryRun()
491 self::update(DI::app()->getBasePath(), true, false);
495 * Updates DB structure and returns eventual errors messages
497 * @param bool $enable_maintenance_mode Set the maintenance mode
498 * @param bool $verbose Display the SQL commands
500 * @return string Empty string if the update is successful, error messages otherwise
503 public static function performUpdate(bool $enable_maintenance_mode = true, bool $verbose = false)
505 if ($enable_maintenance_mode) {
506 DI::config()->set('system', 'maintenance', 1);
509 $status = self::update(DI::app()->getBasePath(), $verbose, true);
511 if ($enable_maintenance_mode) {
512 DI::config()->set('system', 'maintenance', 0);
513 DI::config()->set('system', 'maintenance_reason', '');
520 * Updates DB structure from the installation and returns eventual errors messages
522 * @param string $basePath The base path of this application
524 * @return string Empty string if the update is successful, error messages otherwise
527 public static function install(string $basePath)
529 return self::update($basePath, false, true, true);
533 * Updates DB structure and returns eventual errors messages
535 * @param string $basePath The base path of this application
536 * @param bool $verbose
537 * @param bool $action Whether to actually apply the update
538 * @param bool $install Is this the initial update during the installation?
539 * @param array $tables An array of the database tables
540 * @param array $definition An array of the definition tables
541 * @return string Empty string if the update is successful, error messages otherwise
544 private static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
546 $in_maintenance_mode = DI::config()->get('system', 'maintenance');
548 if ($action && !$install && self::isUpdating()) {
549 return DI::l10n()->t('Another database update is currently running.');
552 if ($in_maintenance_mode) {
553 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
556 // ensure that all initial values exist. This test has to be done prior and after the structure check.
557 // Prior is needed if the specific tables already exists - after is needed when they had been created.
558 self::checkInitialValues();
562 Logger::info('updating structure');
564 // Get the current structure
567 if (is_null($tables)) {
568 $tables = DBA::toArray(DBA::p("SHOW TABLES"));
571 if (DBA::isResult($tables)) {
572 foreach ($tables AS $table) {
573 $table = current($table);
575 Logger::info('updating structure', ['table' => $table]);
576 $database[$table] = self::tableStructure($table);
580 // Get the definition
581 if (is_null($definition)) {
582 $definition = self::definition($basePath);
585 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
586 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
587 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
594 foreach ($definition AS $name => $structure) {
595 $is_new_table = false;
600 if (!isset($database[$name])) {
601 $r = self::createTable($name, $structure, $verbose, $action);
602 if (!DBA::isResult($r)) {
603 $errors .= self::printUpdateError($name);
605 $is_new_table = true;
607 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
608 if (isset($database[$name]["indexes"][$indexname])) {
609 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
611 $current_index_definition = "__NOT_SET__";
613 $new_index_definition = implode(",", $fieldnames);
614 if ($current_index_definition != $new_index_definition) {
615 if ($fieldnames[0] == "UNIQUE") {
618 $temp_name = "temp-" . $name;
625 * Drop the index if it isn't present in the definition
626 * or the definition differ from current status
627 * and index name doesn't start with "local_"
629 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
630 $current_index_definition = implode(",", $fieldnames);
631 if (isset($structure["indexes"][$indexname])) {
632 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
634 $new_index_definition = "__NOT_SET__";
636 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
637 $sql2 = self::dropIndex($indexname);
639 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
641 $sql3 .= ", " . $sql2;
645 // Compare the field structure field by field
646 foreach ($structure["fields"] AS $fieldname => $parameters) {
647 if (!isset($database[$name]["fields"][$fieldname])) {
648 $sql2 = self::addTableField($fieldname, $parameters);
650 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
652 $sql3 .= ", " . $sql2;
655 // Compare the field definition
656 $field_definition = $database[$name]["fields"][$fieldname];
658 // Remove the relation data that is used for the referential integrity
659 unset($parameters['relation']);
660 unset($parameters['foreign']);
662 // We change the collation after the indexes had been changed.
663 // This is done to avoid index length problems.
664 // So here we always ensure that there is no need to change it.
665 unset($parameters['Collation']);
666 unset($field_definition['Collation']);
668 // Only update the comment when it is defined
669 if (!isset($parameters['comment'])) {
670 $parameters['comment'] = "";
673 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
674 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
675 if ($current_field_definition != $new_field_definition) {
676 $sql2 = self::modifyTableField($fieldname, $parameters);
678 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
680 $sql3 .= ", " . $sql2;
688 * Create the index if the index don't exists in database
689 * or the definition differ from the current status.
690 * Don't create keys if table is new
692 if (!$is_new_table) {
693 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
694 if (isset($database[$name]["indexes"][$indexname])) {
695 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
697 $current_index_definition = "__NOT_SET__";
699 $new_index_definition = implode(",", $fieldnames);
700 if ($current_index_definition != $new_index_definition) {
701 $sql2 = self::createIndex($indexname, $fieldnames);
703 // Fetch the "group by" fields for unique indexes
704 $group_by = self::groupBy($fieldnames);
707 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
709 $sql3 .= ", " . $sql2;
715 $existing_foreign_keys = $database[$name]['foreign_keys'];
718 // Compare the field structure field by field
719 foreach ($structure["fields"] AS $fieldname => $parameters) {
720 if (empty($parameters['foreign'])) {
724 $constraint = self::getConstraintName($name, $fieldname, $parameters);
726 unset($existing_foreign_keys[$constraint]);
728 if (empty($database[$name]['foreign_keys'][$constraint])) {
729 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
732 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
734 $sql3 .= ", " . $sql2;
739 foreach ($existing_foreign_keys as $param) {
740 $sql2 = self::dropForeignKey($param['CONSTRAINT_NAME']);
743 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
745 $sql3 .= ", " . $sql2;
749 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
750 $structurecomment = $structure["comment"] ?? '';
751 if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
752 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
755 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
757 $sql3 .= ", " . $sql2;
762 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
763 if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
764 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
767 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
769 $sql3 .= ", " . $sql2;
774 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
775 if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
776 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
779 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
781 $sql3 .= ", " . $sql2;
790 // Now have a look at the field collations
791 // Compare the field structure field by field
792 foreach ($structure["fields"] AS $fieldname => $parameters) {
793 // Compare the field definition
794 $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
796 // Define the default collation if not given
797 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
798 $parameters['Collation'] = 'utf8mb4_general_ci';
800 $parameters['Collation'] = null;
803 if ($field_definition['Collation'] != $parameters['Collation']) {
804 $sql2 = self::modifyTableField($fieldname, $parameters);
805 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
806 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
808 $sql3 .= ", " . $sql2;
815 if (substr($sql3, -2, 2) != "; ") {
820 if ($is_unique && $ignore == '') {
821 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
822 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
824 $field_list = rtrim($field_list, ',');
828 // Ensure index conversion to unique removes duplicates
829 if ($is_unique && ($temp_name != $name)) {
831 echo "SET session old_alter_table=1;\n";
833 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
834 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
840 if ($is_unique && ($temp_name != $name)) {
842 echo "SET session old_alter_table=0;\n";
844 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
845 echo "DROP TABLE `" . $name . "`;\n";
846 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
852 if ($in_maintenance_mode) {
853 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
856 // Ensure index conversion to unique removes duplicates
857 if ($is_unique && ($temp_name != $name)) {
859 DBA::e("SET session old_alter_table=1;");
861 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
862 if (!DBA::isResult($r)) {
863 $errors .= self::printUpdateError($sql3);
867 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
868 if (!DBA::isResult($r)) {
869 $errors .= self::printUpdateError($sql3);
876 if (!DBA::isResult($r)) {
877 $errors .= self::printUpdateError($sql3);
879 if ($is_unique && ($temp_name != $name)) {
881 DBA::e("SET session old_alter_table=0;");
883 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
884 if (!DBA::isResult($r)) {
885 $errors .= self::printUpdateError($sql3);
888 $r = DBA::e("DROP TABLE `" . $name . "`;");
889 if (!DBA::isResult($r)) {
890 $errors .= self::printUpdateError($sql3);
893 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
894 if (!DBA::isResult($r)) {
895 $errors .= self::printUpdateError($sql3);
904 View::create(false, $action);
906 self::checkInitialValues();
908 if ($action && !$install) {
910 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
912 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
919 private static function tableStructure($table)
921 // This query doesn't seem to be executable as a prepared statement
922 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
924 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
925 ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
926 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
927 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
928 DBA::databaseName(), $table]);
930 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
931 ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
932 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
933 DBA::databaseName(), $table]);
935 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
936 ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
937 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
938 DBA::databaseName(), $table]);
944 if (DBA::isResult($foreign_keys)) {
945 foreach ($foreign_keys as $foreign_key) {
946 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
947 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
948 $foreigndata[$constraint] = $foreign_key;
952 if (DBA::isResult($indexes)) {
953 foreach ($indexes AS $index) {
954 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
955 $indexdata[$index["Key_name"]] = ["UNIQUE"];
958 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
959 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
962 $column = $index["Column_name"];
964 if ($index["Sub_part"] != "") {
965 $column .= "(" . $index["Sub_part"] . ")";
968 $indexdata[$index["Key_name"]][] = $column;
973 if (DBA::isResult($fields)) {
974 foreach ($fields AS $field) {
975 $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)'];
976 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
977 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
979 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
981 if ($field['IS_NULLABLE'] == 'NO') {
982 $fielddata[$field['COLUMN_NAME']]['not null'] = true;
985 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
986 $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
989 if (!empty($field['EXTRA'])) {
990 $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
993 if ($field['COLUMN_KEY'] == 'PRI') {
994 $fielddata[$field['COLUMN_NAME']]['primary'] = true;
997 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
998 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
1002 return ["fields" => $fielddata, "indexes" => $indexdata,
1003 "foreign_keys" => $foreigndata, "table_status" => $table_status];
1006 private static function dropIndex($indexname)
1008 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
1012 private static function addTableField($fieldname, $parameters)
1014 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
1018 private static function modifyTableField($fieldname, $parameters)
1020 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
1024 private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
1026 $foreign_table = array_keys($parameters['foreign'])[0];
1027 $foreign_field = array_values($parameters['foreign'])[0];
1029 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
1032 private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
1033 $foreign_table = array_keys($parameters['foreign'])[0];
1034 $foreign_field = array_values($parameters['foreign'])[0];
1036 $sql = "FOREIGN KEY (`" . $fieldname . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
1038 if (!empty($parameters['foreign']['on update'])) {
1039 $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
1041 $sql .= " ON UPDATE RESTRICT";
1044 if (!empty($parameters['foreign']['on delete'])) {
1045 $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
1047 $sql .= " ON DELETE CASCADE";
1053 private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
1055 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
1058 private static function dropForeignKey(string $constraint)
1060 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
1064 * Constructs a GROUP BY clause from a UNIQUE index definition.
1066 * @param array $fieldnames
1069 private static function groupBy(array $fieldnames)
1071 if ($fieldnames[0] != "UNIQUE") {
1075 array_shift($fieldnames);
1078 foreach ($fieldnames AS $fieldname) {
1083 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
1084 $names .= "`" . DBA::escape($matches[1]) . "`";
1086 $names .= "`" . DBA::escape($fieldname) . "`";
1090 $sql = sprintf(" GROUP BY %s", $names);
1095 * Renames columns or the primary key of a table
1097 * @todo You cannot rename a primary key if "auto increment" is set
1099 * @param string $table Table name
1100 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
1101 * Syntax for Primary Key: [ $col1, $col2, ...]
1102 * @param int $type The type of renaming (Default is Column)
1104 * @return boolean Was the renaming successful?
1107 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
1109 if (empty($table) || empty($columns)) {
1113 if (!is_array($columns)) {
1117 $table = DBA::escape($table);
1119 $sql = "ALTER TABLE `" . $table . "`";
1121 case self::RENAME_COLUMN:
1122 if (!self::existsColumn($table, array_keys($columns))) {
1125 $sql .= implode(',', array_map(
1126 function ($to, $from) {
1127 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
1130 array_keys($columns)
1133 case self::RENAME_PRIMARY_KEY:
1134 if (!self::existsColumn($table, $columns)) {
1137 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
1145 $stmt = DBA::p($sql);
1147 if (is_bool($stmt)) {
1159 * Check if the columns of the table exists
1161 * @param string $table Table name
1162 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
1164 * @return boolean Does the table exist?
1167 public static function existsColumn($table, $columns = [])
1169 if (empty($table)) {
1173 if (is_null($columns) || empty($columns)) {
1174 return self::existsTable($table);
1177 $table = DBA::escape($table);
1179 foreach ($columns AS $column) {
1180 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
1182 $stmt = DBA::p($sql);
1184 if (is_bool($stmt)) {
1187 $retval = (DBA::numRows($stmt) > 0);
1201 * Check if a foreign key exists for the given table field
1203 * @param string $table
1204 * @param string $field
1207 public static function existsForeignKeyForField(string $table, string $field)
1209 return DBA::exists(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
1210 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
1211 DBA::databaseName(), $table, $field]);
1214 * Check if a table exists
1216 * @param string|array $table Table name
1218 * @return boolean Does the table exist?
1221 public static function existsTable($table)
1223 if (empty($table)) {
1227 if (is_array($table)) {
1228 $condition = ['table_schema' => key($table), 'table_name' => current($table)];
1230 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
1233 $result = DBA::exists(['information_schema' => 'tables'], $condition);
1239 * Returns the columns of a table
1241 * @param string $table Table name
1243 * @return array An array of the table columns
1246 public static function getColumns($table)
1248 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
1249 return DBA::toArray($stmtColumns);
1253 * Check if initial database values do exist - or create them
1255 public static function checkInitialValues(bool $verbose = false)
1257 if (self::existsTable('verb')) {
1258 if (!DBA::exists('verb', ['id' => 1])) {
1259 foreach (Item::ACTIVITIES as $index => $activity) {
1260 DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], Database::INSERT_IGNORE);
1263 echo "verb: activities added\n";
1265 } elseif ($verbose) {
1266 echo "verb: activities already added\n";
1269 if (!DBA::exists('verb', ['id' => 0])) {
1270 DBA::insert('verb', ['name' => '']);
1271 $lastid = DBA::lastInsertId();
1273 DBA::update('verb', ['id' => 0], ['id' => $lastid]);
1275 echo "Zero verb added\n";
1278 } elseif ($verbose) {
1279 echo "Zero verb already added\n";
1281 } elseif ($verbose) {
1282 echo "verb: Table not found\n";
1285 if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) {
1288 "page-flags" => User::PAGE_FLAGS_SOAPBOX,
1289 "account-type" => User::ACCOUNT_TYPE_RELAY,
1291 DBA::insert('user', $user);
1292 $lastid = DBA::lastInsertId();
1294 DBA::update('user', ['uid' => 0], ['uid' => $lastid]);
1296 echo "Zero user added\n";
1299 } elseif (self::existsTable('user') && $verbose) {
1300 echo "Zero user already added\n";
1301 } elseif ($verbose) {
1302 echo "user: Table not found\n";
1305 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
1306 DBA::insert('contact', ['nurl' => '']);
1307 $lastid = DBA::lastInsertId();
1309 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
1311 echo "Zero contact added\n";
1314 } elseif (self::existsTable('contact') && $verbose) {
1315 echo "Zero contact already added\n";
1316 } elseif ($verbose) {
1317 echo "contact: Table not found\n";
1320 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
1321 DBA::insert('tag', ['name' => '']);
1322 $lastid = DBA::lastInsertId();
1324 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
1326 echo "Zero tag added\n";
1329 } elseif (self::existsTable('tag') && $verbose) {
1330 echo "Zero tag already added\n";
1331 } elseif ($verbose) {
1332 echo "tag: Table not found\n";
1335 if (self::existsTable('permissionset')) {
1336 if (!DBA::exists('permissionset', ['id' => 0])) {
1337 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
1338 $lastid = DBA::lastInsertId();
1340 DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
1342 echo "Zero permissionset added\n";
1345 } elseif ($verbose) {
1346 echo "Zero permissionset already added\n";
1348 if (self::existsTable('item') && !self::existsForeignKeyForField('item', 'psid')) {
1349 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
1350 LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
1351 WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
1352 while ($set = DBA::fetch($sets)) {
1353 if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
1354 $owner = User::getOwnerDataById($set['uid']);
1356 $permission = '<' . $owner['id'] . '>';
1363 $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
1364 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
1365 DBA::insert('permissionset', $fields);
1369 } elseif ($verbose) {
1370 echo "permissionset: Table not found\n";
1373 if (self::existsTable('tokens') && self::existsTable('clients') && !self::existsForeignKeyForField('tokens', 'client_id')) {
1374 $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
1375 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
1376 WHERE `clients`.`client_id` IS NULL");
1377 while ($token = DBA::fetch($tokens)) {
1378 DBA::delete('tokens', ['id' => $token['id']]);
1380 DBA::close($tokens);
1385 * Checks if a database update is currently running
1389 private static function isUpdating()
1393 $processes = DBA::select(['information_schema' => 'processlist'], ['info'],
1394 ['db' => DBA::databaseName(), 'command' => ['Query', 'Execute']]);
1396 while ($process = DBA::fetch($processes)) {
1397 $parts = explode(' ', $process['info']);
1398 if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
1403 DBA::close($processes);