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 * Perform a database structure dryrun (means: just simulating)
369 public static function dryRun()
371 self::update(DI::app()->getBasePath(), true, false);
375 * Updates DB structure and returns eventual errors messages
377 * @param bool $enable_maintenance_mode Set the maintenance mode
378 * @param bool $verbose Display the SQL commands
380 * @return string Empty string if the update is successful, error messages otherwise
383 public static function performUpdate(bool $enable_maintenance_mode = true, bool $verbose = false)
385 if ($enable_maintenance_mode) {
386 DI::config()->set('system', 'maintenance', 1);
389 $status = self::update(DI::app()->getBasePath(), $verbose, true);
391 if ($enable_maintenance_mode) {
392 DI::config()->set('system', 'maintenance', 0);
393 DI::config()->set('system', 'maintenance_reason', '');
400 * Updates DB structure from the installation and returns eventual errors messages
402 * @param string $basePath The base path of this application
404 * @return string Empty string if the update is successful, error messages otherwise
407 public static function install(string $basePath)
409 return self::update($basePath, false, true, true);
413 * Updates DB structure and returns eventual errors messages
415 * @param string $basePath The base path of this application
416 * @param bool $verbose
417 * @param bool $action Whether to actually apply the update
418 * @param bool $install Is this the initial update during the installation?
419 * @param array $tables An array of the database tables
420 * @param array $definition An array of the definition tables
421 * @return string Empty string if the update is successful, error messages otherwise
424 private static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
426 $in_maintenance_mode = DI::config()->get('system', 'maintenance');
428 if ($action && !$install && self::isUpdating()) {
429 return DI::l10n()->t('Another database update is currently running.');
432 if ($in_maintenance_mode) {
433 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
436 // ensure that all initial values exist. This test has to be done prior and after the structure check.
437 // Prior is needed if the specific tables already exists - after is needed when they had been created.
438 self::checkInitialValues();
442 Logger::info('updating structure');
444 // Get the current structure
447 if (is_null($tables)) {
448 $tables = DBA::toArray(DBA::p("SHOW TABLES"));
451 if (DBA::isResult($tables)) {
452 foreach ($tables AS $table) {
453 $table = current($table);
455 Logger::info('updating structure', ['table' => $table]);
456 $database[$table] = self::tableStructure($table);
460 // Get the definition
461 if (is_null($definition)) {
462 $definition = self::definition($basePath);
465 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
466 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
467 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
474 foreach ($definition AS $name => $structure) {
475 $is_new_table = false;
480 if (!isset($database[$name])) {
481 $r = self::createTable($name, $structure, $verbose, $action);
482 if (!DBA::isResult($r)) {
483 $errors .= self::printUpdateError($name);
485 $is_new_table = true;
487 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
488 if (isset($database[$name]["indexes"][$indexname])) {
489 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
491 $current_index_definition = "__NOT_SET__";
493 $new_index_definition = implode(",", $fieldnames);
494 if ($current_index_definition != $new_index_definition) {
495 if ($fieldnames[0] == "UNIQUE") {
498 $temp_name = "temp-" . $name;
505 * Drop the index if it isn't present in the definition
506 * or the definition differ from current status
507 * and index name doesn't start with "local_"
509 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
510 $current_index_definition = implode(",", $fieldnames);
511 if (isset($structure["indexes"][$indexname])) {
512 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
514 $new_index_definition = "__NOT_SET__";
516 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
517 $sql2 = self::dropIndex($indexname);
519 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
521 $sql3 .= ", " . $sql2;
525 // Compare the field structure field by field
526 foreach ($structure["fields"] AS $fieldname => $parameters) {
527 if (!isset($database[$name]["fields"][$fieldname])) {
528 $sql2 = self::addTableField($fieldname, $parameters);
530 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
532 $sql3 .= ", " . $sql2;
535 // Compare the field definition
536 $field_definition = $database[$name]["fields"][$fieldname];
538 // Remove the relation data that is used for the referential integrity
539 unset($parameters['relation']);
540 unset($parameters['foreign']);
542 // We change the collation after the indexes had been changed.
543 // This is done to avoid index length problems.
544 // So here we always ensure that there is no need to change it.
545 unset($parameters['Collation']);
546 unset($field_definition['Collation']);
548 // Only update the comment when it is defined
549 if (!isset($parameters['comment'])) {
550 $parameters['comment'] = "";
553 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
554 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
555 if ($current_field_definition != $new_field_definition) {
556 $sql2 = self::modifyTableField($fieldname, $parameters);
558 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
560 $sql3 .= ", " . $sql2;
568 * Create the index if the index don't exists in database
569 * or the definition differ from the current status.
570 * Don't create keys if table is new
572 if (!$is_new_table) {
573 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
574 if (isset($database[$name]["indexes"][$indexname])) {
575 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
577 $current_index_definition = "__NOT_SET__";
579 $new_index_definition = implode(",", $fieldnames);
580 if ($current_index_definition != $new_index_definition) {
581 $sql2 = self::createIndex($indexname, $fieldnames);
583 // Fetch the "group by" fields for unique indexes
584 $group_by = self::groupBy($fieldnames);
587 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
589 $sql3 .= ", " . $sql2;
595 $existing_foreign_keys = $database[$name]['foreign_keys'];
598 // Compare the field structure field by field
599 foreach ($structure["fields"] AS $fieldname => $parameters) {
600 if (empty($parameters['foreign'])) {
604 $constraint = self::getConstraintName($name, $fieldname, $parameters);
606 unset($existing_foreign_keys[$constraint]);
608 if (empty($database[$name]['foreign_keys'][$constraint])) {
609 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
612 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
614 $sql3 .= ", " . $sql2;
619 foreach ($existing_foreign_keys as $param) {
620 $sql2 = self::dropForeignKey($param['CONSTRAINT_NAME']);
623 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
625 $sql3 .= ", " . $sql2;
629 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
630 $structurecomment = $structure["comment"] ?? '';
631 if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
632 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
635 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
637 $sql3 .= ", " . $sql2;
642 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
643 if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
644 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
647 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
649 $sql3 .= ", " . $sql2;
654 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
655 if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
656 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
659 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
661 $sql3 .= ", " . $sql2;
670 // Now have a look at the field collations
671 // Compare the field structure field by field
672 foreach ($structure["fields"] AS $fieldname => $parameters) {
673 // Compare the field definition
674 $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
676 // Define the default collation if not given
677 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
678 $parameters['Collation'] = 'utf8mb4_general_ci';
680 $parameters['Collation'] = null;
683 if ($field_definition['Collation'] != $parameters['Collation']) {
684 $sql2 = self::modifyTableField($fieldname, $parameters);
685 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
686 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
688 $sql3 .= ", " . $sql2;
695 if (substr($sql3, -2, 2) != "; ") {
700 if ($is_unique && $ignore == '') {
701 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
702 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
704 $field_list = rtrim($field_list, ',');
708 // Ensure index conversion to unique removes duplicates
709 if ($is_unique && ($temp_name != $name)) {
711 echo "SET session old_alter_table=1;\n";
713 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
714 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
720 if ($is_unique && ($temp_name != $name)) {
722 echo "SET session old_alter_table=0;\n";
724 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
725 echo "DROP TABLE `" . $name . "`;\n";
726 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
732 if ($in_maintenance_mode) {
733 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
736 // Ensure index conversion to unique removes duplicates
737 if ($is_unique && ($temp_name != $name)) {
739 DBA::e("SET session old_alter_table=1;");
741 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
742 if (!DBA::isResult($r)) {
743 $errors .= self::printUpdateError($sql3);
747 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
748 if (!DBA::isResult($r)) {
749 $errors .= self::printUpdateError($sql3);
756 if (!DBA::isResult($r)) {
757 $errors .= self::printUpdateError($sql3);
759 if ($is_unique && ($temp_name != $name)) {
761 DBA::e("SET session old_alter_table=0;");
763 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
764 if (!DBA::isResult($r)) {
765 $errors .= self::printUpdateError($sql3);
768 $r = DBA::e("DROP TABLE `" . $name . "`;");
769 if (!DBA::isResult($r)) {
770 $errors .= self::printUpdateError($sql3);
773 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
774 if (!DBA::isResult($r)) {
775 $errors .= self::printUpdateError($sql3);
784 View::create(false, $action);
786 self::checkInitialValues();
788 if ($action && !$install) {
790 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
792 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
799 private static function tableStructure($table)
801 // This query doesn't seem to be executable as a prepared statement
802 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
804 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
805 ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
806 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
807 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
808 DBA::databaseName(), $table]);
810 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
811 ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
812 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
813 DBA::databaseName(), $table]);
815 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
816 ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
817 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
818 DBA::databaseName(), $table]);
824 if (DBA::isResult($foreign_keys)) {
825 foreach ($foreign_keys as $foreign_key) {
826 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
827 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
828 $foreigndata[$constraint] = $foreign_key;
832 if (DBA::isResult($indexes)) {
833 foreach ($indexes AS $index) {
834 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
835 $indexdata[$index["Key_name"]] = ["UNIQUE"];
838 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
839 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
842 $column = $index["Column_name"];
844 if ($index["Sub_part"] != "") {
845 $column .= "(" . $index["Sub_part"] . ")";
848 $indexdata[$index["Key_name"]][] = $column;
853 if (DBA::isResult($fields)) {
854 foreach ($fields AS $field) {
855 $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)'];
856 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
857 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
859 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
861 if ($field['IS_NULLABLE'] == 'NO') {
862 $fielddata[$field['COLUMN_NAME']]['not null'] = true;
865 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
866 $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
869 if (!empty($field['EXTRA'])) {
870 $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
873 if ($field['COLUMN_KEY'] == 'PRI') {
874 $fielddata[$field['COLUMN_NAME']]['primary'] = true;
877 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
878 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
882 return ["fields" => $fielddata, "indexes" => $indexdata,
883 "foreign_keys" => $foreigndata, "table_status" => $table_status];
886 private static function dropIndex($indexname)
888 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
892 private static function addTableField($fieldname, $parameters)
894 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
898 private static function modifyTableField($fieldname, $parameters)
900 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
904 private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
906 $foreign_table = array_keys($parameters['foreign'])[0];
907 $foreign_field = array_values($parameters['foreign'])[0];
909 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
912 private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
913 $foreign_table = array_keys($parameters['foreign'])[0];
914 $foreign_field = array_values($parameters['foreign'])[0];
916 $sql = "FOREIGN KEY (`" . $fieldname . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
918 if (!empty($parameters['foreign']['on update'])) {
919 $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
921 $sql .= " ON UPDATE RESTRICT";
924 if (!empty($parameters['foreign']['on delete'])) {
925 $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
927 $sql .= " ON DELETE CASCADE";
933 private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
935 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
938 private static function dropForeignKey(string $constraint)
940 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
944 * Constructs a GROUP BY clause from a UNIQUE index definition.
946 * @param array $fieldnames
949 private static function groupBy(array $fieldnames)
951 if ($fieldnames[0] != "UNIQUE") {
955 array_shift($fieldnames);
958 foreach ($fieldnames AS $fieldname) {
963 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
964 $names .= "`" . DBA::escape($matches[1]) . "`";
966 $names .= "`" . DBA::escape($fieldname) . "`";
970 $sql = sprintf(" GROUP BY %s", $names);
975 * Renames columns or the primary key of a table
977 * @todo You cannot rename a primary key if "auto increment" is set
979 * @param string $table Table name
980 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
981 * Syntax for Primary Key: [ $col1, $col2, ...]
982 * @param int $type The type of renaming (Default is Column)
984 * @return boolean Was the renaming successful?
987 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
989 if (empty($table) || empty($columns)) {
993 if (!is_array($columns)) {
997 $table = DBA::escape($table);
999 $sql = "ALTER TABLE `" . $table . "`";
1001 case self::RENAME_COLUMN:
1002 if (!self::existsColumn($table, array_keys($columns))) {
1005 $sql .= implode(',', array_map(
1006 function ($to, $from) {
1007 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
1010 array_keys($columns)
1013 case self::RENAME_PRIMARY_KEY:
1014 if (!self::existsColumn($table, $columns)) {
1017 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
1025 $stmt = DBA::p($sql);
1027 if (is_bool($stmt)) {
1039 * Check if the columns of the table exists
1041 * @param string $table Table name
1042 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
1044 * @return boolean Does the table exist?
1047 public static function existsColumn($table, $columns = [])
1049 if (empty($table)) {
1053 if (is_null($columns) || empty($columns)) {
1054 return self::existsTable($table);
1057 $table = DBA::escape($table);
1059 foreach ($columns AS $column) {
1060 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
1062 $stmt = DBA::p($sql);
1064 if (is_bool($stmt)) {
1067 $retval = (DBA::numRows($stmt) > 0);
1081 * Check if a foreign key exists for the given table field
1083 * @param string $table
1084 * @param string $field
1087 public static function existsForeignKeyForField(string $table, string $field)
1089 return DBA::exists(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
1090 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
1091 DBA::databaseName(), $table, $field]);
1094 * Check if a table exists
1096 * @param string|array $table Table name
1098 * @return boolean Does the table exist?
1101 public static function existsTable($table)
1103 if (empty($table)) {
1107 if (is_array($table)) {
1108 $condition = ['table_schema' => key($table), 'table_name' => current($table)];
1110 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
1113 $result = DBA::exists(['information_schema' => 'tables'], $condition);
1119 * Returns the columns of a table
1121 * @param string $table Table name
1123 * @return array An array of the table columns
1126 public static function getColumns($table)
1128 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
1129 return DBA::toArray($stmtColumns);
1133 * Check if initial database values do exist - or create them
1135 public static function checkInitialValues(bool $verbose = false)
1137 if (self::existsTable('verb')) {
1138 if (!DBA::exists('verb', ['id' => 1])) {
1139 foreach (Item::ACTIVITIES as $index => $activity) {
1140 DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], Database::INSERT_IGNORE);
1143 echo "verb: activities added\n";
1145 } elseif ($verbose) {
1146 echo "verb: activities already added\n";
1149 if (!DBA::exists('verb', ['id' => 0])) {
1150 DBA::insert('verb', ['name' => '']);
1151 $lastid = DBA::lastInsertId();
1153 DBA::update('verb', ['id' => 0], ['id' => $lastid]);
1155 echo "Zero verb added\n";
1158 } elseif ($verbose) {
1159 echo "Zero verb already added\n";
1161 } elseif ($verbose) {
1162 echo "verb: Table not found\n";
1165 if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) {
1168 "page-flags" => User::PAGE_FLAGS_SOAPBOX,
1169 "account-type" => User::ACCOUNT_TYPE_RELAY,
1171 DBA::insert('user', $user);
1172 $lastid = DBA::lastInsertId();
1174 DBA::update('user', ['uid' => 0], ['uid' => $lastid]);
1176 echo "Zero user added\n";
1179 } elseif (self::existsTable('user') && $verbose) {
1180 echo "Zero user already added\n";
1181 } elseif ($verbose) {
1182 echo "user: Table not found\n";
1185 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
1186 DBA::insert('contact', ['nurl' => '']);
1187 $lastid = DBA::lastInsertId();
1189 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
1191 echo "Zero contact added\n";
1194 } elseif (self::existsTable('contact') && $verbose) {
1195 echo "Zero contact already added\n";
1196 } elseif ($verbose) {
1197 echo "contact: Table not found\n";
1200 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
1201 DBA::insert('tag', ['name' => '']);
1202 $lastid = DBA::lastInsertId();
1204 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
1206 echo "Zero tag added\n";
1209 } elseif (self::existsTable('tag') && $verbose) {
1210 echo "Zero tag already added\n";
1211 } elseif ($verbose) {
1212 echo "tag: Table not found\n";
1215 if (self::existsTable('permissionset')) {
1216 if (!DBA::exists('permissionset', ['id' => 0])) {
1217 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
1218 $lastid = DBA::lastInsertId();
1220 DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
1222 echo "Zero permissionset added\n";
1225 } elseif ($verbose) {
1226 echo "Zero permissionset already added\n";
1228 if (!self::existsForeignKeyForField('item', 'psid')) {
1229 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
1230 LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
1231 WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
1232 while ($set = DBA::fetch($sets)) {
1233 if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
1234 $owner = User::getOwnerDataById($set['uid']);
1236 $permission = '<' . $owner['id'] . '>';
1243 $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
1244 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
1245 DBA::insert('permissionset', $fields);
1249 } elseif ($verbose) {
1250 echo "permissionset: Table not found\n";
1253 if (!self::existsForeignKeyForField('tokens', 'client_id')) {
1254 $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
1255 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
1256 WHERE `clients`.`client_id` IS NULL");
1257 while ($token = DBA::fetch($tokens)) {
1258 DBA::delete('tokens', ['id' => $token['id']]);
1260 DBA::close($tokens);
1265 * Checks if a database update is currently running
1269 private static function isUpdating()
1273 $processes = DBA::select(['information_schema' => 'processlist'], ['info'],
1274 ['db' => DBA::databaseName(), 'command' => ['Query', 'Execute']]);
1276 while ($process = DBA::fetch($processes)) {
1277 $parts = explode(' ', $process['info']);
1278 if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
1283 DBA::close($processes);