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 $old_tables = ['fserver', 'gcign', 'gcontact', 'gcontact-relation', 'gfollower' ,'glink', 'item-delivery-data',
76 'item_id', 'poll', 'poll_result', 'queue', 'retriever_rule', 'sign', 'spam', 'term'];
78 $tables = DBA::selectToArray(['INFORMATION_SCHEMA' => 'TABLES'], ['TABLE_NAME'],
79 ['TABLE_SCHEMA' => DBA::databaseName(), 'TABLE_TYPE' => 'BASE TABLE']);
82 echo DI::l10n()->t('No unused tables found.');
87 echo DI::l10n()->t('These tables are not used for friendica and will be deleted when you execute "dbstructure drop -e":') . "\n\n";
90 foreach ($tables as $table) {
91 if (in_array($table['TABLE_NAME'], $old_tables)) {
93 $sql = 'DROP TABLE ' . DBA::quoteIdentifier($table['TABLE_NAME']) . ';';
96 $result = DBA::e($sql);
97 if (!DBA::isResult($result)) {
98 self::printUpdateError($sql);
101 echo $table['TABLE_NAME'] . "\n";
108 * Converts all tables from MyISAM/InnoDB Antelope to InnoDB Barracuda
110 public static function convertToInnoDB()
112 $tables = DBA::selectToArray(
113 ['information_schema' => 'tables'],
115 ['engine' => 'MyISAM', 'table_schema' => DBA::databaseName()]
118 $tables = array_merge($tables, DBA::selectToArray(
119 ['information_schema' => 'tables'],
121 ['engine' => 'InnoDB', 'ROW_FORMAT' => ['COMPACT', 'REDUNDANT'], 'table_schema' => DBA::databaseName()]
124 if (!DBA::isResult($tables)) {
125 echo DI::l10n()->t('There are no tables on MyISAM or InnoDB with the Antelope file format.') . "\n";
129 foreach ($tables AS $table) {
130 $sql = "ALTER TABLE " . DBA::quoteIdentifier($table['table_name']) . " ENGINE=InnoDB ROW_FORMAT=DYNAMIC;";
133 $result = DBA::e($sql);
134 if (!DBA::isResult($result)) {
135 self::printUpdateError($sql);
141 * Print out database error messages
143 * @param string $message Message to be added to the error message
145 * @return string Error message
147 private static function printUpdateError($message)
149 echo DI::l10n()->t("\nError %d occurred during database update:\n%s\n",
150 DBA::errorNo(), DBA::errorMessage());
152 return DI::l10n()->t('Errors encountered performing database changes: ') . $message . EOL;
155 public static function printStructure($basePath)
157 $database = self::definition($basePath, false);
159 echo "-- ------------------------------------------\n";
160 echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n";
161 echo "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
162 echo "-- ------------------------------------------\n\n\n";
163 foreach ($database AS $name => $structure) {
165 echo "-- TABLE $name\n";
167 self::createTable($name, $structure, true, false);
172 View::printStructure($basePath);
176 * Loads the database structure definition from the static/dbstructure.config.php file.
177 * On first pass, defines DB_UPDATE_VERSION constant.
179 * @see static/dbstructure.config.php
180 * @param boolean $with_addons_structure Whether to tack on addons additional tables
181 * @param string $basePath The base path of this application
185 public static function definition($basePath, $with_addons_structure = true)
187 if (!self::$definition) {
189 $filename = $basePath . '/static/dbstructure.config.php';
191 if (!is_readable($filename)) {
192 throw new Exception('Missing database structure config file static/dbstructure.config.php');
195 $definition = require $filename;
198 throw new Exception('Corrupted database structure config file static/dbstructure.config.php');
201 self::$definition = $definition;
203 $definition = self::$definition;
206 if ($with_addons_structure) {
207 Hook::callAll('dbstructure_definition', $definition);
214 * Get field data for the given table
216 * @param string $table
217 * @param array $data data fields
218 * @return array fields for the given
220 public static function getFieldsForTable(string $table, array $data = [])
222 $definition = DBStructure::definition('', false);
223 if (empty($definition[$table])) {
227 $fieldnames = array_keys($definition[$table]['fields']);
231 // Assign all field that are present in the table
232 foreach ($fieldnames as $field) {
233 if (isset($data[$field])) {
234 $fields[$field] = $data[$field];
241 private static function createTable($name, $structure, $verbose, $action)
251 foreach ($structure["fields"] AS $fieldname => $field) {
252 $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
253 if (!empty($field['primary'])) {
254 $primary_keys[] = $fieldname;
256 if (!empty($field['foreign'])) {
257 $foreign_keys[$fieldname] = $field;
261 if (!empty($structure["indexes"])) {
262 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
263 $sql_index = self::createIndex($indexname, $fieldnames, "");
264 if (!is_null($sql_index)) {
265 $sql_rows[] = $sql_index;
270 foreach ($foreign_keys AS $fieldname => $parameters) {
271 $sql_rows[] = self::foreignCommand($name, $fieldname, $parameters);
274 if (isset($structure["engine"])) {
275 $engine = " ENGINE=" . $structure["engine"];
278 if (isset($structure["comment"])) {
279 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
282 $sql = implode(",\n\t", $sql_rows);
284 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
285 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
297 private static function FieldCommand($parameters, $create = true)
299 $fieldstruct = $parameters["type"];
301 if (isset($parameters["Collation"])) {
302 $fieldstruct .= " COLLATE " . $parameters["Collation"];
305 if (isset($parameters["not null"])) {
306 $fieldstruct .= " NOT NULL";
309 if (isset($parameters["default"])) {
310 if (strpos(strtolower($parameters["type"]), "int") !== false) {
311 $fieldstruct .= " DEFAULT " . $parameters["default"];
313 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
316 if (isset($parameters["extra"])) {
317 $fieldstruct .= " " . $parameters["extra"];
320 if (isset($parameters["comment"])) {
321 $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
324 /*if (($parameters["primary"] != "") && $create)
325 $fieldstruct .= " PRIMARY KEY";*/
327 return ($fieldstruct);
330 private static function createIndex($indexname, $fieldnames, $method = "ADD")
332 $method = strtoupper(trim($method));
333 if ($method != "" && $method != "ADD") {
334 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
337 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
338 $index_type = array_shift($fieldnames);
339 $method .= " " . $index_type;
343 foreach ($fieldnames AS $fieldname) {
348 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
349 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
351 $names .= "`" . DBA::escape($fieldname) . "`";
355 if ($indexname == "PRIMARY") {
356 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
360 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
365 * Updates DB structure and returns eventual errors messages
367 * @param string $basePath The base path of this application
368 * @param bool $verbose
369 * @param bool $action Whether to actually apply the update
370 * @param bool $install Is this the initial update during the installation?
371 * @param array $tables An array of the database tables
372 * @param array $definition An array of the definition tables
373 * @return string Empty string if the update is successful, error messages otherwise
376 public static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
378 if ($action && !$install) {
379 if (self::isUpdating()) {
380 return DI::l10n()->t('Another database update is currently running.');
383 DI::config()->set('system', 'maintenance', 1);
384 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
387 // ensure that all initial values exist. This test has to be done prior and after the structure check.
388 // Prior is needed if the specific tables already exists - after is needed when they had been created.
389 self::checkInitialValues();
393 Logger::info('updating structure');
395 // Get the current structure
398 if (is_null($tables)) {
399 $tables = DBA::toArray(DBA::p("SHOW TABLES"));
402 if (DBA::isResult($tables)) {
403 foreach ($tables AS $table) {
404 $table = current($table);
406 Logger::info('updating structure', ['table' => $table]);
407 $database[$table] = self::tableStructure($table);
411 // Get the definition
412 if (is_null($definition)) {
413 $definition = self::definition($basePath);
416 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
417 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
418 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
425 foreach ($definition AS $name => $structure) {
426 $is_new_table = false;
431 if (!isset($database[$name])) {
432 $r = self::createTable($name, $structure, $verbose, $action);
433 if (!DBA::isResult($r)) {
434 $errors .= self::printUpdateError($name);
436 $is_new_table = true;
438 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
439 if (isset($database[$name]["indexes"][$indexname])) {
440 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
442 $current_index_definition = "__NOT_SET__";
444 $new_index_definition = implode(",", $fieldnames);
445 if ($current_index_definition != $new_index_definition) {
446 if ($fieldnames[0] == "UNIQUE") {
449 $temp_name = "temp-" . $name;
456 * Drop the index if it isn't present in the definition
457 * or the definition differ from current status
458 * and index name doesn't start with "local_"
460 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
461 $current_index_definition = implode(",", $fieldnames);
462 if (isset($structure["indexes"][$indexname])) {
463 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
465 $new_index_definition = "__NOT_SET__";
467 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
468 $sql2 = self::dropIndex($indexname);
470 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
472 $sql3 .= ", " . $sql2;
476 // Compare the field structure field by field
477 foreach ($structure["fields"] AS $fieldname => $parameters) {
478 if (!isset($database[$name]["fields"][$fieldname])) {
479 $sql2 = self::addTableField($fieldname, $parameters);
481 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
483 $sql3 .= ", " . $sql2;
486 // Compare the field definition
487 $field_definition = $database[$name]["fields"][$fieldname];
489 // Remove the relation data that is used for the referential integrity
490 unset($parameters['relation']);
491 unset($parameters['foreign']);
493 // We change the collation after the indexes had been changed.
494 // This is done to avoid index length problems.
495 // So here we always ensure that there is no need to change it.
496 unset($parameters['Collation']);
497 unset($field_definition['Collation']);
499 // Only update the comment when it is defined
500 if (!isset($parameters['comment'])) {
501 $parameters['comment'] = "";
504 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
505 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
506 if ($current_field_definition != $new_field_definition) {
507 $sql2 = self::modifyTableField($fieldname, $parameters);
509 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
511 $sql3 .= ", " . $sql2;
519 * Create the index if the index don't exists in database
520 * or the definition differ from the current status.
521 * Don't create keys if table is new
523 if (!$is_new_table) {
524 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
525 if (isset($database[$name]["indexes"][$indexname])) {
526 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
528 $current_index_definition = "__NOT_SET__";
530 $new_index_definition = implode(",", $fieldnames);
531 if ($current_index_definition != $new_index_definition) {
532 $sql2 = self::createIndex($indexname, $fieldnames);
534 // Fetch the "group by" fields for unique indexes
535 $group_by = self::groupBy($fieldnames);
538 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
540 $sql3 .= ", " . $sql2;
546 $existing_foreign_keys = $database[$name]['foreign_keys'];
549 // Compare the field structure field by field
550 foreach ($structure["fields"] AS $fieldname => $parameters) {
551 if (empty($parameters['foreign'])) {
555 $constraint = self::getConstraintName($name, $fieldname, $parameters);
557 unset($existing_foreign_keys[$constraint]);
559 if (empty($database[$name]['foreign_keys'][$constraint])) {
560 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
563 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
565 $sql3 .= ", " . $sql2;
570 foreach ($existing_foreign_keys as $param) {
571 $sql2 = self::dropForeignKey($param['CONSTRAINT_NAME']);
574 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
576 $sql3 .= ", " . $sql2;
580 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
581 $structurecomment = $structure["comment"] ?? '';
582 if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
583 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
586 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
588 $sql3 .= ", " . $sql2;
593 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
594 if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
595 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
598 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
600 $sql3 .= ", " . $sql2;
605 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
606 if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
607 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
610 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
612 $sql3 .= ", " . $sql2;
621 // Now have a look at the field collations
622 // Compare the field structure field by field
623 foreach ($structure["fields"] AS $fieldname => $parameters) {
624 // Compare the field definition
625 $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
627 // Define the default collation if not given
628 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
629 $parameters['Collation'] = 'utf8mb4_general_ci';
631 $parameters['Collation'] = null;
634 if ($field_definition['Collation'] != $parameters['Collation']) {
635 $sql2 = self::modifyTableField($fieldname, $parameters);
636 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
637 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
639 $sql3 .= ", " . $sql2;
646 if (substr($sql3, -2, 2) != "; ") {
651 if ($is_unique && $ignore == '') {
652 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
653 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
655 $field_list = rtrim($field_list, ',');
659 // Ensure index conversion to unique removes duplicates
660 if ($is_unique && ($temp_name != $name)) {
662 echo "SET session old_alter_table=1;\n";
664 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
665 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
671 if ($is_unique && ($temp_name != $name)) {
673 echo "SET session old_alter_table=0;\n";
675 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
676 echo "DROP TABLE `" . $name . "`;\n";
677 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
684 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
687 // Ensure index conversion to unique removes duplicates
688 if ($is_unique && ($temp_name != $name)) {
690 DBA::e("SET session old_alter_table=1;");
692 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
693 if (!DBA::isResult($r)) {
694 $errors .= self::printUpdateError($sql3);
698 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
699 if (!DBA::isResult($r)) {
700 $errors .= self::printUpdateError($sql3);
707 if (!DBA::isResult($r)) {
708 $errors .= self::printUpdateError($sql3);
710 if ($is_unique && ($temp_name != $name)) {
712 DBA::e("SET session old_alter_table=0;");
714 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
715 if (!DBA::isResult($r)) {
716 $errors .= self::printUpdateError($sql3);
719 $r = DBA::e("DROP TABLE `" . $name . "`;");
720 if (!DBA::isResult($r)) {
721 $errors .= self::printUpdateError($sql3);
724 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
725 if (!DBA::isResult($r)) {
726 $errors .= self::printUpdateError($sql3);
735 View::create(false, $action);
737 self::checkInitialValues();
739 if ($action && !$install) {
740 DI::config()->set('system', 'maintenance', 0);
741 DI::config()->set('system', 'maintenance_reason', '');
744 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
746 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
753 private static function tableStructure($table)
755 // This query doesn't seem to be executable as a prepared statement
756 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
758 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
759 ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
760 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
761 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
762 DBA::databaseName(), $table]);
764 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
765 ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
766 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
767 DBA::databaseName(), $table]);
769 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
770 ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
771 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
772 DBA::databaseName(), $table]);
778 if (DBA::isResult($foreign_keys)) {
779 foreach ($foreign_keys as $foreign_key) {
780 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
781 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
782 $foreigndata[$constraint] = $foreign_key;
786 if (DBA::isResult($indexes)) {
787 foreach ($indexes AS $index) {
788 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
789 $indexdata[$index["Key_name"]] = ["UNIQUE"];
792 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
793 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
796 $column = $index["Column_name"];
798 if ($index["Sub_part"] != "") {
799 $column .= "(" . $index["Sub_part"] . ")";
802 $indexdata[$index["Key_name"]][] = $column;
807 if (DBA::isResult($fields)) {
808 foreach ($fields AS $field) {
809 $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)'];
810 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
811 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
813 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
815 if ($field['IS_NULLABLE'] == 'NO') {
816 $fielddata[$field['COLUMN_NAME']]['not null'] = true;
819 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
820 $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
823 if (!empty($field['EXTRA'])) {
824 $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
827 if ($field['COLUMN_KEY'] == 'PRI') {
828 $fielddata[$field['COLUMN_NAME']]['primary'] = true;
831 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
832 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
836 return ["fields" => $fielddata, "indexes" => $indexdata,
837 "foreign_keys" => $foreigndata, "table_status" => $table_status];
840 private static function dropIndex($indexname)
842 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
846 private static function addTableField($fieldname, $parameters)
848 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
852 private static function modifyTableField($fieldname, $parameters)
854 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
858 private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
860 $foreign_table = array_keys($parameters['foreign'])[0];
861 $foreign_field = array_values($parameters['foreign'])[0];
863 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
866 private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
867 $foreign_table = array_keys($parameters['foreign'])[0];
868 $foreign_field = array_values($parameters['foreign'])[0];
870 $sql = "FOREIGN KEY (`" . $fieldname . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
872 if (!empty($parameters['foreign']['on update'])) {
873 $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
875 $sql .= " ON UPDATE RESTRICT";
878 if (!empty($parameters['foreign']['on delete'])) {
879 $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
881 $sql .= " ON DELETE CASCADE";
887 private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
889 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
892 private static function dropForeignKey(string $constraint)
894 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
898 * Constructs a GROUP BY clause from a UNIQUE index definition.
900 * @param array $fieldnames
903 private static function groupBy(array $fieldnames)
905 if ($fieldnames[0] != "UNIQUE") {
909 array_shift($fieldnames);
912 foreach ($fieldnames AS $fieldname) {
917 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
918 $names .= "`" . DBA::escape($matches[1]) . "`";
920 $names .= "`" . DBA::escape($fieldname) . "`";
924 $sql = sprintf(" GROUP BY %s", $names);
929 * Renames columns or the primary key of a table
931 * @todo You cannot rename a primary key if "auto increment" is set
933 * @param string $table Table name
934 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
935 * Syntax for Primary Key: [ $col1, $col2, ...]
936 * @param int $type The type of renaming (Default is Column)
938 * @return boolean Was the renaming successful?
941 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
943 if (empty($table) || empty($columns)) {
947 if (!is_array($columns)) {
951 $table = DBA::escape($table);
953 $sql = "ALTER TABLE `" . $table . "`";
955 case self::RENAME_COLUMN:
956 if (!self::existsColumn($table, array_keys($columns))) {
959 $sql .= implode(',', array_map(
960 function ($to, $from) {
961 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
967 case self::RENAME_PRIMARY_KEY:
968 if (!self::existsColumn($table, $columns)) {
971 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
979 $stmt = DBA::p($sql);
981 if (is_bool($stmt)) {
993 * Check if the columns of the table exists
995 * @param string $table Table name
996 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
998 * @return boolean Does the table exist?
1001 public static function existsColumn($table, $columns = [])
1003 if (empty($table)) {
1007 if (is_null($columns) || empty($columns)) {
1008 return self::existsTable($table);
1011 $table = DBA::escape($table);
1013 foreach ($columns AS $column) {
1014 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
1016 $stmt = DBA::p($sql);
1018 if (is_bool($stmt)) {
1021 $retval = (DBA::numRows($stmt) > 0);
1035 * Check if a foreign key exists for the given table field
1037 * @param string $table
1038 * @param string $field
1041 public static function existsForeignKeyForField(string $table, string $field)
1043 return DBA::exists(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
1044 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
1045 DBA::databaseName(), $table, $field]);
1048 * Check if a table exists
1050 * @param string|array $table Table name
1052 * @return boolean Does the table exist?
1055 public static function existsTable($table)
1057 if (empty($table)) {
1061 if (is_array($table)) {
1062 $condition = ['table_schema' => key($table), 'table_name' => current($table)];
1064 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
1067 $result = DBA::exists(['information_schema' => 'tables'], $condition);
1073 * Returns the columns of a table
1075 * @param string $table Table name
1077 * @return array An array of the table columns
1080 public static function getColumns($table)
1082 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
1083 return DBA::toArray($stmtColumns);
1087 * Check if initial database values do exist - or create them
1089 public static function checkInitialValues(bool $verbose = false)
1091 if (self::existsTable('verb')) {
1092 if (!DBA::exists('verb', ['id' => 1])) {
1093 foreach (Item::ACTIVITIES as $index => $activity) {
1094 DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], Database::INSERT_IGNORE);
1097 echo "verb: activities added\n";
1099 } elseif ($verbose) {
1100 echo "verb: activities already added\n";
1103 if (!DBA::exists('verb', ['id' => 0])) {
1104 DBA::insert('verb', ['name' => '']);
1105 $lastid = DBA::lastInsertId();
1107 DBA::update('verb', ['id' => 0], ['id' => $lastid]);
1109 echo "Zero verb added\n";
1112 } elseif ($verbose) {
1113 echo "Zero verb already added\n";
1115 } elseif ($verbose) {
1116 echo "verb: Table not found\n";
1119 if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) {
1122 "page-flags" => User::PAGE_FLAGS_SOAPBOX,
1123 "account-type" => User::ACCOUNT_TYPE_RELAY,
1125 DBA::insert('user', $user);
1126 $lastid = DBA::lastInsertId();
1128 DBA::update('user', ['uid' => 0], ['uid' => $lastid]);
1130 echo "Zero user added\n";
1133 } elseif (self::existsTable('user') && $verbose) {
1134 echo "Zero user already added\n";
1135 } elseif ($verbose) {
1136 echo "user: Table not found\n";
1139 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
1140 DBA::insert('contact', ['nurl' => '']);
1141 $lastid = DBA::lastInsertId();
1143 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
1145 echo "Zero contact added\n";
1148 } elseif (self::existsTable('contact') && $verbose) {
1149 echo "Zero contact already added\n";
1150 } elseif ($verbose) {
1151 echo "contact: Table not found\n";
1154 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
1155 DBA::insert('tag', ['name' => '']);
1156 $lastid = DBA::lastInsertId();
1158 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
1160 echo "Zero tag added\n";
1163 } elseif (self::existsTable('tag') && $verbose) {
1164 echo "Zero tag already added\n";
1165 } elseif ($verbose) {
1166 echo "tag: Table not found\n";
1169 if (self::existsTable('permissionset')) {
1170 if (!DBA::exists('permissionset', ['id' => 0])) {
1171 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
1172 $lastid = DBA::lastInsertId();
1174 DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
1176 echo "Zero permissionset added\n";
1179 } elseif ($verbose) {
1180 echo "Zero permissionset already added\n";
1182 if (!self::existsForeignKeyForField('item', 'psid')) {
1183 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
1184 LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
1185 WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
1186 while ($set = DBA::fetch($sets)) {
1187 if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
1188 $owner = User::getOwnerDataById($set['uid']);
1190 $permission = '<' . $owner['id'] . '>';
1197 $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
1198 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
1199 DBA::insert('permissionset', $fields);
1203 } elseif ($verbose) {
1204 echo "permissionset: Table not found\n";
1207 if (!self::existsForeignKeyForField('tokens', 'client_id')) {
1208 $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
1209 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
1210 WHERE `clients`.`client_id` IS NULL");
1211 while ($token = DBA::fetch($tokens)) {
1212 DBA::delete('tokens', ['id' => $token['id']]);
1214 DBA::close($tokens);
1219 * Checks if a database update is currently running
1223 private static function isUpdating()
1227 $processes = DBA::select(['information_schema' => 'processlist'], ['info'],
1228 ['db' => DBA::databaseName(), 'command' => ['Query', 'Execute']]);
1230 while ($process = DBA::fetch($processes)) {
1231 $parts = explode(' ', $process['info']);
1232 if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
1237 DBA::close($processes);