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 $in_maintenance = DI::config()->get('system', 'maintenance');
380 if ($action && !$install) {
381 if (self::isUpdating()) {
382 return DI::l10n()->t('Another database update is currently running.');
385 DI::config()->set('system', 'maintenance', 1);
386 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
389 // ensure that all initial values exist. This test has to be done prior and after the structure check.
390 // Prior is needed if the specific tables already exists - after is needed when they had been created.
391 self::checkInitialValues();
395 Logger::info('updating structure');
397 // Get the current structure
400 if (is_null($tables)) {
401 $tables = DBA::toArray(DBA::p("SHOW TABLES"));
404 if (DBA::isResult($tables)) {
405 foreach ($tables AS $table) {
406 $table = current($table);
408 Logger::info('updating structure', ['table' => $table]);
409 $database[$table] = self::tableStructure($table);
413 // Get the definition
414 if (is_null($definition)) {
415 $definition = self::definition($basePath);
418 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
419 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
420 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
427 foreach ($definition AS $name => $structure) {
428 $is_new_table = false;
433 if (!isset($database[$name])) {
434 $r = self::createTable($name, $structure, $verbose, $action);
435 if (!DBA::isResult($r)) {
436 $errors .= self::printUpdateError($name);
438 $is_new_table = true;
440 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
441 if (isset($database[$name]["indexes"][$indexname])) {
442 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
444 $current_index_definition = "__NOT_SET__";
446 $new_index_definition = implode(",", $fieldnames);
447 if ($current_index_definition != $new_index_definition) {
448 if ($fieldnames[0] == "UNIQUE") {
451 $temp_name = "temp-" . $name;
458 * Drop the index if it isn't present in the definition
459 * or the definition differ from current status
460 * and index name doesn't start with "local_"
462 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
463 $current_index_definition = implode(",", $fieldnames);
464 if (isset($structure["indexes"][$indexname])) {
465 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
467 $new_index_definition = "__NOT_SET__";
469 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
470 $sql2 = self::dropIndex($indexname);
472 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
474 $sql3 .= ", " . $sql2;
478 // Compare the field structure field by field
479 foreach ($structure["fields"] AS $fieldname => $parameters) {
480 if (!isset($database[$name]["fields"][$fieldname])) {
481 $sql2 = self::addTableField($fieldname, $parameters);
483 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
485 $sql3 .= ", " . $sql2;
488 // Compare the field definition
489 $field_definition = $database[$name]["fields"][$fieldname];
491 // Remove the relation data that is used for the referential integrity
492 unset($parameters['relation']);
493 unset($parameters['foreign']);
495 // We change the collation after the indexes had been changed.
496 // This is done to avoid index length problems.
497 // So here we always ensure that there is no need to change it.
498 unset($parameters['Collation']);
499 unset($field_definition['Collation']);
501 // Only update the comment when it is defined
502 if (!isset($parameters['comment'])) {
503 $parameters['comment'] = "";
506 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
507 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
508 if ($current_field_definition != $new_field_definition) {
509 $sql2 = self::modifyTableField($fieldname, $parameters);
511 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
513 $sql3 .= ", " . $sql2;
521 * Create the index if the index don't exists in database
522 * or the definition differ from the current status.
523 * Don't create keys if table is new
525 if (!$is_new_table) {
526 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
527 if (isset($database[$name]["indexes"][$indexname])) {
528 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
530 $current_index_definition = "__NOT_SET__";
532 $new_index_definition = implode(",", $fieldnames);
533 if ($current_index_definition != $new_index_definition) {
534 $sql2 = self::createIndex($indexname, $fieldnames);
536 // Fetch the "group by" fields for unique indexes
537 $group_by = self::groupBy($fieldnames);
540 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
542 $sql3 .= ", " . $sql2;
548 $existing_foreign_keys = $database[$name]['foreign_keys'];
551 // Compare the field structure field by field
552 foreach ($structure["fields"] AS $fieldname => $parameters) {
553 if (empty($parameters['foreign'])) {
557 $constraint = self::getConstraintName($name, $fieldname, $parameters);
559 unset($existing_foreign_keys[$constraint]);
561 if (empty($database[$name]['foreign_keys'][$constraint])) {
562 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
565 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
567 $sql3 .= ", " . $sql2;
572 foreach ($existing_foreign_keys as $param) {
573 $sql2 = self::dropForeignKey($param['CONSTRAINT_NAME']);
576 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
578 $sql3 .= ", " . $sql2;
582 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
583 $structurecomment = $structure["comment"] ?? '';
584 if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
585 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
588 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
590 $sql3 .= ", " . $sql2;
595 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
596 if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
597 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
600 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
602 $sql3 .= ", " . $sql2;
607 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
608 if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
609 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
612 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
614 $sql3 .= ", " . $sql2;
623 // Now have a look at the field collations
624 // Compare the field structure field by field
625 foreach ($structure["fields"] AS $fieldname => $parameters) {
626 // Compare the field definition
627 $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
629 // Define the default collation if not given
630 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
631 $parameters['Collation'] = 'utf8mb4_general_ci';
633 $parameters['Collation'] = null;
636 if ($field_definition['Collation'] != $parameters['Collation']) {
637 $sql2 = self::modifyTableField($fieldname, $parameters);
638 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
639 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
641 $sql3 .= ", " . $sql2;
648 if (substr($sql3, -2, 2) != "; ") {
653 if ($is_unique && $ignore == '') {
654 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
655 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
657 $field_list = rtrim($field_list, ',');
661 // Ensure index conversion to unique removes duplicates
662 if ($is_unique && ($temp_name != $name)) {
664 echo "SET session old_alter_table=1;\n";
666 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
667 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
673 if ($is_unique && ($temp_name != $name)) {
675 echo "SET session old_alter_table=0;\n";
677 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
678 echo "DROP TABLE `" . $name . "`;\n";
679 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
686 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
689 // Ensure index conversion to unique removes duplicates
690 if ($is_unique && ($temp_name != $name)) {
692 DBA::e("SET session old_alter_table=1;");
694 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
695 if (!DBA::isResult($r)) {
696 $errors .= self::printUpdateError($sql3);
700 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
701 if (!DBA::isResult($r)) {
702 $errors .= self::printUpdateError($sql3);
709 if (!DBA::isResult($r)) {
710 $errors .= self::printUpdateError($sql3);
712 if ($is_unique && ($temp_name != $name)) {
714 DBA::e("SET session old_alter_table=0;");
716 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
717 if (!DBA::isResult($r)) {
718 $errors .= self::printUpdateError($sql3);
721 $r = DBA::e("DROP TABLE `" . $name . "`;");
722 if (!DBA::isResult($r)) {
723 $errors .= self::printUpdateError($sql3);
726 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
727 if (!DBA::isResult($r)) {
728 $errors .= self::printUpdateError($sql3);
737 View::create(false, $action);
739 self::checkInitialValues();
741 if ($action && !$install) {
742 if (!$in_maintenance) {
743 DI::config()->set('system', 'maintenance', 0);
744 DI::config()->set('system', 'maintenance_reason', '');
748 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
750 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
757 private static function tableStructure($table)
759 // This query doesn't seem to be executable as a prepared statement
760 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
762 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
763 ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
764 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
765 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
766 DBA::databaseName(), $table]);
768 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
769 ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
770 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
771 DBA::databaseName(), $table]);
773 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
774 ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
775 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
776 DBA::databaseName(), $table]);
782 if (DBA::isResult($foreign_keys)) {
783 foreach ($foreign_keys as $foreign_key) {
784 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
785 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
786 $foreigndata[$constraint] = $foreign_key;
790 if (DBA::isResult($indexes)) {
791 foreach ($indexes AS $index) {
792 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
793 $indexdata[$index["Key_name"]] = ["UNIQUE"];
796 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
797 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
800 $column = $index["Column_name"];
802 if ($index["Sub_part"] != "") {
803 $column .= "(" . $index["Sub_part"] . ")";
806 $indexdata[$index["Key_name"]][] = $column;
811 if (DBA::isResult($fields)) {
812 foreach ($fields AS $field) {
813 $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)'];
814 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
815 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
817 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
819 if ($field['IS_NULLABLE'] == 'NO') {
820 $fielddata[$field['COLUMN_NAME']]['not null'] = true;
823 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
824 $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
827 if (!empty($field['EXTRA'])) {
828 $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
831 if ($field['COLUMN_KEY'] == 'PRI') {
832 $fielddata[$field['COLUMN_NAME']]['primary'] = true;
835 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
836 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
840 return ["fields" => $fielddata, "indexes" => $indexdata,
841 "foreign_keys" => $foreigndata, "table_status" => $table_status];
844 private static function dropIndex($indexname)
846 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
850 private static function addTableField($fieldname, $parameters)
852 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
856 private static function modifyTableField($fieldname, $parameters)
858 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
862 private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
864 $foreign_table = array_keys($parameters['foreign'])[0];
865 $foreign_field = array_values($parameters['foreign'])[0];
867 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
870 private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
871 $foreign_table = array_keys($parameters['foreign'])[0];
872 $foreign_field = array_values($parameters['foreign'])[0];
874 $sql = "FOREIGN KEY (`" . $fieldname . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
876 if (!empty($parameters['foreign']['on update'])) {
877 $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
879 $sql .= " ON UPDATE RESTRICT";
882 if (!empty($parameters['foreign']['on delete'])) {
883 $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
885 $sql .= " ON DELETE CASCADE";
891 private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
893 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
896 private static function dropForeignKey(string $constraint)
898 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
902 * Constructs a GROUP BY clause from a UNIQUE index definition.
904 * @param array $fieldnames
907 private static function groupBy(array $fieldnames)
909 if ($fieldnames[0] != "UNIQUE") {
913 array_shift($fieldnames);
916 foreach ($fieldnames AS $fieldname) {
921 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
922 $names .= "`" . DBA::escape($matches[1]) . "`";
924 $names .= "`" . DBA::escape($fieldname) . "`";
928 $sql = sprintf(" GROUP BY %s", $names);
933 * Renames columns or the primary key of a table
935 * @todo You cannot rename a primary key if "auto increment" is set
937 * @param string $table Table name
938 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
939 * Syntax for Primary Key: [ $col1, $col2, ...]
940 * @param int $type The type of renaming (Default is Column)
942 * @return boolean Was the renaming successful?
945 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
947 if (empty($table) || empty($columns)) {
951 if (!is_array($columns)) {
955 $table = DBA::escape($table);
957 $sql = "ALTER TABLE `" . $table . "`";
959 case self::RENAME_COLUMN:
960 if (!self::existsColumn($table, array_keys($columns))) {
963 $sql .= implode(',', array_map(
964 function ($to, $from) {
965 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
971 case self::RENAME_PRIMARY_KEY:
972 if (!self::existsColumn($table, $columns)) {
975 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
983 $stmt = DBA::p($sql);
985 if (is_bool($stmt)) {
997 * Check if the columns of the table exists
999 * @param string $table Table name
1000 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
1002 * @return boolean Does the table exist?
1005 public static function existsColumn($table, $columns = [])
1007 if (empty($table)) {
1011 if (is_null($columns) || empty($columns)) {
1012 return self::existsTable($table);
1015 $table = DBA::escape($table);
1017 foreach ($columns AS $column) {
1018 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
1020 $stmt = DBA::p($sql);
1022 if (is_bool($stmt)) {
1025 $retval = (DBA::numRows($stmt) > 0);
1039 * Check if a foreign key exists for the given table field
1041 * @param string $table
1042 * @param string $field
1045 public static function existsForeignKeyForField(string $table, string $field)
1047 return DBA::exists(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
1048 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
1049 DBA::databaseName(), $table, $field]);
1052 * Check if a table exists
1054 * @param string|array $table Table name
1056 * @return boolean Does the table exist?
1059 public static function existsTable($table)
1061 if (empty($table)) {
1065 if (is_array($table)) {
1066 $condition = ['table_schema' => key($table), 'table_name' => current($table)];
1068 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
1071 $result = DBA::exists(['information_schema' => 'tables'], $condition);
1077 * Returns the columns of a table
1079 * @param string $table Table name
1081 * @return array An array of the table columns
1084 public static function getColumns($table)
1086 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
1087 return DBA::toArray($stmtColumns);
1091 * Check if initial database values do exist - or create them
1093 public static function checkInitialValues(bool $verbose = false)
1095 if (self::existsTable('verb')) {
1096 if (!DBA::exists('verb', ['id' => 1])) {
1097 foreach (Item::ACTIVITIES as $index => $activity) {
1098 DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], Database::INSERT_IGNORE);
1101 echo "verb: activities added\n";
1103 } elseif ($verbose) {
1104 echo "verb: activities already added\n";
1107 if (!DBA::exists('verb', ['id' => 0])) {
1108 DBA::insert('verb', ['name' => '']);
1109 $lastid = DBA::lastInsertId();
1111 DBA::update('verb', ['id' => 0], ['id' => $lastid]);
1113 echo "Zero verb added\n";
1116 } elseif ($verbose) {
1117 echo "Zero verb already added\n";
1119 } elseif ($verbose) {
1120 echo "verb: Table not found\n";
1123 if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) {
1126 "page-flags" => User::PAGE_FLAGS_SOAPBOX,
1127 "account-type" => User::ACCOUNT_TYPE_RELAY,
1129 DBA::insert('user', $user);
1130 $lastid = DBA::lastInsertId();
1132 DBA::update('user', ['uid' => 0], ['uid' => $lastid]);
1134 echo "Zero user added\n";
1137 } elseif (self::existsTable('user') && $verbose) {
1138 echo "Zero user already added\n";
1139 } elseif ($verbose) {
1140 echo "user: Table not found\n";
1143 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
1144 DBA::insert('contact', ['nurl' => '']);
1145 $lastid = DBA::lastInsertId();
1147 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
1149 echo "Zero contact added\n";
1152 } elseif (self::existsTable('contact') && $verbose) {
1153 echo "Zero contact already added\n";
1154 } elseif ($verbose) {
1155 echo "contact: Table not found\n";
1158 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
1159 DBA::insert('tag', ['name' => '']);
1160 $lastid = DBA::lastInsertId();
1162 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
1164 echo "Zero tag added\n";
1167 } elseif (self::existsTable('tag') && $verbose) {
1168 echo "Zero tag already added\n";
1169 } elseif ($verbose) {
1170 echo "tag: Table not found\n";
1173 if (self::existsTable('permissionset')) {
1174 if (!DBA::exists('permissionset', ['id' => 0])) {
1175 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
1176 $lastid = DBA::lastInsertId();
1178 DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
1180 echo "Zero permissionset added\n";
1183 } elseif ($verbose) {
1184 echo "Zero permissionset already added\n";
1186 if (!self::existsForeignKeyForField('item', 'psid')) {
1187 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
1188 LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
1189 WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
1190 while ($set = DBA::fetch($sets)) {
1191 if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
1192 $owner = User::getOwnerDataById($set['uid']);
1194 $permission = '<' . $owner['id'] . '>';
1201 $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
1202 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
1203 DBA::insert('permissionset', $fields);
1207 } elseif ($verbose) {
1208 echo "permissionset: Table not found\n";
1211 if (!self::existsForeignKeyForField('tokens', 'client_id')) {
1212 $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
1213 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
1214 WHERE `clients`.`client_id` IS NULL");
1215 while ($token = DBA::fetch($tokens)) {
1216 DBA::delete('tokens', ['id' => $token['id']]);
1218 DBA::close($tokens);
1223 * Checks if a database update is currently running
1227 private static function isUpdating()
1231 $processes = DBA::select(['information_schema' => 'processlist'], ['info'],
1232 ['db' => DBA::databaseName(), 'command' => ['Query', 'Execute']]);
1234 while ($process = DBA::fetch($processes)) {
1235 $parts = explode(' ', $process['info']);
1236 if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
1241 DBA::close($processes);