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()
165 Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
168 foreach (self::definition(null) as $name => $definition) {
171 'fields' => 'Fields',
178 $lengths = ['name' => 4, 'fields' => 6];
179 foreach ($definition['indexes'] as $key => $value) {
180 $fieldlist = implode(', ', $value);
181 $indexes[] = ['name' => $key, 'fields' => $fieldlist];
182 $lengths['name'] = max($lengths['name'], strlen($key));
183 $lengths['fields'] = max($lengths['fields'], strlen($fieldlist));
186 array_walk_recursive($indexes, function(&$value, $key) use ($lengths)
188 $value = str_pad($value, $lengths[$key], $value === '-' ? '-' : ' ');
194 'comment' => 'Description',
198 'default' => 'Default',
219 foreach ($definition['fields'] as $key => $value) {
221 $field['name'] = $key;
222 $field['comment'] = $value['comment'] ?? '';
223 $field['type'] = $value['type'];
224 $field['null'] = ($value['not null'] ?? false) ? 'NO' : 'YES';
225 $field['primary'] = ($value['primary'] ?? false) ? 'PRI' : '';
226 $field['default'] = $value['default'] ?? 'NULL';
227 $field['extra'] = $value['extra'] ?? '';
229 foreach ($field as $fieldname => $fieldvalue) {
230 $lengths[$fieldname] = max($lengths[$fieldname] ?? 0, strlen($fieldvalue));
234 if (!empty($value['foreign'])) {
237 'targettable' => array_keys($value['foreign'])[0],
238 'targetfield' => array_values($value['foreign'])[0]
243 array_walk_recursive($fields, function(&$value, $key) use ($lengths)
245 $value = str_pad($value, $lengths[$key], $value === '-' ? '-' : ' ');
248 $tables[] = ['name' => $name, 'comment' => $definition['comment']];
249 $content = Renderer::replaceMacros(Renderer::getMarkupTemplate('structure.tpl'), [
251 '$comment' => $definition['comment'],
252 '$fields' => $fields,
253 '$indexes' => $indexes,
254 '$foreign' => $foreign,
256 $filename = DI::basePath() . '/doc/database/db_' . $name . '.md';
257 file_put_contents($filename, $content);
260 $content = Renderer::replaceMacros(Renderer::getMarkupTemplate('tables.tpl'), [
261 '$tables' => $tables,
263 $filename = DI::basePath() . '/doc/database.md';
264 file_put_contents($filename, $content);
267 public static function printStructure($basePath)
269 $database = self::definition($basePath, false);
271 echo "-- ------------------------------------------\n";
272 echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n";
273 echo "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
274 echo "-- ------------------------------------------\n\n\n";
275 foreach ($database AS $name => $structure) {
277 echo "-- TABLE $name\n";
279 self::createTable($name, $structure, true, false);
284 View::printStructure($basePath);
288 * Loads the database structure definition from the static/dbstructure.config.php file.
289 * On first pass, defines DB_UPDATE_VERSION constant.
291 * @see static/dbstructure.config.php
292 * @param boolean $with_addons_structure Whether to tack on addons additional tables
293 * @param string $basePath The base path of this application
297 public static function definition($basePath, $with_addons_structure = true)
299 if (!self::$definition) {
300 if (empty($basePath)) {
301 $basePath = DI::app()->getBasePath();
304 $filename = $basePath . '/static/dbstructure.config.php';
306 if (!is_readable($filename)) {
307 throw new Exception('Missing database structure config file static/dbstructure.config.php');
310 $definition = require $filename;
313 throw new Exception('Corrupted database structure config file static/dbstructure.config.php');
316 self::$definition = $definition;
318 $definition = self::$definition;
321 if ($with_addons_structure) {
322 Hook::callAll('dbstructure_definition', $definition);
329 * Get field data for the given table
331 * @param string $table
332 * @param array $data data fields
333 * @return array fields for the given
335 public static function getFieldsForTable(string $table, array $data = [])
337 $definition = DBStructure::definition('', false);
338 if (empty($definition[$table])) {
342 $fieldnames = array_keys($definition[$table]['fields']);
346 // Assign all field that are present in the table
347 foreach ($fieldnames as $field) {
348 if (isset($data[$field])) {
349 // Limit the length of varchar, varbinary, char and binrary fields
350 if (is_string($data[$field]) && preg_match("/char\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
351 $data[$field] = mb_substr($data[$field], 0, $result[1]);
352 } elseif (is_string($data[$field]) && preg_match("/binary\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
353 $data[$field] = substr($data[$field], 0, $result[1]);
355 $fields[$field] = $data[$field];
362 private static function createTable($name, $structure, $verbose, $action)
372 foreach ($structure["fields"] AS $fieldname => $field) {
373 $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
374 if (!empty($field['primary'])) {
375 $primary_keys[] = $fieldname;
377 if (!empty($field['foreign'])) {
378 $foreign_keys[$fieldname] = $field;
382 if (!empty($structure["indexes"])) {
383 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
384 $sql_index = self::createIndex($indexname, $fieldnames, "");
385 if (!is_null($sql_index)) {
386 $sql_rows[] = $sql_index;
391 foreach ($foreign_keys AS $fieldname => $parameters) {
392 $sql_rows[] = self::foreignCommand($name, $fieldname, $parameters);
395 if (isset($structure["engine"])) {
396 $engine = " ENGINE=" . $structure["engine"];
399 if (isset($structure["comment"])) {
400 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
403 $sql = implode(",\n\t", $sql_rows);
405 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
406 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
418 private static function FieldCommand($parameters, $create = true)
420 $fieldstruct = $parameters["type"];
422 if (isset($parameters["Collation"])) {
423 $fieldstruct .= " COLLATE " . $parameters["Collation"];
426 if (isset($parameters["not null"])) {
427 $fieldstruct .= " NOT NULL";
430 if (isset($parameters["default"])) {
431 if (strpos(strtolower($parameters["type"]), "int") !== false) {
432 $fieldstruct .= " DEFAULT " . $parameters["default"];
434 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
437 if (isset($parameters["extra"])) {
438 $fieldstruct .= " " . $parameters["extra"];
441 if (isset($parameters["comment"])) {
442 $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
445 /*if (($parameters["primary"] != "") && $create)
446 $fieldstruct .= " PRIMARY KEY";*/
448 return ($fieldstruct);
451 private static function createIndex($indexname, $fieldnames, $method = "ADD")
453 $method = strtoupper(trim($method));
454 if ($method != "" && $method != "ADD") {
455 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
458 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
459 $index_type = array_shift($fieldnames);
460 $method .= " " . $index_type;
464 foreach ($fieldnames AS $fieldname) {
469 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
470 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
472 $names .= "`" . DBA::escape($fieldname) . "`";
476 if ($indexname == "PRIMARY") {
477 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
481 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
486 * Perform a database structure dryrun (means: just simulating)
490 public static function dryRun()
492 self::update(DI::app()->getBasePath(), true, false);
496 * Updates DB structure and returns eventual errors messages
498 * @param bool $enable_maintenance_mode Set the maintenance mode
499 * @param bool $verbose Display the SQL commands
501 * @return string Empty string if the update is successful, error messages otherwise
504 public static function performUpdate(bool $enable_maintenance_mode = true, bool $verbose = false)
506 if ($enable_maintenance_mode) {
507 DI::config()->set('system', 'maintenance', 1);
510 $status = self::update(DI::app()->getBasePath(), $verbose, true);
512 if ($enable_maintenance_mode) {
513 DI::config()->set('system', 'maintenance', 0);
514 DI::config()->set('system', 'maintenance_reason', '');
521 * Updates DB structure from the installation and returns eventual errors messages
523 * @param string $basePath The base path of this application
525 * @return string Empty string if the update is successful, error messages otherwise
528 public static function install(string $basePath)
530 return self::update($basePath, false, true, true);
534 * Updates DB structure and returns eventual errors messages
536 * @param string $basePath The base path of this application
537 * @param bool $verbose
538 * @param bool $action Whether to actually apply the update
539 * @param bool $install Is this the initial update during the installation?
540 * @param array $tables An array of the database tables
541 * @param array $definition An array of the definition tables
542 * @return string Empty string if the update is successful, error messages otherwise
545 private static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
547 $in_maintenance_mode = DI::config()->get('system', 'maintenance');
549 if ($action && !$install && self::isUpdating()) {
550 return DI::l10n()->t('Another database update is currently running.');
553 if ($in_maintenance_mode) {
554 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
557 // ensure that all initial values exist. This test has to be done prior and after the structure check.
558 // Prior is needed if the specific tables already exists - after is needed when they had been created.
559 self::checkInitialValues();
563 Logger::info('updating structure');
565 // Get the current structure
568 if (is_null($tables)) {
569 $tables = DBA::toArray(DBA::p("SHOW TABLES"));
572 if (DBA::isResult($tables)) {
573 foreach ($tables AS $table) {
574 $table = current($table);
576 Logger::info('updating structure', ['table' => $table]);
577 $database[$table] = self::tableStructure($table);
581 // Get the definition
582 if (is_null($definition)) {
583 $definition = self::definition($basePath);
586 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
587 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
588 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
595 foreach ($definition AS $name => $structure) {
596 $is_new_table = false;
601 if (!isset($database[$name])) {
602 $r = self::createTable($name, $structure, $verbose, $action);
603 if (!DBA::isResult($r)) {
604 $errors .= self::printUpdateError($name);
606 $is_new_table = true;
608 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
609 if (isset($database[$name]["indexes"][$indexname])) {
610 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
612 $current_index_definition = "__NOT_SET__";
614 $new_index_definition = implode(",", $fieldnames);
615 if ($current_index_definition != $new_index_definition) {
616 if ($fieldnames[0] == "UNIQUE") {
619 $temp_name = "temp-" . $name;
626 * Drop the index if it isn't present in the definition
627 * or the definition differ from current status
628 * and index name doesn't start with "local_"
630 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
631 $current_index_definition = implode(",", $fieldnames);
632 if (isset($structure["indexes"][$indexname])) {
633 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
635 $new_index_definition = "__NOT_SET__";
637 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
638 $sql2 = self::dropIndex($indexname);
640 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
642 $sql3 .= ", " . $sql2;
646 // Compare the field structure field by field
647 foreach ($structure["fields"] AS $fieldname => $parameters) {
648 if (!isset($database[$name]["fields"][$fieldname])) {
649 $sql2 = self::addTableField($fieldname, $parameters);
651 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
653 $sql3 .= ", " . $sql2;
656 // Compare the field definition
657 $field_definition = $database[$name]["fields"][$fieldname];
659 // Remove the relation data that is used for the referential integrity
660 unset($parameters['relation']);
661 unset($parameters['foreign']);
663 // We change the collation after the indexes had been changed.
664 // This is done to avoid index length problems.
665 // So here we always ensure that there is no need to change it.
666 unset($parameters['Collation']);
667 unset($field_definition['Collation']);
669 // Only update the comment when it is defined
670 if (!isset($parameters['comment'])) {
671 $parameters['comment'] = "";
674 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
675 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
676 if ($current_field_definition != $new_field_definition) {
677 $sql2 = self::modifyTableField($fieldname, $parameters);
679 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
681 $sql3 .= ", " . $sql2;
689 * Create the index if the index don't exists in database
690 * or the definition differ from the current status.
691 * Don't create keys if table is new
693 if (!$is_new_table) {
694 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
695 if (isset($database[$name]["indexes"][$indexname])) {
696 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
698 $current_index_definition = "__NOT_SET__";
700 $new_index_definition = implode(",", $fieldnames);
701 if ($current_index_definition != $new_index_definition) {
702 $sql2 = self::createIndex($indexname, $fieldnames);
704 // Fetch the "group by" fields for unique indexes
705 $group_by = self::groupBy($fieldnames);
708 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
710 $sql3 .= ", " . $sql2;
716 $existing_foreign_keys = $database[$name]['foreign_keys'];
719 // Compare the field structure field by field
720 foreach ($structure["fields"] AS $fieldname => $parameters) {
721 if (empty($parameters['foreign'])) {
725 $constraint = self::getConstraintName($name, $fieldname, $parameters);
727 unset($existing_foreign_keys[$constraint]);
729 if (empty($database[$name]['foreign_keys'][$constraint])) {
730 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
733 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
735 $sql3 .= ", " . $sql2;
740 foreach ($existing_foreign_keys as $param) {
741 $sql2 = self::dropForeignKey($param['CONSTRAINT_NAME']);
744 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
746 $sql3 .= ", " . $sql2;
750 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
751 $structurecomment = $structure["comment"] ?? '';
752 if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
753 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
756 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
758 $sql3 .= ", " . $sql2;
763 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
764 if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
765 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
768 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
770 $sql3 .= ", " . $sql2;
775 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
776 if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
777 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
780 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
782 $sql3 .= ", " . $sql2;
791 // Now have a look at the field collations
792 // Compare the field structure field by field
793 foreach ($structure["fields"] AS $fieldname => $parameters) {
794 // Compare the field definition
795 $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
797 // Define the default collation if not given
798 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
799 $parameters['Collation'] = 'utf8mb4_general_ci';
801 $parameters['Collation'] = null;
804 if ($field_definition['Collation'] != $parameters['Collation']) {
805 $sql2 = self::modifyTableField($fieldname, $parameters);
806 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
807 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
809 $sql3 .= ", " . $sql2;
816 if (substr($sql3, -2, 2) != "; ") {
821 if ($is_unique && $ignore == '') {
822 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
823 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
825 $field_list = rtrim($field_list, ',');
829 // Ensure index conversion to unique removes duplicates
830 if ($is_unique && ($temp_name != $name)) {
832 echo "SET session old_alter_table=1;\n";
834 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
835 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
841 if ($is_unique && ($temp_name != $name)) {
843 echo "SET session old_alter_table=0;\n";
845 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
846 echo "DROP TABLE `" . $name . "`;\n";
847 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
853 if ($in_maintenance_mode) {
854 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
857 // Ensure index conversion to unique removes duplicates
858 if ($is_unique && ($temp_name != $name)) {
860 DBA::e("SET session old_alter_table=1;");
862 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
863 if (!DBA::isResult($r)) {
864 $errors .= self::printUpdateError($sql3);
868 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
869 if (!DBA::isResult($r)) {
870 $errors .= self::printUpdateError($sql3);
877 if (!DBA::isResult($r)) {
878 $errors .= self::printUpdateError($sql3);
880 if ($is_unique && ($temp_name != $name)) {
882 DBA::e("SET session old_alter_table=0;");
884 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
885 if (!DBA::isResult($r)) {
886 $errors .= self::printUpdateError($sql3);
889 $r = DBA::e("DROP TABLE `" . $name . "`;");
890 if (!DBA::isResult($r)) {
891 $errors .= self::printUpdateError($sql3);
894 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
895 if (!DBA::isResult($r)) {
896 $errors .= self::printUpdateError($sql3);
905 View::create(false, $action);
907 self::checkInitialValues();
909 if ($action && !$install) {
911 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
913 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
920 private static function tableStructure($table)
922 // This query doesn't seem to be executable as a prepared statement
923 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
925 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
926 ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
927 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
928 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
929 DBA::databaseName(), $table]);
931 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
932 ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
933 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
934 DBA::databaseName(), $table]);
936 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
937 ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
938 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
939 DBA::databaseName(), $table]);
945 if (DBA::isResult($foreign_keys)) {
946 foreach ($foreign_keys as $foreign_key) {
947 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
948 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
949 $foreigndata[$constraint] = $foreign_key;
953 if (DBA::isResult($indexes)) {
954 foreach ($indexes AS $index) {
955 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
956 $indexdata[$index["Key_name"]] = ["UNIQUE"];
959 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
960 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
963 $column = $index["Column_name"];
965 if ($index["Sub_part"] != "") {
966 $column .= "(" . $index["Sub_part"] . ")";
969 $indexdata[$index["Key_name"]][] = $column;
974 if (DBA::isResult($fields)) {
975 foreach ($fields AS $field) {
976 $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)'];
977 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
978 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
980 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
982 if ($field['IS_NULLABLE'] == 'NO') {
983 $fielddata[$field['COLUMN_NAME']]['not null'] = true;
986 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
987 $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
990 if (!empty($field['EXTRA'])) {
991 $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
994 if ($field['COLUMN_KEY'] == 'PRI') {
995 $fielddata[$field['COLUMN_NAME']]['primary'] = true;
998 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
999 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
1003 return ["fields" => $fielddata, "indexes" => $indexdata,
1004 "foreign_keys" => $foreigndata, "table_status" => $table_status];
1007 private static function dropIndex($indexname)
1009 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
1013 private static function addTableField($fieldname, $parameters)
1015 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
1019 private static function modifyTableField($fieldname, $parameters)
1021 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
1025 private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
1027 $foreign_table = array_keys($parameters['foreign'])[0];
1028 $foreign_field = array_values($parameters['foreign'])[0];
1030 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
1033 private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
1034 $foreign_table = array_keys($parameters['foreign'])[0];
1035 $foreign_field = array_values($parameters['foreign'])[0];
1037 $sql = "FOREIGN KEY (`" . $fieldname . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
1039 if (!empty($parameters['foreign']['on update'])) {
1040 $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
1042 $sql .= " ON UPDATE RESTRICT";
1045 if (!empty($parameters['foreign']['on delete'])) {
1046 $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
1048 $sql .= " ON DELETE CASCADE";
1054 private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
1056 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
1059 private static function dropForeignKey(string $constraint)
1061 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
1065 * Constructs a GROUP BY clause from a UNIQUE index definition.
1067 * @param array $fieldnames
1070 private static function groupBy(array $fieldnames)
1072 if ($fieldnames[0] != "UNIQUE") {
1076 array_shift($fieldnames);
1079 foreach ($fieldnames AS $fieldname) {
1084 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
1085 $names .= "`" . DBA::escape($matches[1]) . "`";
1087 $names .= "`" . DBA::escape($fieldname) . "`";
1091 $sql = sprintf(" GROUP BY %s", $names);
1096 * Renames columns or the primary key of a table
1098 * @todo You cannot rename a primary key if "auto increment" is set
1100 * @param string $table Table name
1101 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
1102 * Syntax for Primary Key: [ $col1, $col2, ...]
1103 * @param int $type The type of renaming (Default is Column)
1105 * @return boolean Was the renaming successful?
1108 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
1110 if (empty($table) || empty($columns)) {
1114 if (!is_array($columns)) {
1118 $table = DBA::escape($table);
1120 $sql = "ALTER TABLE `" . $table . "`";
1122 case self::RENAME_COLUMN:
1123 if (!self::existsColumn($table, array_keys($columns))) {
1126 $sql .= implode(',', array_map(
1127 function ($to, $from) {
1128 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
1131 array_keys($columns)
1134 case self::RENAME_PRIMARY_KEY:
1135 if (!self::existsColumn($table, $columns)) {
1138 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
1146 $stmt = DBA::p($sql);
1148 if (is_bool($stmt)) {
1160 * Check if the columns of the table exists
1162 * @param string $table Table name
1163 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
1165 * @return boolean Does the table exist?
1168 public static function existsColumn($table, $columns = [])
1170 if (empty($table)) {
1174 if (is_null($columns) || empty($columns)) {
1175 return self::existsTable($table);
1178 $table = DBA::escape($table);
1180 foreach ($columns AS $column) {
1181 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
1183 $stmt = DBA::p($sql);
1185 if (is_bool($stmt)) {
1188 $retval = (DBA::numRows($stmt) > 0);
1202 * Check if a foreign key exists for the given table field
1204 * @param string $table
1205 * @param string $field
1208 public static function existsForeignKeyForField(string $table, string $field)
1210 return DBA::exists(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
1211 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
1212 DBA::databaseName(), $table, $field]);
1215 * Check if a table exists
1217 * @param string|array $table Table name
1219 * @return boolean Does the table exist?
1222 public static function existsTable($table)
1224 if (empty($table)) {
1228 if (is_array($table)) {
1229 $condition = ['table_schema' => key($table), 'table_name' => current($table)];
1231 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
1234 $result = DBA::exists(['information_schema' => 'tables'], $condition);
1240 * Returns the columns of a table
1242 * @param string $table Table name
1244 * @return array An array of the table columns
1247 public static function getColumns($table)
1249 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
1250 return DBA::toArray($stmtColumns);
1254 * Check if initial database values do exist - or create them
1256 public static function checkInitialValues(bool $verbose = false)
1258 if (self::existsTable('verb')) {
1259 if (!DBA::exists('verb', ['id' => 1])) {
1260 foreach (Item::ACTIVITIES as $index => $activity) {
1261 DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], Database::INSERT_IGNORE);
1264 echo "verb: activities added\n";
1266 } elseif ($verbose) {
1267 echo "verb: activities already added\n";
1270 if (!DBA::exists('verb', ['id' => 0])) {
1271 DBA::insert('verb', ['name' => '']);
1272 $lastid = DBA::lastInsertId();
1274 DBA::update('verb', ['id' => 0], ['id' => $lastid]);
1276 echo "Zero verb added\n";
1279 } elseif ($verbose) {
1280 echo "Zero verb already added\n";
1282 } elseif ($verbose) {
1283 echo "verb: Table not found\n";
1286 if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) {
1289 "page-flags" => User::PAGE_FLAGS_SOAPBOX,
1290 "account-type" => User::ACCOUNT_TYPE_RELAY,
1292 DBA::insert('user', $user);
1293 $lastid = DBA::lastInsertId();
1295 DBA::update('user', ['uid' => 0], ['uid' => $lastid]);
1297 echo "Zero user added\n";
1300 } elseif (self::existsTable('user') && $verbose) {
1301 echo "Zero user already added\n";
1302 } elseif ($verbose) {
1303 echo "user: Table not found\n";
1306 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
1307 DBA::insert('contact', ['nurl' => '']);
1308 $lastid = DBA::lastInsertId();
1310 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
1312 echo "Zero contact added\n";
1315 } elseif (self::existsTable('contact') && $verbose) {
1316 echo "Zero contact already added\n";
1317 } elseif ($verbose) {
1318 echo "contact: Table not found\n";
1321 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
1322 DBA::insert('tag', ['name' => '']);
1323 $lastid = DBA::lastInsertId();
1325 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
1327 echo "Zero tag added\n";
1330 } elseif (self::existsTable('tag') && $verbose) {
1331 echo "Zero tag already added\n";
1332 } elseif ($verbose) {
1333 echo "tag: Table not found\n";
1336 if (self::existsTable('permissionset')) {
1337 if (!DBA::exists('permissionset', ['id' => 0])) {
1338 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
1339 $lastid = DBA::lastInsertId();
1341 DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
1343 echo "Zero permissionset added\n";
1346 } elseif ($verbose) {
1347 echo "Zero permissionset already added\n";
1349 if (self::existsTable('item') && !self::existsForeignKeyForField('item', 'psid')) {
1350 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
1351 LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
1352 WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
1353 while ($set = DBA::fetch($sets)) {
1354 if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
1355 $owner = User::getOwnerDataById($set['uid']);
1357 $permission = '<' . $owner['id'] . '>';
1364 $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
1365 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
1366 DBA::insert('permissionset', $fields);
1370 } elseif ($verbose) {
1371 echo "permissionset: Table not found\n";
1374 if (!self::existsForeignKeyForField('tokens', 'client_id')) {
1375 $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
1376 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
1377 WHERE `clients`.`client_id` IS NULL");
1378 while ($token = DBA::fetch($tokens)) {
1379 DBA::delete('tokens', ['id' => $token['id']]);
1381 DBA::close($tokens);
1386 * Checks if a database update is currently running
1390 private static function isUpdating()
1394 $processes = DBA::select(['information_schema' => 'processlist'], ['info'],
1395 ['db' => DBA::databaseName(), 'command' => ['Query', 'Execute']]);
1397 while ($process = DBA::fetch($processes)) {
1398 $parts = explode(' ', $process['info']);
1399 if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
1404 DBA::close($processes);