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 // When the field structure changes then we will not perform the special index handling for MySQL.
681 $sql2 = self::modifyTableField($fieldname, $parameters);
683 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
685 $sql3 .= ", " . $sql2;
693 * Create the index if the index don't exists in database
694 * or the definition differ from the current status.
695 * Don't create keys if table is new
697 if (!$is_new_table) {
698 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
699 if (isset($database[$name]["indexes"][$indexname])) {
700 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
702 $current_index_definition = "__NOT_SET__";
704 $new_index_definition = implode(",", $fieldnames);
705 if ($current_index_definition != $new_index_definition) {
706 $sql2 = self::createIndex($indexname, $fieldnames);
708 // Fetch the "group by" fields for unique indexes
709 $group_by = self::groupBy($fieldnames);
712 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
714 $sql3 .= ", " . $sql2;
720 $existing_foreign_keys = $database[$name]['foreign_keys'];
723 // Compare the field structure field by field
724 foreach ($structure["fields"] AS $fieldname => $parameters) {
725 if (empty($parameters['foreign'])) {
729 $constraint = self::getConstraintName($name, $fieldname, $parameters);
731 unset($existing_foreign_keys[$constraint]);
733 if (empty($database[$name]['foreign_keys'][$constraint])) {
734 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
737 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
739 $sql3 .= ", " . $sql2;
744 foreach ($existing_foreign_keys as $param) {
745 $sql2 = self::dropForeignKey($param['CONSTRAINT_NAME']);
748 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
750 $sql3 .= ", " . $sql2;
754 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
755 $structurecomment = $structure["comment"] ?? '';
756 if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
757 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
760 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
762 $sql3 .= ", " . $sql2;
767 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
768 if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
769 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
772 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
774 $sql3 .= ", " . $sql2;
779 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
780 if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
781 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
784 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
786 $sql3 .= ", " . $sql2;
795 // Now have a look at the field collations
796 // Compare the field structure field by field
797 foreach ($structure["fields"] AS $fieldname => $parameters) {
798 // Compare the field definition
799 $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
801 // Define the default collation if not given
802 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
803 $parameters['Collation'] = 'utf8mb4_general_ci';
805 $parameters['Collation'] = null;
808 if ($field_definition['Collation'] != $parameters['Collation']) {
809 $sql2 = self::modifyTableField($fieldname, $parameters);
810 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
811 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
813 $sql3 .= ", " . $sql2;
820 if (substr($sql3, -2, 2) != "; ") {
825 if ($is_unique && $ignore == '') {
826 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
827 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
829 $field_list = rtrim($field_list, ',');
833 // Ensure index conversion to unique removes duplicates
834 if ($is_unique && ($temp_name != $name)) {
836 echo "SET session old_alter_table=1;\n";
838 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
839 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
845 if ($is_unique && ($temp_name != $name)) {
847 echo "SET session old_alter_table=0;\n";
849 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
850 echo "DROP TABLE `" . $name . "`;\n";
851 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
857 if ($in_maintenance_mode) {
858 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
861 // Ensure index conversion to unique removes duplicates
862 if ($is_unique && ($temp_name != $name)) {
864 DBA::e("SET session old_alter_table=1;");
866 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
867 if (!DBA::isResult($r)) {
868 $errors .= self::printUpdateError($sql3);
872 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
873 if (!DBA::isResult($r)) {
874 $errors .= self::printUpdateError($sql3);
881 if (!DBA::isResult($r)) {
882 $errors .= self::printUpdateError($sql3);
884 if ($is_unique && ($temp_name != $name)) {
886 DBA::e("SET session old_alter_table=0;");
888 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
889 if (!DBA::isResult($r)) {
890 $errors .= self::printUpdateError($sql3);
893 $r = DBA::e("DROP TABLE `" . $name . "`;");
894 if (!DBA::isResult($r)) {
895 $errors .= self::printUpdateError($sql3);
898 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
899 if (!DBA::isResult($r)) {
900 $errors .= self::printUpdateError($sql3);
909 View::create(false, $action);
911 self::checkInitialValues();
913 if ($action && !$install) {
915 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
917 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
924 private static function tableStructure($table)
926 // This query doesn't seem to be executable as a prepared statement
927 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
929 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
930 ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
931 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
932 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
933 DBA::databaseName(), $table]);
935 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
936 ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
937 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
938 DBA::databaseName(), $table]);
940 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
941 ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
942 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
943 DBA::databaseName(), $table]);
949 if (DBA::isResult($foreign_keys)) {
950 foreach ($foreign_keys as $foreign_key) {
951 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
952 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
953 $foreigndata[$constraint] = $foreign_key;
957 if (DBA::isResult($indexes)) {
958 foreach ($indexes AS $index) {
959 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
960 $indexdata[$index["Key_name"]] = ["UNIQUE"];
963 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
964 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
967 $column = $index["Column_name"];
969 if ($index["Sub_part"] != "") {
970 $column .= "(" . $index["Sub_part"] . ")";
973 $indexdata[$index["Key_name"]][] = $column;
978 if (DBA::isResult($fields)) {
979 foreach ($fields AS $field) {
980 $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)'];
981 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
982 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
984 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
986 if ($field['IS_NULLABLE'] == 'NO') {
987 $fielddata[$field['COLUMN_NAME']]['not null'] = true;
990 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
991 $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
994 if (!empty($field['EXTRA'])) {
995 $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
998 if ($field['COLUMN_KEY'] == 'PRI') {
999 $fielddata[$field['COLUMN_NAME']]['primary'] = true;
1002 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
1003 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
1007 return ["fields" => $fielddata, "indexes" => $indexdata,
1008 "foreign_keys" => $foreigndata, "table_status" => $table_status];
1011 private static function dropIndex($indexname)
1013 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
1017 private static function addTableField($fieldname, $parameters)
1019 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
1023 private static function modifyTableField($fieldname, $parameters)
1025 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
1029 private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
1031 $foreign_table = array_keys($parameters['foreign'])[0];
1032 $foreign_field = array_values($parameters['foreign'])[0];
1034 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
1037 private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
1038 $foreign_table = array_keys($parameters['foreign'])[0];
1039 $foreign_field = array_values($parameters['foreign'])[0];
1041 $sql = "FOREIGN KEY (`" . $fieldname . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
1043 if (!empty($parameters['foreign']['on update'])) {
1044 $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
1046 $sql .= " ON UPDATE RESTRICT";
1049 if (!empty($parameters['foreign']['on delete'])) {
1050 $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
1052 $sql .= " ON DELETE CASCADE";
1058 private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
1060 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
1063 private static function dropForeignKey(string $constraint)
1065 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
1069 * Constructs a GROUP BY clause from a UNIQUE index definition.
1071 * @param array $fieldnames
1074 private static function groupBy(array $fieldnames)
1076 if ($fieldnames[0] != "UNIQUE") {
1080 array_shift($fieldnames);
1083 foreach ($fieldnames AS $fieldname) {
1088 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
1089 $names .= "`" . DBA::escape($matches[1]) . "`";
1091 $names .= "`" . DBA::escape($fieldname) . "`";
1095 $sql = sprintf(" GROUP BY %s", $names);
1100 * Renames columns or the primary key of a table
1102 * @todo You cannot rename a primary key if "auto increment" is set
1104 * @param string $table Table name
1105 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
1106 * Syntax for Primary Key: [ $col1, $col2, ...]
1107 * @param int $type The type of renaming (Default is Column)
1109 * @return boolean Was the renaming successful?
1112 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
1114 if (empty($table) || empty($columns)) {
1118 if (!is_array($columns)) {
1122 $table = DBA::escape($table);
1124 $sql = "ALTER TABLE `" . $table . "`";
1126 case self::RENAME_COLUMN:
1127 if (!self::existsColumn($table, array_keys($columns))) {
1130 $sql .= implode(',', array_map(
1131 function ($to, $from) {
1132 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
1135 array_keys($columns)
1138 case self::RENAME_PRIMARY_KEY:
1139 if (!self::existsColumn($table, $columns)) {
1142 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
1150 $stmt = DBA::p($sql);
1152 if (is_bool($stmt)) {
1164 * Check if the columns of the table exists
1166 * @param string $table Table name
1167 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
1169 * @return boolean Does the table exist?
1172 public static function existsColumn($table, $columns = [])
1174 if (empty($table)) {
1178 if (is_null($columns) || empty($columns)) {
1179 return self::existsTable($table);
1182 $table = DBA::escape($table);
1184 foreach ($columns AS $column) {
1185 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
1187 $stmt = DBA::p($sql);
1189 if (is_bool($stmt)) {
1192 $retval = (DBA::numRows($stmt) > 0);
1206 * Check if a foreign key exists for the given table field
1208 * @param string $table
1209 * @param string $field
1212 public static function existsForeignKeyForField(string $table, string $field)
1214 return DBA::exists(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
1215 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
1216 DBA::databaseName(), $table, $field]);
1219 * Check if a table exists
1221 * @param string|array $table Table name
1223 * @return boolean Does the table exist?
1226 public static function existsTable($table)
1228 if (empty($table)) {
1232 if (is_array($table)) {
1233 $condition = ['table_schema' => key($table), 'table_name' => current($table)];
1235 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
1238 $result = DBA::exists(['information_schema' => 'tables'], $condition);
1244 * Returns the columns of a table
1246 * @param string $table Table name
1248 * @return array An array of the table columns
1251 public static function getColumns($table)
1253 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
1254 return DBA::toArray($stmtColumns);
1258 * Check if initial database values do exist - or create them
1260 public static function checkInitialValues(bool $verbose = false)
1262 if (self::existsTable('verb')) {
1263 if (!DBA::exists('verb', ['id' => 1])) {
1264 foreach (Item::ACTIVITIES as $index => $activity) {
1265 DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], Database::INSERT_IGNORE);
1268 echo "verb: activities added\n";
1270 } elseif ($verbose) {
1271 echo "verb: activities already added\n";
1274 if (!DBA::exists('verb', ['id' => 0])) {
1275 DBA::insert('verb', ['name' => '']);
1276 $lastid = DBA::lastInsertId();
1278 DBA::update('verb', ['id' => 0], ['id' => $lastid]);
1280 echo "Zero verb added\n";
1283 } elseif ($verbose) {
1284 echo "Zero verb already added\n";
1286 } elseif ($verbose) {
1287 echo "verb: Table not found\n";
1290 if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) {
1293 "page-flags" => User::PAGE_FLAGS_SOAPBOX,
1294 "account-type" => User::ACCOUNT_TYPE_RELAY,
1296 DBA::insert('user', $user);
1297 $lastid = DBA::lastInsertId();
1299 DBA::update('user', ['uid' => 0], ['uid' => $lastid]);
1301 echo "Zero user added\n";
1304 } elseif (self::existsTable('user') && $verbose) {
1305 echo "Zero user already added\n";
1306 } elseif ($verbose) {
1307 echo "user: Table not found\n";
1310 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
1311 DBA::insert('contact', ['nurl' => '']);
1312 $lastid = DBA::lastInsertId();
1314 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
1316 echo "Zero contact added\n";
1319 } elseif (self::existsTable('contact') && $verbose) {
1320 echo "Zero contact already added\n";
1321 } elseif ($verbose) {
1322 echo "contact: Table not found\n";
1325 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
1326 DBA::insert('tag', ['name' => '']);
1327 $lastid = DBA::lastInsertId();
1329 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
1331 echo "Zero tag added\n";
1334 } elseif (self::existsTable('tag') && $verbose) {
1335 echo "Zero tag already added\n";
1336 } elseif ($verbose) {
1337 echo "tag: Table not found\n";
1340 if (self::existsTable('permissionset')) {
1341 if (!DBA::exists('permissionset', ['id' => 0])) {
1342 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
1343 $lastid = DBA::lastInsertId();
1345 DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
1347 echo "Zero permissionset added\n";
1350 } elseif ($verbose) {
1351 echo "Zero permissionset already added\n";
1353 if (self::existsTable('item') && !self::existsForeignKeyForField('item', 'psid')) {
1354 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
1355 LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
1356 WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
1357 while ($set = DBA::fetch($sets)) {
1358 if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
1359 $owner = User::getOwnerDataById($set['uid']);
1361 $permission = '<' . $owner['id'] . '>';
1368 $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
1369 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
1370 DBA::insert('permissionset', $fields);
1374 } elseif ($verbose) {
1375 echo "permissionset: Table not found\n";
1378 if (self::existsTable('tokens') && self::existsTable('clients') && !self::existsForeignKeyForField('tokens', 'client_id')) {
1379 $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
1380 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
1381 WHERE `clients`.`client_id` IS NULL");
1382 while ($token = DBA::fetch($tokens)) {
1383 DBA::delete('tokens', ['id' => $token['id']]);
1385 DBA::close($tokens);
1390 * Checks if a database update is currently running
1394 private static function isUpdating()
1398 $processes = DBA::select(['information_schema' => 'processlist'], ['info'],
1399 ['db' => DBA::databaseName(), 'command' => ['Query', 'Execute']]);
1401 while ($process = DBA::fetch($processes)) {
1402 $parts = explode(' ', $process['info']);
1403 if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
1408 DBA::close($processes);