3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Database;
25 use Friendica\Core\Hook;
26 use Friendica\Core\Logger;
27 use Friendica\Core\Renderer;
29 use Friendica\Model\Item;
30 use Friendica\Model\User;
31 use Friendica\Util\DateTimeFormat;
34 * This class contains functions that doesn't need to know if pdo, mysqli or whatever is used.
38 const UPDATE_NOT_CHECKED = 0; // Database check wasn't executed before
39 const UPDATE_SUCCESSFUL = 1; // Database check was successful
40 const UPDATE_FAILED = 2; // Database check failed
42 const RENAME_COLUMN = 0;
43 const RENAME_PRIMARY_KEY = 1;
46 * Database structure definition loaded from config/dbstructure.config.php
50 private static $definition = [];
53 * Set a database version to trigger update functions
55 * @param string $version
58 public static function setDatabaseVersion(string $version)
60 if (!is_numeric($version)) {
61 throw new \Asika\SimpleConsole\CommandArgsException('The version number must be numeric');
64 DI::config()->set('system', 'build', $version);
65 echo DI::l10n()->t('The database version had been set to %s.', $version);
71 * @param boolean $execute
74 public static function dropTables(bool $execute)
76 $postupdate = DI::config()->get("system", "post_update_version", PostUpdate::VERSION);
77 if ($postupdate < PostUpdate::VERSION) {
78 echo DI::l10n()->t('The post update is at version %d, it has to be at %d to safely drop the tables.', $postupdate, PostUpdate::VERSION);
82 $old_tables = ['fserver', 'gcign', 'gcontact', 'gcontact-relation', 'gfollower' ,'glink', 'item-delivery-data',
83 'item-activity', 'item-content', 'item_id', 'participation', 'poll', 'poll_result', 'queue', 'retriever_rule',
84 'deliverq', 'dsprphotoq', 'ffinder', 'sign', 'spam', 'term', 'user-item', 'thread', 'item', 'challenge',
85 'auth_codes', 'clients', 'tokens', 'profile_check'];
87 $tables = DBA::selectToArray(['INFORMATION_SCHEMA' => 'TABLES'], ['TABLE_NAME'],
88 ['TABLE_SCHEMA' => DBA::databaseName(), 'TABLE_TYPE' => 'BASE TABLE']);
91 echo DI::l10n()->t('No unused tables found.');
96 echo DI::l10n()->t('These tables are not used for friendica and will be deleted when you execute "dbstructure drop -e":') . "\n\n";
99 foreach ($tables as $table) {
100 if (in_array($table['TABLE_NAME'], $old_tables)) {
102 $sql = 'DROP TABLE ' . DBA::quoteIdentifier($table['TABLE_NAME']) . ';';
105 $result = DBA::e($sql);
106 if (!DBA::isResult($result)) {
107 self::printUpdateError($sql);
110 echo $table['TABLE_NAME'] . "\n";
117 * Converts all tables from MyISAM/InnoDB Antelope to InnoDB Barracuda
119 public static function convertToInnoDB()
121 $tables = DBA::selectToArray(
122 ['information_schema' => 'tables'],
124 ['engine' => 'MyISAM', 'table_schema' => DBA::databaseName()]
127 $tables = array_merge($tables, DBA::selectToArray(
128 ['information_schema' => 'tables'],
130 ['engine' => 'InnoDB', 'ROW_FORMAT' => ['COMPACT', 'REDUNDANT'], 'table_schema' => DBA::databaseName()]
133 if (!DBA::isResult($tables)) {
134 echo DI::l10n()->t('There are no tables on MyISAM or InnoDB with the Antelope file format.') . "\n";
138 foreach ($tables as $table) {
139 $sql = "ALTER TABLE " . DBA::quoteIdentifier($table['table_name']) . " ENGINE=InnoDB ROW_FORMAT=DYNAMIC;";
142 $result = DBA::e($sql);
143 if (!DBA::isResult($result)) {
144 self::printUpdateError($sql);
150 * Print out database error messages
152 * @param string $message Message to be added to the error message
154 * @return string Error message
156 private static function printUpdateError($message)
158 echo DI::l10n()->t("\nError %d occurred during database update:\n%s\n",
159 DBA::errorNo(), DBA::errorMessage());
161 return DI::l10n()->t('Errors encountered performing database changes: ') . $message . EOL;
164 public static function writeStructure()
167 foreach (self::definition(null) as $name => $definition) {
170 'fields' => 'Fields',
177 $lengths = ['name' => 4, 'fields' => 6];
178 foreach ($definition['indexes'] as $key => $value) {
179 $fieldlist = implode(', ', $value);
180 $indexes[] = ['name' => $key, 'fields' => $fieldlist];
181 $lengths['name'] = max($lengths['name'], strlen($key));
182 $lengths['fields'] = max($lengths['fields'], strlen($fieldlist));
185 array_walk_recursive($indexes, function(&$value, $key) use ($lengths)
187 $value = str_pad($value, $lengths[$key], $value === '-' ? '-' : ' ');
193 'comment' => 'Description',
197 'default' => 'Default',
218 foreach ($definition['fields'] as $key => $value) {
220 $field['name'] = $key;
221 $field['comment'] = $value['comment'] ?? '';
222 $field['type'] = $value['type'];
223 $field['null'] = ($value['not null'] ?? false) ? 'NO' : 'YES';
224 $field['primary'] = ($value['primary'] ?? false) ? 'PRI' : '';
225 $field['default'] = $value['default'] ?? 'NULL';
226 $field['extra'] = $value['extra'] ?? '';
228 foreach ($field as $fieldname => $fieldvalue) {
229 $lengths[$fieldname] = max($lengths[$fieldname] ?? 0, strlen($fieldvalue));
233 if (!empty($value['foreign'])) {
236 'targettable' => array_keys($value['foreign'])[0],
237 'targetfield' => array_values($value['foreign'])[0]
242 array_walk_recursive($fields, function(&$value, $key) use ($lengths)
244 $value = str_pad($value, $lengths[$key], $value === '-' ? '-' : ' ');
247 $tables[] = ['name' => $name, 'comment' => $definition['comment']];
248 $content = Renderer::replaceMacros(Renderer::getMarkupTemplate('structure.tpl'), [
250 '$comment' => $definition['comment'],
251 '$fields' => $fields,
252 '$indexes' => $indexes,
253 '$foreign' => $foreign,
255 $filename = DI::basePath() . '/doc/database/db_' . $name . '.md';
256 file_put_contents($filename, $content);
259 $content = Renderer::replaceMacros(Renderer::getMarkupTemplate('tables.tpl'), [
260 '$tables' => $tables,
262 $filename = DI::basePath() . '/doc/database.md';
263 file_put_contents($filename, $content);
266 public static function printStructure($basePath)
268 $database = self::definition($basePath, false);
270 echo "-- ------------------------------------------\n";
271 echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n";
272 echo "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
273 echo "-- ------------------------------------------\n\n\n";
274 foreach ($database as $name => $structure) {
276 echo "-- TABLE $name\n";
278 self::createTable($name, $structure, true, false);
283 View::printStructure($basePath);
287 * Loads the database structure definition from the static/dbstructure.config.php file.
288 * On first pass, defines DB_UPDATE_VERSION constant.
290 * @see static/dbstructure.config.php
291 * @param boolean $with_addons_structure Whether to tack on addons additional tables
292 * @param string $basePath The base path of this application
296 public static function definition($basePath, $with_addons_structure = true)
298 if (!self::$definition) {
299 if (empty($basePath)) {
300 $basePath = DI::app()->getBasePath();
303 $filename = $basePath . '/static/dbstructure.config.php';
305 if (!is_readable($filename)) {
306 throw new Exception('Missing database structure config file static/dbstructure.config.php');
309 $definition = require $filename;
312 throw new Exception('Corrupted database structure config file static/dbstructure.config.php');
315 self::$definition = $definition;
317 $definition = self::$definition;
320 if ($with_addons_structure) {
321 Hook::callAll('dbstructure_definition', $definition);
328 * Get field data for the given table
330 * @param string $table
331 * @param array $data data fields
332 * @return array fields for the given
334 public static function getFieldsForTable(string $table, array $data = [])
336 $definition = DBStructure::definition('', false);
337 if (empty($definition[$table])) {
341 $fieldnames = array_keys($definition[$table]['fields']);
345 // Assign all field that are present in the table
346 foreach ($fieldnames as $field) {
347 if (isset($data[$field])) {
348 // Limit the length of varchar, varbinary, char and binrary fields
349 if (is_string($data[$field]) && preg_match("/char\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
350 $data[$field] = mb_substr($data[$field], 0, $result[1]);
351 } elseif (is_string($data[$field]) && preg_match("/binary\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
352 $data[$field] = substr($data[$field], 0, $result[1]);
354 $fields[$field] = $data[$field];
361 private static function createTable($name, $structure, $verbose, $action)
371 foreach ($structure["fields"] as $fieldname => $field) {
372 $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
373 if (!empty($field['primary'])) {
374 $primary_keys[] = $fieldname;
376 if (!empty($field['foreign'])) {
377 $foreign_keys[$fieldname] = $field;
381 if (!empty($structure["indexes"])) {
382 foreach ($structure["indexes"] as $indexname => $fieldnames) {
383 $sql_index = self::createIndex($indexname, $fieldnames, "");
384 if (!is_null($sql_index)) {
385 $sql_rows[] = $sql_index;
390 foreach ($foreign_keys as $fieldname => $parameters) {
391 $sql_rows[] = self::foreignCommand($name, $fieldname, $parameters);
394 if (isset($structure["engine"])) {
395 $engine = " ENGINE=" . $structure["engine"];
398 if (isset($structure["comment"])) {
399 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
402 $sql = implode(",\n\t", $sql_rows);
404 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
405 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
417 private static function FieldCommand($parameters, $create = true)
419 $fieldstruct = $parameters["type"];
421 if (isset($parameters["Collation"])) {
422 $fieldstruct .= " COLLATE " . $parameters["Collation"];
425 if (isset($parameters["not null"])) {
426 $fieldstruct .= " NOT NULL";
429 if (isset($parameters["default"])) {
430 if (strpos(strtolower($parameters["type"]), "int") !== false) {
431 $fieldstruct .= " DEFAULT " . $parameters["default"];
433 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
436 if (isset($parameters["extra"])) {
437 $fieldstruct .= " " . $parameters["extra"];
440 if (isset($parameters["comment"])) {
441 $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
444 /*if (($parameters["primary"] != "") && $create)
445 $fieldstruct .= " PRIMARY KEY";*/
447 return ($fieldstruct);
450 private static function createIndex($indexname, $fieldnames, $method = "ADD")
452 $method = strtoupper(trim($method));
453 if ($method != "" && $method != "ADD") {
454 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
457 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
458 $index_type = array_shift($fieldnames);
459 $method .= " " . $index_type;
463 foreach ($fieldnames as $fieldname) {
468 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
469 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
471 $names .= "`" . DBA::escape($fieldname) . "`";
475 if ($indexname == "PRIMARY") {
476 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
480 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
485 * Perform a database structure dryrun (means: just simulating)
489 public static function dryRun()
491 self::update(DI::app()->getBasePath(), true, false);
495 * Updates DB structure and returns eventual errors messages
497 * @param bool $enable_maintenance_mode Set the maintenance mode
498 * @param bool $verbose Display the SQL commands
500 * @return string Empty string if the update is successful, error messages otherwise
503 public static function performUpdate(bool $enable_maintenance_mode = true, bool $verbose = false)
505 if ($enable_maintenance_mode) {
506 DI::config()->set('system', 'maintenance', 1);
509 $status = self::update(DI::app()->getBasePath(), $verbose, true);
511 if ($enable_maintenance_mode) {
512 DI::config()->set('system', 'maintenance', 0);
513 DI::config()->set('system', 'maintenance_reason', '');
520 * Updates DB structure from the installation and returns eventual errors messages
522 * @param string $basePath The base path of this application
524 * @return string Empty string if the update is successful, error messages otherwise
527 public static function install(string $basePath)
529 return self::update($basePath, false, true, true);
533 * Updates DB structure and returns eventual errors messages
535 * @param string $basePath The base path of this application
536 * @param bool $verbose
537 * @param bool $action Whether to actually apply the update
538 * @param bool $install Is this the initial update during the installation?
539 * @param array $tables An array of the database tables
540 * @param array $definition An array of the definition tables
541 * @return string Empty string if the update is successful, error messages otherwise
544 private static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
546 $in_maintenance_mode = DI::config()->get('system', 'maintenance');
548 if ($action && !$install && self::isUpdating()) {
549 return DI::l10n()->t('Another database update is currently running.');
552 if ($in_maintenance_mode) {
553 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
556 // ensure that all initial values exist. This test has to be done prior and after the structure check.
557 // Prior is needed if the specific tables already exists - after is needed when they had been created.
558 self::checkInitialValues();
562 Logger::info('updating structure');
564 // Get the current structure
567 if (is_null($tables)) {
568 $tables = DBA::toArray(DBA::p("SHOW TABLES"));
571 if (DBA::isResult($tables)) {
572 foreach ($tables as $table) {
573 $table = current($table);
575 Logger::info('updating structure', ['table' => $table]);
576 $database[$table] = self::tableStructure($table);
580 // Get the definition
581 if (is_null($definition)) {
582 $definition = self::definition($basePath);
585 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
586 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
587 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
594 foreach ($definition as $name => $structure) {
595 $is_new_table = false;
597 if (!isset($database[$name])) {
598 $r = self::createTable($name, $structure, $verbose, $action);
599 if (!DBA::isResult($r)) {
600 $errors .= self::printUpdateError($name);
602 $is_new_table = true;
605 * Drop the index if it isn't present in the definition
606 * or the definition differ from current status
607 * and index name doesn't start with "local_"
609 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
610 $current_index_definition = implode(",", $fieldnames);
611 if (isset($structure["indexes"][$indexname])) {
612 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
614 $new_index_definition = "__NOT_SET__";
616 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
617 $sql2 = self::dropIndex($indexname);
619 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
621 $sql3 .= ", " . $sql2;
625 // Compare the field structure field by field
626 foreach ($structure["fields"] as $fieldname => $parameters) {
627 if (!isset($database[$name]["fields"][$fieldname])) {
628 $sql2 = self::addTableField($fieldname, $parameters);
630 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
632 $sql3 .= ", " . $sql2;
635 // Compare the field definition
636 $field_definition = $database[$name]["fields"][$fieldname];
638 // Remove the relation data that is used for the referential integrity
639 unset($parameters['relation']);
640 unset($parameters['foreign']);
642 // We change the collation after the indexes had been changed.
643 // This is done to avoid index length problems.
644 // So here we always ensure that there is no need to change it.
645 unset($parameters['Collation']);
646 unset($field_definition['Collation']);
648 // Only update the comment when it is defined
649 if (!isset($parameters['comment'])) {
650 $parameters['comment'] = "";
653 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
654 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
655 if ($current_field_definition != $new_field_definition) {
656 $sql2 = self::modifyTableField($fieldname, $parameters);
658 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
660 $sql3 .= ", " . $sql2;
668 * Create the index if the index don't exists in database
669 * or the definition differ from the current status.
670 * Don't create keys if table is new
672 if (!$is_new_table) {
673 foreach ($structure["indexes"] as $indexname => $fieldnames) {
674 if (isset($database[$name]["indexes"][$indexname])) {
675 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
677 $current_index_definition = "__NOT_SET__";
679 $new_index_definition = implode(",", $fieldnames);
680 if ($current_index_definition != $new_index_definition) {
681 $sql2 = self::createIndex($indexname, $fieldnames);
685 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
687 $sql3 .= ", " . $sql2;
693 $existing_foreign_keys = $database[$name]['foreign_keys'];
696 // Compare the field structure field by field
697 foreach ($structure["fields"] as $fieldname => $parameters) {
698 if (empty($parameters['foreign'])) {
702 $constraint = self::getConstraintName($name, $fieldname, $parameters);
704 unset($existing_foreign_keys[$constraint]);
706 if (empty($database[$name]['foreign_keys'][$constraint])) {
707 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
710 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
712 $sql3 .= ", " . $sql2;
717 foreach ($existing_foreign_keys as $param) {
718 $sql2 = self::dropForeignKey($param['CONSTRAINT_NAME']);
721 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
723 $sql3 .= ", " . $sql2;
727 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
728 $structurecomment = $structure["comment"] ?? '';
729 if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
730 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
733 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
735 $sql3 .= ", " . $sql2;
740 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
741 if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
742 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
745 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
747 $sql3 .= ", " . $sql2;
752 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
753 if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
754 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
757 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
759 $sql3 .= ", " . $sql2;
768 // Now have a look at the field collations
769 // Compare the field structure field by field
770 foreach ($structure["fields"] as $fieldname => $parameters) {
771 // Compare the field definition
772 $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
774 // Define the default collation if not given
775 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
776 $parameters['Collation'] = 'utf8mb4_general_ci';
778 $parameters['Collation'] = null;
781 if ($field_definition['Collation'] != $parameters['Collation']) {
782 $sql2 = self::modifyTableField($fieldname, $parameters);
783 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
784 $sql3 .= "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
786 $sql3 .= ", " . $sql2;
793 if (substr($sql3, -2, 2) != "; ") {
802 if ($in_maintenance_mode) {
803 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
807 if (!DBA::isResult($r)) {
808 $errors .= self::printUpdateError($sql3);
814 View::create(false, $action);
816 self::checkInitialValues();
818 if ($action && !$install) {
820 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
822 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
829 private static function tableStructure($table)
831 // This query doesn't seem to be executable as a prepared statement
832 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
834 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
835 ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
836 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
837 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
838 DBA::databaseName(), $table]);
840 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
841 ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
842 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
843 DBA::databaseName(), $table]);
845 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
846 ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
847 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
848 DBA::databaseName(), $table]);
854 if (DBA::isResult($foreign_keys)) {
855 foreach ($foreign_keys as $foreign_key) {
856 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
857 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
858 $foreigndata[$constraint] = $foreign_key;
862 if (DBA::isResult($indexes)) {
863 foreach ($indexes as $index) {
864 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
865 $indexdata[$index["Key_name"]] = ["UNIQUE"];
868 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
869 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
872 $column = $index["Column_name"];
874 if ($index["Sub_part"] != "") {
875 $column .= "(" . $index["Sub_part"] . ")";
878 $indexdata[$index["Key_name"]][] = $column;
883 if (DBA::isResult($fields)) {
884 foreach ($fields as $field) {
885 $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)'];
886 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
887 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
889 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
891 if ($field['IS_NULLABLE'] == 'NO') {
892 $fielddata[$field['COLUMN_NAME']]['not null'] = true;
895 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
896 $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
899 if (!empty($field['EXTRA'])) {
900 $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
903 if ($field['COLUMN_KEY'] == 'PRI') {
904 $fielddata[$field['COLUMN_NAME']]['primary'] = true;
907 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
908 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
912 return ["fields" => $fielddata, "indexes" => $indexdata,
913 "foreign_keys" => $foreigndata, "table_status" => $table_status];
916 private static function dropIndex($indexname)
918 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
922 private static function addTableField($fieldname, $parameters)
924 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
928 private static function modifyTableField($fieldname, $parameters)
930 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
934 private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
936 $foreign_table = array_keys($parameters['foreign'])[0];
937 $foreign_field = array_values($parameters['foreign'])[0];
939 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
942 private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
943 $foreign_table = array_keys($parameters['foreign'])[0];
944 $foreign_field = array_values($parameters['foreign'])[0];
946 $sql = "FOREIGN KEY (`" . $fieldname . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
948 if (!empty($parameters['foreign']['on update'])) {
949 $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
951 $sql .= " ON UPDATE RESTRICT";
954 if (!empty($parameters['foreign']['on delete'])) {
955 $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
957 $sql .= " ON DELETE CASCADE";
963 private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
965 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
968 private static function dropForeignKey(string $constraint)
970 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
974 * Renames columns or the primary key of a table
976 * @todo You cannot rename a primary key if "auto increment" is set
978 * @param string $table Table name
979 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
980 * Syntax for Primary Key: [ $col1, $col2, ...]
981 * @param int $type The type of renaming (Default is Column)
983 * @return boolean Was the renaming successful?
986 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
988 if (empty($table) || empty($columns)) {
992 if (!is_array($columns)) {
996 $table = DBA::escape($table);
998 $sql = "ALTER TABLE `" . $table . "`";
1000 case self::RENAME_COLUMN:
1001 if (!self::existsColumn($table, array_keys($columns))) {
1004 $sql .= implode(',', array_map(
1005 function ($to, $from) {
1006 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
1009 array_keys($columns)
1012 case self::RENAME_PRIMARY_KEY:
1013 if (!self::existsColumn($table, $columns)) {
1016 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
1024 $stmt = DBA::p($sql);
1026 if (is_bool($stmt)) {
1038 * Check if the columns of the table exists
1040 * @param string $table Table name
1041 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
1043 * @return boolean Does the table exist?
1046 public static function existsColumn($table, $columns = [])
1048 if (empty($table)) {
1052 if (is_null($columns) || empty($columns)) {
1053 return self::existsTable($table);
1056 $table = DBA::escape($table);
1058 foreach ($columns as $column) {
1059 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
1061 $stmt = DBA::p($sql);
1063 if (is_bool($stmt)) {
1066 $retval = (DBA::numRows($stmt) > 0);
1080 * Check if a foreign key exists for the given table field
1082 * @param string $table
1083 * @param string $field
1086 public static function existsForeignKeyForField(string $table, string $field)
1088 return DBA::exists(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
1089 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
1090 DBA::databaseName(), $table, $field]);
1093 * Check if a table exists
1095 * @param string|array $table Table name
1097 * @return boolean Does the table exist?
1100 public static function existsTable($table)
1102 if (empty($table)) {
1106 if (is_array($table)) {
1107 $condition = ['table_schema' => key($table), 'table_name' => current($table)];
1109 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
1112 $result = DBA::exists(['information_schema' => 'tables'], $condition);
1118 * Returns the columns of a table
1120 * @param string $table Table name
1122 * @return array An array of the table columns
1125 public static function getColumns($table)
1127 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
1128 return DBA::toArray($stmtColumns);
1132 * Check if initial database values do exist - or create them
1134 public static function checkInitialValues(bool $verbose = false)
1136 if (self::existsTable('verb')) {
1137 if (!DBA::exists('verb', ['id' => 1])) {
1138 foreach (Item::ACTIVITIES as $index => $activity) {
1139 DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], Database::INSERT_IGNORE);
1142 echo "verb: activities added\n";
1144 } elseif ($verbose) {
1145 echo "verb: activities already added\n";
1148 if (!DBA::exists('verb', ['id' => 0])) {
1149 DBA::insert('verb', ['name' => '']);
1150 $lastid = DBA::lastInsertId();
1152 DBA::update('verb', ['id' => 0], ['id' => $lastid]);
1154 echo "Zero verb added\n";
1157 } elseif ($verbose) {
1158 echo "Zero verb already added\n";
1160 } elseif ($verbose) {
1161 echo "verb: Table not found\n";
1164 if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) {
1167 "page-flags" => User::PAGE_FLAGS_SOAPBOX,
1168 "account-type" => User::ACCOUNT_TYPE_RELAY,
1170 DBA::insert('user', $user);
1171 $lastid = DBA::lastInsertId();
1173 DBA::update('user', ['uid' => 0], ['uid' => $lastid]);
1175 echo "Zero user added\n";
1178 } elseif (self::existsTable('user') && $verbose) {
1179 echo "Zero user already added\n";
1180 } elseif ($verbose) {
1181 echo "user: Table not found\n";
1184 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
1185 DBA::insert('contact', ['nurl' => '']);
1186 $lastid = DBA::lastInsertId();
1188 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
1190 echo "Zero contact added\n";
1193 } elseif (self::existsTable('contact') && $verbose) {
1194 echo "Zero contact already added\n";
1195 } elseif ($verbose) {
1196 echo "contact: Table not found\n";
1199 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
1200 DBA::insert('tag', ['name' => '']);
1201 $lastid = DBA::lastInsertId();
1203 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
1205 echo "Zero tag added\n";
1208 } elseif (self::existsTable('tag') && $verbose) {
1209 echo "Zero tag already added\n";
1210 } elseif ($verbose) {
1211 echo "tag: Table not found\n";
1214 if (self::existsTable('permissionset')) {
1215 if (!DBA::exists('permissionset', ['id' => 0])) {
1216 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
1217 $lastid = DBA::lastInsertId();
1219 DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
1221 echo "Zero permissionset added\n";
1224 } elseif ($verbose) {
1225 echo "Zero permissionset already added\n";
1227 if (self::existsTable('item') && !self::existsForeignKeyForField('item', 'psid')) {
1228 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
1229 LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
1230 WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
1231 while ($set = DBA::fetch($sets)) {
1232 if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
1233 $owner = User::getOwnerDataById($set['uid']);
1235 $permission = '<' . $owner['id'] . '>';
1242 $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
1243 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
1244 DBA::insert('permissionset', $fields);
1248 } elseif ($verbose) {
1249 echo "permissionset: Table not found\n";
1252 if (self::existsTable('tokens') && self::existsTable('clients') && !self::existsForeignKeyForField('tokens', 'client_id')) {
1253 $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
1254 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
1255 WHERE `clients`.`client_id` IS NULL");
1256 while ($token = DBA::fetch($tokens)) {
1257 DBA::delete('tokens', ['id' => $token['id']]);
1259 DBA::close($tokens);
1264 * Checks if a database update is currently running
1268 private static function isUpdating()
1272 $processes = DBA::select(['information_schema' => 'processlist'], ['info'],
1273 ['db' => DBA::databaseName(), 'command' => ['Query', 'Execute']]);
1275 while ($process = DBA::fetch($processes)) {
1276 $parts = explode(' ', $process['info']);
1277 if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
1282 DBA::close($processes);