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) {
170 foreach ($definition['indexes'] as $key => $value) {
171 $indexes[] = ['name' => $key, 'fields' => implode(', ', $value)];
177 'comment' => 'Description',
181 'default' => 'Default',
202 foreach ($definition['fields'] as $key => $value) {
204 $field['name'] = $key;
205 $field['comment'] = $value['comment'] ?? '';
206 $field['type'] = $value['type'];
207 $field['null'] = ($value['not null'] ?? false) ? 'NO' : 'YES';
208 $field['primary'] = ($value['primary'] ?? false) ? 'PRI' : '';
209 $field['default'] = $value['default'] ?? 'NULL';
210 $field['extra'] = $value['extra'] ?? '';
212 foreach ($field as $fieldname => $fieldvalue) {
213 $lengths[$fieldname] = max($lengths[$fieldname] ?? 0, strlen($fieldvalue));
217 if (!empty($value['foreign'])) {
220 'targettable' => array_keys($value['foreign'])[0],
221 'targetfield' => array_values($value['foreign'])[0]
226 array_walk_recursive($fields, function(&$value, $key) use ($lengths)
228 $value = str_pad($value, $lengths[$key], $value === '-' ? '-' : ' ');
231 $tables[] = ['name' => $name, 'comment' => $definition['comment']];
232 $content = Renderer::replaceMacros(Renderer::getMarkupTemplate('structure.tpl'), [
234 '$comment' => $definition['comment'],
235 '$fields' => $fields,
236 '$indexes' => $indexes,
237 '$foreign' => $foreign,
239 $filename = DI::basePath() . '/doc/database/db_' . $name . '.md';
240 file_put_contents($filename, $content);
243 $content = Renderer::replaceMacros(Renderer::getMarkupTemplate('tables.tpl'), [
244 '$tables' => $tables,
246 $filename = DI::basePath() . '/doc/database.md';
247 file_put_contents($filename, $content);
250 public static function printStructure($basePath)
252 $database = self::definition($basePath, false);
254 echo "-- ------------------------------------------\n";
255 echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n";
256 echo "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
257 echo "-- ------------------------------------------\n\n\n";
258 foreach ($database AS $name => $structure) {
260 echo "-- TABLE $name\n";
262 self::createTable($name, $structure, true, false);
267 View::printStructure($basePath);
271 * Loads the database structure definition from the static/dbstructure.config.php file.
272 * On first pass, defines DB_UPDATE_VERSION constant.
274 * @see static/dbstructure.config.php
275 * @param boolean $with_addons_structure Whether to tack on addons additional tables
276 * @param string $basePath The base path of this application
280 public static function definition($basePath, $with_addons_structure = true)
282 if (!self::$definition) {
283 if (empty($basePath)) {
284 $basePath = DI::app()->getBasePath();
287 $filename = $basePath . '/static/dbstructure.config.php';
289 if (!is_readable($filename)) {
290 throw new Exception('Missing database structure config file static/dbstructure.config.php');
293 $definition = require $filename;
296 throw new Exception('Corrupted database structure config file static/dbstructure.config.php');
299 self::$definition = $definition;
301 $definition = self::$definition;
304 if ($with_addons_structure) {
305 Hook::callAll('dbstructure_definition', $definition);
312 * Get field data for the given table
314 * @param string $table
315 * @param array $data data fields
316 * @return array fields for the given
318 public static function getFieldsForTable(string $table, array $data = [])
320 $definition = DBStructure::definition('', false);
321 if (empty($definition[$table])) {
325 $fieldnames = array_keys($definition[$table]['fields']);
329 // Assign all field that are present in the table
330 foreach ($fieldnames as $field) {
331 if (isset($data[$field])) {
332 // Limit the length of varchar, varbinary, char and binrary fields
333 if (is_string($data[$field]) && preg_match("/char\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
334 $data[$field] = mb_substr($data[$field], 0, $result[1]);
335 } elseif (is_string($data[$field]) && preg_match("/binary\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
336 $data[$field] = substr($data[$field], 0, $result[1]);
338 $fields[$field] = $data[$field];
345 private static function createTable($name, $structure, $verbose, $action)
355 foreach ($structure["fields"] AS $fieldname => $field) {
356 $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
357 if (!empty($field['primary'])) {
358 $primary_keys[] = $fieldname;
360 if (!empty($field['foreign'])) {
361 $foreign_keys[$fieldname] = $field;
365 if (!empty($structure["indexes"])) {
366 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
367 $sql_index = self::createIndex($indexname, $fieldnames, "");
368 if (!is_null($sql_index)) {
369 $sql_rows[] = $sql_index;
374 foreach ($foreign_keys AS $fieldname => $parameters) {
375 $sql_rows[] = self::foreignCommand($name, $fieldname, $parameters);
378 if (isset($structure["engine"])) {
379 $engine = " ENGINE=" . $structure["engine"];
382 if (isset($structure["comment"])) {
383 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
386 $sql = implode(",\n\t", $sql_rows);
388 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
389 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
401 private static function FieldCommand($parameters, $create = true)
403 $fieldstruct = $parameters["type"];
405 if (isset($parameters["Collation"])) {
406 $fieldstruct .= " COLLATE " . $parameters["Collation"];
409 if (isset($parameters["not null"])) {
410 $fieldstruct .= " NOT NULL";
413 if (isset($parameters["default"])) {
414 if (strpos(strtolower($parameters["type"]), "int") !== false) {
415 $fieldstruct .= " DEFAULT " . $parameters["default"];
417 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
420 if (isset($parameters["extra"])) {
421 $fieldstruct .= " " . $parameters["extra"];
424 if (isset($parameters["comment"])) {
425 $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
428 /*if (($parameters["primary"] != "") && $create)
429 $fieldstruct .= " PRIMARY KEY";*/
431 return ($fieldstruct);
434 private static function createIndex($indexname, $fieldnames, $method = "ADD")
436 $method = strtoupper(trim($method));
437 if ($method != "" && $method != "ADD") {
438 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
441 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
442 $index_type = array_shift($fieldnames);
443 $method .= " " . $index_type;
447 foreach ($fieldnames AS $fieldname) {
452 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
453 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
455 $names .= "`" . DBA::escape($fieldname) . "`";
459 if ($indexname == "PRIMARY") {
460 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
464 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
469 * Perform a database structure dryrun (means: just simulating)
473 public static function dryRun()
475 self::update(DI::app()->getBasePath(), true, false);
479 * Updates DB structure and returns eventual errors messages
481 * @param bool $enable_maintenance_mode Set the maintenance mode
482 * @param bool $verbose Display the SQL commands
484 * @return string Empty string if the update is successful, error messages otherwise
487 public static function performUpdate(bool $enable_maintenance_mode = true, bool $verbose = false)
489 if ($enable_maintenance_mode) {
490 DI::config()->set('system', 'maintenance', 1);
493 $status = self::update(DI::app()->getBasePath(), $verbose, true);
495 if ($enable_maintenance_mode) {
496 DI::config()->set('system', 'maintenance', 0);
497 DI::config()->set('system', 'maintenance_reason', '');
504 * Updates DB structure from the installation and returns eventual errors messages
506 * @param string $basePath The base path of this application
508 * @return string Empty string if the update is successful, error messages otherwise
511 public static function install(string $basePath)
513 return self::update($basePath, false, true, true);
517 * Updates DB structure and returns eventual errors messages
519 * @param string $basePath The base path of this application
520 * @param bool $verbose
521 * @param bool $action Whether to actually apply the update
522 * @param bool $install Is this the initial update during the installation?
523 * @param array $tables An array of the database tables
524 * @param array $definition An array of the definition tables
525 * @return string Empty string if the update is successful, error messages otherwise
528 private static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
530 $in_maintenance_mode = DI::config()->get('system', 'maintenance');
532 if ($action && !$install && self::isUpdating()) {
533 return DI::l10n()->t('Another database update is currently running.');
536 if ($in_maintenance_mode) {
537 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
540 // ensure that all initial values exist. This test has to be done prior and after the structure check.
541 // Prior is needed if the specific tables already exists - after is needed when they had been created.
542 self::checkInitialValues();
546 Logger::info('updating structure');
548 // Get the current structure
551 if (is_null($tables)) {
552 $tables = DBA::toArray(DBA::p("SHOW TABLES"));
555 if (DBA::isResult($tables)) {
556 foreach ($tables AS $table) {
557 $table = current($table);
559 Logger::info('updating structure', ['table' => $table]);
560 $database[$table] = self::tableStructure($table);
564 // Get the definition
565 if (is_null($definition)) {
566 $definition = self::definition($basePath);
569 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
570 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
571 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
578 foreach ($definition AS $name => $structure) {
579 $is_new_table = false;
584 if (!isset($database[$name])) {
585 $r = self::createTable($name, $structure, $verbose, $action);
586 if (!DBA::isResult($r)) {
587 $errors .= self::printUpdateError($name);
589 $is_new_table = true;
591 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
592 if (isset($database[$name]["indexes"][$indexname])) {
593 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
595 $current_index_definition = "__NOT_SET__";
597 $new_index_definition = implode(",", $fieldnames);
598 if ($current_index_definition != $new_index_definition) {
599 if ($fieldnames[0] == "UNIQUE") {
602 $temp_name = "temp-" . $name;
609 * Drop the index if it isn't present in the definition
610 * or the definition differ from current status
611 * and index name doesn't start with "local_"
613 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
614 $current_index_definition = implode(",", $fieldnames);
615 if (isset($structure["indexes"][$indexname])) {
616 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
618 $new_index_definition = "__NOT_SET__";
620 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
621 $sql2 = self::dropIndex($indexname);
623 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
625 $sql3 .= ", " . $sql2;
629 // Compare the field structure field by field
630 foreach ($structure["fields"] AS $fieldname => $parameters) {
631 if (!isset($database[$name]["fields"][$fieldname])) {
632 $sql2 = self::addTableField($fieldname, $parameters);
634 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
636 $sql3 .= ", " . $sql2;
639 // Compare the field definition
640 $field_definition = $database[$name]["fields"][$fieldname];
642 // Remove the relation data that is used for the referential integrity
643 unset($parameters['relation']);
644 unset($parameters['foreign']);
646 // We change the collation after the indexes had been changed.
647 // This is done to avoid index length problems.
648 // So here we always ensure that there is no need to change it.
649 unset($parameters['Collation']);
650 unset($field_definition['Collation']);
652 // Only update the comment when it is defined
653 if (!isset($parameters['comment'])) {
654 $parameters['comment'] = "";
657 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
658 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
659 if ($current_field_definition != $new_field_definition) {
660 $sql2 = self::modifyTableField($fieldname, $parameters);
662 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
664 $sql3 .= ", " . $sql2;
672 * Create the index if the index don't exists in database
673 * or the definition differ from the current status.
674 * Don't create keys if table is new
676 if (!$is_new_table) {
677 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
678 if (isset($database[$name]["indexes"][$indexname])) {
679 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
681 $current_index_definition = "__NOT_SET__";
683 $new_index_definition = implode(",", $fieldnames);
684 if ($current_index_definition != $new_index_definition) {
685 $sql2 = self::createIndex($indexname, $fieldnames);
687 // Fetch the "group by" fields for unique indexes
688 $group_by = self::groupBy($fieldnames);
691 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
693 $sql3 .= ", " . $sql2;
699 $existing_foreign_keys = $database[$name]['foreign_keys'];
702 // Compare the field structure field by field
703 foreach ($structure["fields"] AS $fieldname => $parameters) {
704 if (empty($parameters['foreign'])) {
708 $constraint = self::getConstraintName($name, $fieldname, $parameters);
710 unset($existing_foreign_keys[$constraint]);
712 if (empty($database[$name]['foreign_keys'][$constraint])) {
713 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
716 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
718 $sql3 .= ", " . $sql2;
723 foreach ($existing_foreign_keys as $param) {
724 $sql2 = self::dropForeignKey($param['CONSTRAINT_NAME']);
727 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
729 $sql3 .= ", " . $sql2;
733 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
734 $structurecomment = $structure["comment"] ?? '';
735 if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
736 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
739 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
741 $sql3 .= ", " . $sql2;
746 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
747 if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
748 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
751 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
753 $sql3 .= ", " . $sql2;
758 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
759 if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
760 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
763 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
765 $sql3 .= ", " . $sql2;
774 // Now have a look at the field collations
775 // Compare the field structure field by field
776 foreach ($structure["fields"] AS $fieldname => $parameters) {
777 // Compare the field definition
778 $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
780 // Define the default collation if not given
781 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
782 $parameters['Collation'] = 'utf8mb4_general_ci';
784 $parameters['Collation'] = null;
787 if ($field_definition['Collation'] != $parameters['Collation']) {
788 $sql2 = self::modifyTableField($fieldname, $parameters);
789 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
790 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
792 $sql3 .= ", " . $sql2;
799 if (substr($sql3, -2, 2) != "; ") {
804 if ($is_unique && $ignore == '') {
805 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
806 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
808 $field_list = rtrim($field_list, ',');
812 // Ensure index conversion to unique removes duplicates
813 if ($is_unique && ($temp_name != $name)) {
815 echo "SET session old_alter_table=1;\n";
817 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
818 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
824 if ($is_unique && ($temp_name != $name)) {
826 echo "SET session old_alter_table=0;\n";
828 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
829 echo "DROP TABLE `" . $name . "`;\n";
830 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
836 if ($in_maintenance_mode) {
837 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
840 // Ensure index conversion to unique removes duplicates
841 if ($is_unique && ($temp_name != $name)) {
843 DBA::e("SET session old_alter_table=1;");
845 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
846 if (!DBA::isResult($r)) {
847 $errors .= self::printUpdateError($sql3);
851 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
852 if (!DBA::isResult($r)) {
853 $errors .= self::printUpdateError($sql3);
860 if (!DBA::isResult($r)) {
861 $errors .= self::printUpdateError($sql3);
863 if ($is_unique && ($temp_name != $name)) {
865 DBA::e("SET session old_alter_table=0;");
867 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
868 if (!DBA::isResult($r)) {
869 $errors .= self::printUpdateError($sql3);
872 $r = DBA::e("DROP TABLE `" . $name . "`;");
873 if (!DBA::isResult($r)) {
874 $errors .= self::printUpdateError($sql3);
877 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
878 if (!DBA::isResult($r)) {
879 $errors .= self::printUpdateError($sql3);
888 View::create(false, $action);
890 self::checkInitialValues();
892 if ($action && !$install) {
894 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
896 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
903 private static function tableStructure($table)
905 // This query doesn't seem to be executable as a prepared statement
906 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
908 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
909 ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
910 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
911 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
912 DBA::databaseName(), $table]);
914 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
915 ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
916 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
917 DBA::databaseName(), $table]);
919 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
920 ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
921 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
922 DBA::databaseName(), $table]);
928 if (DBA::isResult($foreign_keys)) {
929 foreach ($foreign_keys as $foreign_key) {
930 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
931 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
932 $foreigndata[$constraint] = $foreign_key;
936 if (DBA::isResult($indexes)) {
937 foreach ($indexes AS $index) {
938 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
939 $indexdata[$index["Key_name"]] = ["UNIQUE"];
942 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
943 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
946 $column = $index["Column_name"];
948 if ($index["Sub_part"] != "") {
949 $column .= "(" . $index["Sub_part"] . ")";
952 $indexdata[$index["Key_name"]][] = $column;
957 if (DBA::isResult($fields)) {
958 foreach ($fields AS $field) {
959 $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)'];
960 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
961 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
963 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
965 if ($field['IS_NULLABLE'] == 'NO') {
966 $fielddata[$field['COLUMN_NAME']]['not null'] = true;
969 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
970 $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
973 if (!empty($field['EXTRA'])) {
974 $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
977 if ($field['COLUMN_KEY'] == 'PRI') {
978 $fielddata[$field['COLUMN_NAME']]['primary'] = true;
981 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
982 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
986 return ["fields" => $fielddata, "indexes" => $indexdata,
987 "foreign_keys" => $foreigndata, "table_status" => $table_status];
990 private static function dropIndex($indexname)
992 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
996 private static function addTableField($fieldname, $parameters)
998 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
1002 private static function modifyTableField($fieldname, $parameters)
1004 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
1008 private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
1010 $foreign_table = array_keys($parameters['foreign'])[0];
1011 $foreign_field = array_values($parameters['foreign'])[0];
1013 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
1016 private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
1017 $foreign_table = array_keys($parameters['foreign'])[0];
1018 $foreign_field = array_values($parameters['foreign'])[0];
1020 $sql = "FOREIGN KEY (`" . $fieldname . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
1022 if (!empty($parameters['foreign']['on update'])) {
1023 $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
1025 $sql .= " ON UPDATE RESTRICT";
1028 if (!empty($parameters['foreign']['on delete'])) {
1029 $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
1031 $sql .= " ON DELETE CASCADE";
1037 private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
1039 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
1042 private static function dropForeignKey(string $constraint)
1044 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
1048 * Constructs a GROUP BY clause from a UNIQUE index definition.
1050 * @param array $fieldnames
1053 private static function groupBy(array $fieldnames)
1055 if ($fieldnames[0] != "UNIQUE") {
1059 array_shift($fieldnames);
1062 foreach ($fieldnames AS $fieldname) {
1067 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
1068 $names .= "`" . DBA::escape($matches[1]) . "`";
1070 $names .= "`" . DBA::escape($fieldname) . "`";
1074 $sql = sprintf(" GROUP BY %s", $names);
1079 * Renames columns or the primary key of a table
1081 * @todo You cannot rename a primary key if "auto increment" is set
1083 * @param string $table Table name
1084 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
1085 * Syntax for Primary Key: [ $col1, $col2, ...]
1086 * @param int $type The type of renaming (Default is Column)
1088 * @return boolean Was the renaming successful?
1091 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
1093 if (empty($table) || empty($columns)) {
1097 if (!is_array($columns)) {
1101 $table = DBA::escape($table);
1103 $sql = "ALTER TABLE `" . $table . "`";
1105 case self::RENAME_COLUMN:
1106 if (!self::existsColumn($table, array_keys($columns))) {
1109 $sql .= implode(',', array_map(
1110 function ($to, $from) {
1111 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
1114 array_keys($columns)
1117 case self::RENAME_PRIMARY_KEY:
1118 if (!self::existsColumn($table, $columns)) {
1121 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
1129 $stmt = DBA::p($sql);
1131 if (is_bool($stmt)) {
1143 * Check if the columns of the table exists
1145 * @param string $table Table name
1146 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
1148 * @return boolean Does the table exist?
1151 public static function existsColumn($table, $columns = [])
1153 if (empty($table)) {
1157 if (is_null($columns) || empty($columns)) {
1158 return self::existsTable($table);
1161 $table = DBA::escape($table);
1163 foreach ($columns AS $column) {
1164 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
1166 $stmt = DBA::p($sql);
1168 if (is_bool($stmt)) {
1171 $retval = (DBA::numRows($stmt) > 0);
1185 * Check if a foreign key exists for the given table field
1187 * @param string $table
1188 * @param string $field
1191 public static function existsForeignKeyForField(string $table, string $field)
1193 return DBA::exists(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
1194 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
1195 DBA::databaseName(), $table, $field]);
1198 * Check if a table exists
1200 * @param string|array $table Table name
1202 * @return boolean Does the table exist?
1205 public static function existsTable($table)
1207 if (empty($table)) {
1211 if (is_array($table)) {
1212 $condition = ['table_schema' => key($table), 'table_name' => current($table)];
1214 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
1217 $result = DBA::exists(['information_schema' => 'tables'], $condition);
1223 * Returns the columns of a table
1225 * @param string $table Table name
1227 * @return array An array of the table columns
1230 public static function getColumns($table)
1232 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
1233 return DBA::toArray($stmtColumns);
1237 * Check if initial database values do exist - or create them
1239 public static function checkInitialValues(bool $verbose = false)
1241 if (self::existsTable('verb')) {
1242 if (!DBA::exists('verb', ['id' => 1])) {
1243 foreach (Item::ACTIVITIES as $index => $activity) {
1244 DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], Database::INSERT_IGNORE);
1247 echo "verb: activities added\n";
1249 } elseif ($verbose) {
1250 echo "verb: activities already added\n";
1253 if (!DBA::exists('verb', ['id' => 0])) {
1254 DBA::insert('verb', ['name' => '']);
1255 $lastid = DBA::lastInsertId();
1257 DBA::update('verb', ['id' => 0], ['id' => $lastid]);
1259 echo "Zero verb added\n";
1262 } elseif ($verbose) {
1263 echo "Zero verb already added\n";
1265 } elseif ($verbose) {
1266 echo "verb: Table not found\n";
1269 if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) {
1272 "page-flags" => User::PAGE_FLAGS_SOAPBOX,
1273 "account-type" => User::ACCOUNT_TYPE_RELAY,
1275 DBA::insert('user', $user);
1276 $lastid = DBA::lastInsertId();
1278 DBA::update('user', ['uid' => 0], ['uid' => $lastid]);
1280 echo "Zero user added\n";
1283 } elseif (self::existsTable('user') && $verbose) {
1284 echo "Zero user already added\n";
1285 } elseif ($verbose) {
1286 echo "user: Table not found\n";
1289 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
1290 DBA::insert('contact', ['nurl' => '']);
1291 $lastid = DBA::lastInsertId();
1293 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
1295 echo "Zero contact added\n";
1298 } elseif (self::existsTable('contact') && $verbose) {
1299 echo "Zero contact already added\n";
1300 } elseif ($verbose) {
1301 echo "contact: Table not found\n";
1304 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
1305 DBA::insert('tag', ['name' => '']);
1306 $lastid = DBA::lastInsertId();
1308 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
1310 echo "Zero tag added\n";
1313 } elseif (self::existsTable('tag') && $verbose) {
1314 echo "Zero tag already added\n";
1315 } elseif ($verbose) {
1316 echo "tag: Table not found\n";
1319 if (self::existsTable('permissionset')) {
1320 if (!DBA::exists('permissionset', ['id' => 0])) {
1321 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
1322 $lastid = DBA::lastInsertId();
1324 DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
1326 echo "Zero permissionset added\n";
1329 } elseif ($verbose) {
1330 echo "Zero permissionset already added\n";
1332 if (self::existsTable('item') && !self::existsForeignKeyForField('item', 'psid')) {
1333 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
1334 LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
1335 WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
1336 while ($set = DBA::fetch($sets)) {
1337 if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
1338 $owner = User::getOwnerDataById($set['uid']);
1340 $permission = '<' . $owner['id'] . '>';
1347 $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
1348 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
1349 DBA::insert('permissionset', $fields);
1353 } elseif ($verbose) {
1354 echo "permissionset: Table not found\n";
1357 if (!self::existsForeignKeyForField('tokens', 'client_id')) {
1358 $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
1359 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
1360 WHERE `clients`.`client_id` IS NULL");
1361 while ($token = DBA::fetch($tokens)) {
1362 DBA::delete('tokens', ['id' => $token['id']]);
1364 DBA::close($tokens);
1369 * Checks if a database update is currently running
1373 private static function isUpdating()
1377 $processes = DBA::select(['information_schema' => 'processlist'], ['info'],
1378 ['db' => DBA::databaseName(), 'command' => ['Query', 'Execute']]);
1380 while ($process = DBA::fetch($processes)) {
1381 $parts = explode(' ', $process['info']);
1382 if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
1387 DBA::close($processes);