3 * @copyright Copyright (C) 2020, Friendica
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;
28 use Friendica\Model\Item;
29 use Friendica\Model\User;
30 use Friendica\Util\DateTimeFormat;
33 * This class contains functions that doesn't need to know if pdo, mysqli or whatever is used.
37 const UPDATE_NOT_CHECKED = 0; // Database check wasn't executed before
38 const UPDATE_SUCCESSFUL = 1; // Database check was successful
39 const UPDATE_FAILED = 2; // Database check failed
41 const RENAME_COLUMN = 0;
42 const RENAME_PRIMARY_KEY = 1;
45 * Database structure definition loaded from config/dbstructure.config.php
49 private static $definition = [];
52 * Set a database version to trigger update functions
54 * @param string $version
57 public static function setDatabaseVersion(string $version)
59 if (!is_numeric($version)) {
60 throw new \Asika\SimpleConsole\CommandArgsException('The version number must be numeric');
63 DI::config()->set('system', 'build', $version);
64 echo DI::l10n()->t('The database version had been set to %s.', $version);
70 * @param boolean $execute
73 public static function dropTables(bool $execute)
75 $postupdate = DI::config()->get("system", "post_update_version", PostUpdate::VERSION);
76 if ($postupdate < PostUpdate::VERSION) {
77 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);
81 $old_tables = ['fserver', 'gcign', 'gcontact', 'gcontact-relation', 'gfollower' ,'glink', 'item-delivery-data',
82 'item-activity', 'item-content', 'item_id', 'poll', 'poll_result', 'queue', 'retriever_rule', 'sign', 'spam', 'term'];
84 $tables = DBA::selectToArray(['INFORMATION_SCHEMA' => 'TABLES'], ['TABLE_NAME'],
85 ['TABLE_SCHEMA' => DBA::databaseName(), 'TABLE_TYPE' => 'BASE TABLE']);
88 echo DI::l10n()->t('No unused tables found.');
93 echo DI::l10n()->t('These tables are not used for friendica and will be deleted when you execute "dbstructure drop -e":') . "\n\n";
96 foreach ($tables as $table) {
97 if (in_array($table['TABLE_NAME'], $old_tables)) {
99 $sql = 'DROP TABLE ' . DBA::quoteIdentifier($table['TABLE_NAME']) . ';';
102 $result = DBA::e($sql);
103 if (!DBA::isResult($result)) {
104 self::printUpdateError($sql);
107 echo $table['TABLE_NAME'] . "\n";
114 * Converts all tables from MyISAM/InnoDB Antelope to InnoDB Barracuda
116 public static function convertToInnoDB()
118 $tables = DBA::selectToArray(
119 ['information_schema' => 'tables'],
121 ['engine' => 'MyISAM', 'table_schema' => DBA::databaseName()]
124 $tables = array_merge($tables, DBA::selectToArray(
125 ['information_schema' => 'tables'],
127 ['engine' => 'InnoDB', 'ROW_FORMAT' => ['COMPACT', 'REDUNDANT'], 'table_schema' => DBA::databaseName()]
130 if (!DBA::isResult($tables)) {
131 echo DI::l10n()->t('There are no tables on MyISAM or InnoDB with the Antelope file format.') . "\n";
135 foreach ($tables AS $table) {
136 $sql = "ALTER TABLE " . DBA::quoteIdentifier($table['table_name']) . " ENGINE=InnoDB ROW_FORMAT=DYNAMIC;";
139 $result = DBA::e($sql);
140 if (!DBA::isResult($result)) {
141 self::printUpdateError($sql);
147 * Print out database error messages
149 * @param string $message Message to be added to the error message
151 * @return string Error message
153 private static function printUpdateError($message)
155 echo DI::l10n()->t("\nError %d occurred during database update:\n%s\n",
156 DBA::errorNo(), DBA::errorMessage());
158 return DI::l10n()->t('Errors encountered performing database changes: ') . $message . EOL;
161 public static function printStructure($basePath)
163 $database = self::definition($basePath, false);
165 echo "-- ------------------------------------------\n";
166 echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n";
167 echo "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
168 echo "-- ------------------------------------------\n\n\n";
169 foreach ($database AS $name => $structure) {
171 echo "-- TABLE $name\n";
173 self::createTable($name, $structure, true, false);
178 View::printStructure($basePath);
182 * Loads the database structure definition from the static/dbstructure.config.php file.
183 * On first pass, defines DB_UPDATE_VERSION constant.
185 * @see static/dbstructure.config.php
186 * @param boolean $with_addons_structure Whether to tack on addons additional tables
187 * @param string $basePath The base path of this application
191 public static function definition($basePath, $with_addons_structure = true)
193 if (!self::$definition) {
195 $filename = $basePath . '/static/dbstructure.config.php';
197 if (!is_readable($filename)) {
198 throw new Exception('Missing database structure config file static/dbstructure.config.php');
201 $definition = require $filename;
204 throw new Exception('Corrupted database structure config file static/dbstructure.config.php');
207 self::$definition = $definition;
209 $definition = self::$definition;
212 if ($with_addons_structure) {
213 Hook::callAll('dbstructure_definition', $definition);
220 * Get field data for the given table
222 * @param string $table
223 * @param array $data data fields
224 * @return array fields for the given
226 public static function getFieldsForTable(string $table, array $data = [])
228 $definition = DBStructure::definition('', false);
229 if (empty($definition[$table])) {
233 $fieldnames = array_keys($definition[$table]['fields']);
237 // Assign all field that are present in the table
238 foreach ($fieldnames as $field) {
239 if (isset($data[$field])) {
240 $fields[$field] = $data[$field];
247 private static function createTable($name, $structure, $verbose, $action)
257 foreach ($structure["fields"] AS $fieldname => $field) {
258 $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
259 if (!empty($field['primary'])) {
260 $primary_keys[] = $fieldname;
262 if (!empty($field['foreign'])) {
263 $foreign_keys[$fieldname] = $field;
267 if (!empty($structure["indexes"])) {
268 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
269 $sql_index = self::createIndex($indexname, $fieldnames, "");
270 if (!is_null($sql_index)) {
271 $sql_rows[] = $sql_index;
276 foreach ($foreign_keys AS $fieldname => $parameters) {
277 $sql_rows[] = self::foreignCommand($name, $fieldname, $parameters);
280 if (isset($structure["engine"])) {
281 $engine = " ENGINE=" . $structure["engine"];
284 if (isset($structure["comment"])) {
285 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
288 $sql = implode(",\n\t", $sql_rows);
290 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
291 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
303 private static function FieldCommand($parameters, $create = true)
305 $fieldstruct = $parameters["type"];
307 if (isset($parameters["Collation"])) {
308 $fieldstruct .= " COLLATE " . $parameters["Collation"];
311 if (isset($parameters["not null"])) {
312 $fieldstruct .= " NOT NULL";
315 if (isset($parameters["default"])) {
316 if (strpos(strtolower($parameters["type"]), "int") !== false) {
317 $fieldstruct .= " DEFAULT " . $parameters["default"];
319 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
322 if (isset($parameters["extra"])) {
323 $fieldstruct .= " " . $parameters["extra"];
326 if (isset($parameters["comment"])) {
327 $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
330 /*if (($parameters["primary"] != "") && $create)
331 $fieldstruct .= " PRIMARY KEY";*/
333 return ($fieldstruct);
336 private static function createIndex($indexname, $fieldnames, $method = "ADD")
338 $method = strtoupper(trim($method));
339 if ($method != "" && $method != "ADD") {
340 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
343 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
344 $index_type = array_shift($fieldnames);
345 $method .= " " . $index_type;
349 foreach ($fieldnames AS $fieldname) {
354 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
355 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
357 $names .= "`" . DBA::escape($fieldname) . "`";
361 if ($indexname == "PRIMARY") {
362 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
366 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
371 * Perform a database structure dryrun (means: just simulating)
375 public static function dryRun()
377 self::update(DI::app()->getBasePath(), true, false);
381 * Updates DB structure and returns eventual errors messages
383 * @param bool $enable_maintenance_mode Set the maintenance mode
384 * @param bool $verbose Display the SQL commands
386 * @return string Empty string if the update is successful, error messages otherwise
389 public static function performUpdate(bool $enable_maintenance_mode = true, bool $verbose = false)
391 if ($enable_maintenance_mode) {
392 DI::config()->set('system', 'maintenance', 1);
395 $status = self::update(DI::app()->getBasePath(), $verbose, true);
397 if ($enable_maintenance_mode) {
398 DI::config()->set('system', 'maintenance', 0);
399 DI::config()->set('system', 'maintenance_reason', '');
406 * Updates DB structure from the installation and returns eventual errors messages
408 * @param string $basePath The base path of this application
410 * @return string Empty string if the update is successful, error messages otherwise
413 public static function install(string $basePath)
415 return self::update($basePath, false, true, true);
419 * Updates DB structure and returns eventual errors messages
421 * @param string $basePath The base path of this application
422 * @param bool $verbose
423 * @param bool $action Whether to actually apply the update
424 * @param bool $install Is this the initial update during the installation?
425 * @param array $tables An array of the database tables
426 * @param array $definition An array of the definition tables
427 * @return string Empty string if the update is successful, error messages otherwise
430 private static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
432 $in_maintenance_mode = DI::config()->get('system', 'maintenance');
434 if ($action && !$install && self::isUpdating()) {
435 return DI::l10n()->t('Another database update is currently running.');
438 if ($in_maintenance_mode) {
439 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
442 // ensure that all initial values exist. This test has to be done prior and after the structure check.
443 // Prior is needed if the specific tables already exists - after is needed when they had been created.
444 self::checkInitialValues();
448 Logger::info('updating structure');
450 // Get the current structure
453 if (is_null($tables)) {
454 $tables = DBA::toArray(DBA::p("SHOW TABLES"));
457 if (DBA::isResult($tables)) {
458 foreach ($tables AS $table) {
459 $table = current($table);
461 Logger::info('updating structure', ['table' => $table]);
462 $database[$table] = self::tableStructure($table);
466 // Get the definition
467 if (is_null($definition)) {
468 $definition = self::definition($basePath);
471 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
472 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
473 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
480 foreach ($definition AS $name => $structure) {
481 $is_new_table = false;
486 if (!isset($database[$name])) {
487 $r = self::createTable($name, $structure, $verbose, $action);
488 if (!DBA::isResult($r)) {
489 $errors .= self::printUpdateError($name);
491 $is_new_table = true;
493 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
494 if (isset($database[$name]["indexes"][$indexname])) {
495 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
497 $current_index_definition = "__NOT_SET__";
499 $new_index_definition = implode(",", $fieldnames);
500 if ($current_index_definition != $new_index_definition) {
501 if ($fieldnames[0] == "UNIQUE") {
504 $temp_name = "temp-" . $name;
511 * Drop the index if it isn't present in the definition
512 * or the definition differ from current status
513 * and index name doesn't start with "local_"
515 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
516 $current_index_definition = implode(",", $fieldnames);
517 if (isset($structure["indexes"][$indexname])) {
518 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
520 $new_index_definition = "__NOT_SET__";
522 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
523 $sql2 = self::dropIndex($indexname);
525 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
527 $sql3 .= ", " . $sql2;
531 // Compare the field structure field by field
532 foreach ($structure["fields"] AS $fieldname => $parameters) {
533 if (!isset($database[$name]["fields"][$fieldname])) {
534 $sql2 = self::addTableField($fieldname, $parameters);
536 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
538 $sql3 .= ", " . $sql2;
541 // Compare the field definition
542 $field_definition = $database[$name]["fields"][$fieldname];
544 // Remove the relation data that is used for the referential integrity
545 unset($parameters['relation']);
546 unset($parameters['foreign']);
548 // We change the collation after the indexes had been changed.
549 // This is done to avoid index length problems.
550 // So here we always ensure that there is no need to change it.
551 unset($parameters['Collation']);
552 unset($field_definition['Collation']);
554 // Only update the comment when it is defined
555 if (!isset($parameters['comment'])) {
556 $parameters['comment'] = "";
559 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
560 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
561 if ($current_field_definition != $new_field_definition) {
562 $sql2 = self::modifyTableField($fieldname, $parameters);
564 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
566 $sql3 .= ", " . $sql2;
574 * Create the index if the index don't exists in database
575 * or the definition differ from the current status.
576 * Don't create keys if table is new
578 if (!$is_new_table) {
579 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
580 if (isset($database[$name]["indexes"][$indexname])) {
581 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
583 $current_index_definition = "__NOT_SET__";
585 $new_index_definition = implode(",", $fieldnames);
586 if ($current_index_definition != $new_index_definition) {
587 $sql2 = self::createIndex($indexname, $fieldnames);
589 // Fetch the "group by" fields for unique indexes
590 $group_by = self::groupBy($fieldnames);
593 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
595 $sql3 .= ", " . $sql2;
601 $existing_foreign_keys = $database[$name]['foreign_keys'];
604 // Compare the field structure field by field
605 foreach ($structure["fields"] AS $fieldname => $parameters) {
606 if (empty($parameters['foreign'])) {
610 $constraint = self::getConstraintName($name, $fieldname, $parameters);
612 unset($existing_foreign_keys[$constraint]);
614 if (empty($database[$name]['foreign_keys'][$constraint])) {
615 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
618 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
620 $sql3 .= ", " . $sql2;
625 foreach ($existing_foreign_keys as $param) {
626 $sql2 = self::dropForeignKey($param['CONSTRAINT_NAME']);
629 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
631 $sql3 .= ", " . $sql2;
635 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
636 $structurecomment = $structure["comment"] ?? '';
637 if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
638 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
641 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
643 $sql3 .= ", " . $sql2;
648 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
649 if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
650 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
653 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
655 $sql3 .= ", " . $sql2;
660 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
661 if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
662 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
665 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
667 $sql3 .= ", " . $sql2;
676 // Now have a look at the field collations
677 // Compare the field structure field by field
678 foreach ($structure["fields"] AS $fieldname => $parameters) {
679 // Compare the field definition
680 $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
682 // Define the default collation if not given
683 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
684 $parameters['Collation'] = 'utf8mb4_general_ci';
686 $parameters['Collation'] = null;
689 if ($field_definition['Collation'] != $parameters['Collation']) {
690 $sql2 = self::modifyTableField($fieldname, $parameters);
691 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
692 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
694 $sql3 .= ", " . $sql2;
701 if (substr($sql3, -2, 2) != "; ") {
706 if ($is_unique && $ignore == '') {
707 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
708 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
710 $field_list = rtrim($field_list, ',');
714 // Ensure index conversion to unique removes duplicates
715 if ($is_unique && ($temp_name != $name)) {
717 echo "SET session old_alter_table=1;\n";
719 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
720 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
726 if ($is_unique && ($temp_name != $name)) {
728 echo "SET session old_alter_table=0;\n";
730 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
731 echo "DROP TABLE `" . $name . "`;\n";
732 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
738 if ($in_maintenance_mode) {
739 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
742 // Ensure index conversion to unique removes duplicates
743 if ($is_unique && ($temp_name != $name)) {
745 DBA::e("SET session old_alter_table=1;");
747 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
748 if (!DBA::isResult($r)) {
749 $errors .= self::printUpdateError($sql3);
753 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
754 if (!DBA::isResult($r)) {
755 $errors .= self::printUpdateError($sql3);
762 if (!DBA::isResult($r)) {
763 $errors .= self::printUpdateError($sql3);
765 if ($is_unique && ($temp_name != $name)) {
767 DBA::e("SET session old_alter_table=0;");
769 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
770 if (!DBA::isResult($r)) {
771 $errors .= self::printUpdateError($sql3);
774 $r = DBA::e("DROP TABLE `" . $name . "`;");
775 if (!DBA::isResult($r)) {
776 $errors .= self::printUpdateError($sql3);
779 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
780 if (!DBA::isResult($r)) {
781 $errors .= self::printUpdateError($sql3);
790 View::create(false, $action);
792 self::checkInitialValues();
794 if ($action && !$install) {
796 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
798 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
805 private static function tableStructure($table)
807 // This query doesn't seem to be executable as a prepared statement
808 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
810 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
811 ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
812 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
813 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
814 DBA::databaseName(), $table]);
816 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
817 ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
818 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
819 DBA::databaseName(), $table]);
821 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
822 ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
823 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
824 DBA::databaseName(), $table]);
830 if (DBA::isResult($foreign_keys)) {
831 foreach ($foreign_keys as $foreign_key) {
832 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
833 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
834 $foreigndata[$constraint] = $foreign_key;
838 if (DBA::isResult($indexes)) {
839 foreach ($indexes AS $index) {
840 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
841 $indexdata[$index["Key_name"]] = ["UNIQUE"];
844 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
845 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
848 $column = $index["Column_name"];
850 if ($index["Sub_part"] != "") {
851 $column .= "(" . $index["Sub_part"] . ")";
854 $indexdata[$index["Key_name"]][] = $column;
859 if (DBA::isResult($fields)) {
860 foreach ($fields AS $field) {
861 $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)'];
862 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
863 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
865 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
867 if ($field['IS_NULLABLE'] == 'NO') {
868 $fielddata[$field['COLUMN_NAME']]['not null'] = true;
871 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
872 $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
875 if (!empty($field['EXTRA'])) {
876 $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
879 if ($field['COLUMN_KEY'] == 'PRI') {
880 $fielddata[$field['COLUMN_NAME']]['primary'] = true;
883 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
884 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
888 return ["fields" => $fielddata, "indexes" => $indexdata,
889 "foreign_keys" => $foreigndata, "table_status" => $table_status];
892 private static function dropIndex($indexname)
894 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
898 private static function addTableField($fieldname, $parameters)
900 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
904 private static function modifyTableField($fieldname, $parameters)
906 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
910 private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
912 $foreign_table = array_keys($parameters['foreign'])[0];
913 $foreign_field = array_values($parameters['foreign'])[0];
915 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
918 private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
919 $foreign_table = array_keys($parameters['foreign'])[0];
920 $foreign_field = array_values($parameters['foreign'])[0];
922 $sql = "FOREIGN KEY (`" . $fieldname . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
924 if (!empty($parameters['foreign']['on update'])) {
925 $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
927 $sql .= " ON UPDATE RESTRICT";
930 if (!empty($parameters['foreign']['on delete'])) {
931 $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
933 $sql .= " ON DELETE CASCADE";
939 private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
941 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
944 private static function dropForeignKey(string $constraint)
946 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
950 * Constructs a GROUP BY clause from a UNIQUE index definition.
952 * @param array $fieldnames
955 private static function groupBy(array $fieldnames)
957 if ($fieldnames[0] != "UNIQUE") {
961 array_shift($fieldnames);
964 foreach ($fieldnames AS $fieldname) {
969 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
970 $names .= "`" . DBA::escape($matches[1]) . "`";
972 $names .= "`" . DBA::escape($fieldname) . "`";
976 $sql = sprintf(" GROUP BY %s", $names);
981 * Renames columns or the primary key of a table
983 * @todo You cannot rename a primary key if "auto increment" is set
985 * @param string $table Table name
986 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
987 * Syntax for Primary Key: [ $col1, $col2, ...]
988 * @param int $type The type of renaming (Default is Column)
990 * @return boolean Was the renaming successful?
993 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
995 if (empty($table) || empty($columns)) {
999 if (!is_array($columns)) {
1003 $table = DBA::escape($table);
1005 $sql = "ALTER TABLE `" . $table . "`";
1007 case self::RENAME_COLUMN:
1008 if (!self::existsColumn($table, array_keys($columns))) {
1011 $sql .= implode(',', array_map(
1012 function ($to, $from) {
1013 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
1016 array_keys($columns)
1019 case self::RENAME_PRIMARY_KEY:
1020 if (!self::existsColumn($table, $columns)) {
1023 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
1031 $stmt = DBA::p($sql);
1033 if (is_bool($stmt)) {
1045 * Check if the columns of the table exists
1047 * @param string $table Table name
1048 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
1050 * @return boolean Does the table exist?
1053 public static function existsColumn($table, $columns = [])
1055 if (empty($table)) {
1059 if (is_null($columns) || empty($columns)) {
1060 return self::existsTable($table);
1063 $table = DBA::escape($table);
1065 foreach ($columns AS $column) {
1066 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
1068 $stmt = DBA::p($sql);
1070 if (is_bool($stmt)) {
1073 $retval = (DBA::numRows($stmt) > 0);
1087 * Check if a foreign key exists for the given table field
1089 * @param string $table
1090 * @param string $field
1093 public static function existsForeignKeyForField(string $table, string $field)
1095 return DBA::exists(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
1096 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
1097 DBA::databaseName(), $table, $field]);
1100 * Check if a table exists
1102 * @param string|array $table Table name
1104 * @return boolean Does the table exist?
1107 public static function existsTable($table)
1109 if (empty($table)) {
1113 if (is_array($table)) {
1114 $condition = ['table_schema' => key($table), 'table_name' => current($table)];
1116 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
1119 $result = DBA::exists(['information_schema' => 'tables'], $condition);
1125 * Returns the columns of a table
1127 * @param string $table Table name
1129 * @return array An array of the table columns
1132 public static function getColumns($table)
1134 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
1135 return DBA::toArray($stmtColumns);
1139 * Check if initial database values do exist - or create them
1141 public static function checkInitialValues(bool $verbose = false)
1143 if (self::existsTable('verb')) {
1144 if (!DBA::exists('verb', ['id' => 1])) {
1145 foreach (Item::ACTIVITIES as $index => $activity) {
1146 DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], Database::INSERT_IGNORE);
1149 echo "verb: activities added\n";
1151 } elseif ($verbose) {
1152 echo "verb: activities already added\n";
1155 if (!DBA::exists('verb', ['id' => 0])) {
1156 DBA::insert('verb', ['name' => '']);
1157 $lastid = DBA::lastInsertId();
1159 DBA::update('verb', ['id' => 0], ['id' => $lastid]);
1161 echo "Zero verb added\n";
1164 } elseif ($verbose) {
1165 echo "Zero verb already added\n";
1167 } elseif ($verbose) {
1168 echo "verb: Table not found\n";
1171 if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) {
1174 "page-flags" => User::PAGE_FLAGS_SOAPBOX,
1175 "account-type" => User::ACCOUNT_TYPE_RELAY,
1177 DBA::insert('user', $user);
1178 $lastid = DBA::lastInsertId();
1180 DBA::update('user', ['uid' => 0], ['uid' => $lastid]);
1182 echo "Zero user added\n";
1185 } elseif (self::existsTable('user') && $verbose) {
1186 echo "Zero user already added\n";
1187 } elseif ($verbose) {
1188 echo "user: Table not found\n";
1191 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
1192 DBA::insert('contact', ['nurl' => '']);
1193 $lastid = DBA::lastInsertId();
1195 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
1197 echo "Zero contact added\n";
1200 } elseif (self::existsTable('contact') && $verbose) {
1201 echo "Zero contact already added\n";
1202 } elseif ($verbose) {
1203 echo "contact: Table not found\n";
1206 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
1207 DBA::insert('tag', ['name' => '']);
1208 $lastid = DBA::lastInsertId();
1210 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
1212 echo "Zero tag added\n";
1215 } elseif (self::existsTable('tag') && $verbose) {
1216 echo "Zero tag already added\n";
1217 } elseif ($verbose) {
1218 echo "tag: Table not found\n";
1221 if (self::existsTable('permissionset')) {
1222 if (!DBA::exists('permissionset', ['id' => 0])) {
1223 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
1224 $lastid = DBA::lastInsertId();
1226 DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
1228 echo "Zero permissionset added\n";
1231 } elseif ($verbose) {
1232 echo "Zero permissionset already added\n";
1234 if (!self::existsForeignKeyForField('item', 'psid')) {
1235 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
1236 LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
1237 WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
1238 while ($set = DBA::fetch($sets)) {
1239 if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
1240 $owner = User::getOwnerDataById($set['uid']);
1242 $permission = '<' . $owner['id'] . '>';
1249 $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
1250 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
1251 DBA::insert('permissionset', $fields);
1255 } elseif ($verbose) {
1256 echo "permissionset: Table not found\n";
1259 if (!self::existsForeignKeyForField('tokens', 'client_id')) {
1260 $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
1261 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
1262 WHERE `clients`.`client_id` IS NULL");
1263 while ($token = DBA::fetch($tokens)) {
1264 DBA::delete('tokens', ['id' => $token['id']]);
1266 DBA::close($tokens);
1271 * Checks if a database update is currently running
1275 private static function isUpdating()
1279 $processes = DBA::select(['information_schema' => 'processlist'], ['info'],
1280 ['db' => DBA::databaseName(), 'command' => ['Query', 'Execute']]);
1282 while ($process = DBA::fetch($processes)) {
1283 $parts = explode(' ', $process['info']);
1284 if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
1289 DBA::close($processes);