3 * @copyright Copyright (C) 2010-2022, 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', 'tokens', 'clients', 'profile_check', 'host'];
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 ($old_tables as $table) {
100 if (in_array($table, array_column($tables, 'TABLE_NAME'))) {
102 $sql = 'DROP TABLE ' . DBA::quoteIdentifier($table) . ';';
105 $result = DBA::e($sql);
106 if (!DBA::isResult($result)) {
107 self::printUpdateError($sql);
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
153 * @return string Error message
155 private static function printUpdateError(string $message): string
157 echo DI::l10n()->t("\nError %d occurred during database update:\n%s\n",
158 DBA::errorNo(), DBA::errorMessage());
160 return DI::l10n()->t('Errors encountered performing database changes: ') . $message . EOL;
163 public static function writeStructure()
166 foreach (self::definition('') as $name => $definition) {
169 'fields' => 'Fields',
176 $lengths = ['name' => 4, 'fields' => 6];
177 foreach ($definition['indexes'] as $key => $value) {
178 $fieldlist = implode(', ', $value);
179 $indexes[] = ['name' => $key, 'fields' => $fieldlist];
180 $lengths['name'] = max($lengths['name'], strlen($key));
181 $lengths['fields'] = max($lengths['fields'], strlen($fieldlist));
184 array_walk_recursive($indexes, function(&$value, $key) use ($lengths)
186 $value = str_pad($value, $lengths[$key], $value === '-' ? '-' : ' ');
192 'comment' => 'Description',
196 'default' => 'Default',
217 foreach ($definition['fields'] as $key => $value) {
219 $field['name'] = $key;
220 $field['comment'] = $value['comment'] ?? '';
221 $field['type'] = $value['type'];
222 $field['null'] = ($value['not null'] ?? false) ? 'NO' : 'YES';
223 $field['primary'] = ($value['primary'] ?? false) ? 'PRI' : '';
224 $field['default'] = $value['default'] ?? 'NULL';
225 $field['extra'] = $value['extra'] ?? '';
227 foreach ($field as $fieldName => $fieldvalue) {
228 $lengths[$fieldName] = max($lengths[$fieldName] ?? 0, strlen($fieldvalue));
232 if (!empty($value['foreign'])) {
235 'targettable' => array_keys($value['foreign'])[0],
236 'targetfield' => array_values($value['foreign'])[0]
241 array_walk_recursive($fields, function(&$value, $key) use ($lengths)
243 $value = str_pad($value, $lengths[$key], $value === '-' ? '-' : ' ');
246 $tables[] = ['name' => $name, 'comment' => $definition['comment']];
247 $content = Renderer::replaceMacros(Renderer::getMarkupTemplate('structure.tpl'), [
249 '$comment' => $definition['comment'],
250 '$fields' => $fields,
251 '$indexes' => $indexes,
252 '$foreign' => $foreign,
254 $filename = DI::basePath() . '/doc/database/db_' . $name . '.md';
255 file_put_contents($filename, $content);
258 $content = Renderer::replaceMacros(Renderer::getMarkupTemplate('tables.tpl'), [
259 '$tables' => $tables,
261 $filename = DI::basePath() . '/doc/database.md';
262 file_put_contents($filename, $content);
265 public static function printStructure(string $basePath)
267 $database = self::definition($basePath, false);
269 echo "-- ------------------------------------------\n";
270 echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n";
271 echo "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
272 echo "-- ------------------------------------------\n\n\n";
273 foreach ($database as $name => $structure) {
275 echo "-- TABLE $name\n";
277 self::createTable($name, $structure, true, false);
282 View::printStructure($basePath);
286 * Loads the database structure definition from the static/dbstructure.config.php file.
287 * On first pass, defines DB_UPDATE_VERSION constant.
289 * @see static/dbstructure.config.php
290 * @param string $basePath The base path of this application
291 * @param boolean $with_addons_structure Whether to tack on addons additional tables
295 public static function definition(string $basePath, bool $with_addons_structure = true): array
297 if (!self::$definition) {
298 if (empty($basePath)) {
299 $basePath = DI::app()->getBasePath();
302 $filename = $basePath . '/static/dbstructure.config.php';
304 if (!is_readable($filename)) {
305 throw new Exception('Missing database structure config file static/dbstructure.config.php at basePath=' . $basePath);
308 $definition = require $filename;
311 throw new Exception('Corrupted database structure config file static/dbstructure.config.php');
314 self::$definition = $definition;
316 $definition = self::$definition;
319 if ($with_addons_structure) {
320 Hook::callAll('dbstructure_definition', $definition);
327 * Get field data for the given table
329 * @param string $table Tavle to load field definitions for
330 * @param array $data data fields
331 * @return array fields for the given
333 public static function getFieldsForTable(string $table, array $data = []): array
335 $definition = DBStructure::definition('', false);
336 if (empty($definition[$table])) {
340 $fieldNames = array_keys($definition[$table]['fields']);
344 // Assign all field that are present in the table
345 foreach ($fieldNames as $field) {
346 if (isset($data[$field])) {
347 // Limit the length of varchar, varbinary, char and binrary fields
348 if (is_string($data[$field]) && preg_match("/char\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
349 $data[$field] = mb_substr($data[$field], 0, $result[1]);
350 } elseif (is_string($data[$field]) && preg_match("/binary\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
351 $data[$field] = substr($data[$field], 0, $result[1]);
353 $fields[$field] = $data[$field];
361 * Creates given table with structure
363 * @param string $name Name of table
364 * @param array $structure Structure of table
365 * @param boolean $verbose Output SQL statements
366 * @param boolean $action Whether to run the SQL commands
367 * @return Whether the SQL command ran successful
369 private static function createTable(string $name, array $structure, bool $verbose, bool $action): bool
379 foreach ($structure['fields'] as $fieldName => $field) {
380 $sql_rows[] = '`' . DBA::escape($fieldName) . '` ' . self::FieldCommand($field);
381 if (!empty($field['primary'])) {
382 $primary_keys[] = $fieldName;
384 if (!empty($field['foreign'])) {
385 $foreign_keys[$fieldName] = $field;
389 if (!empty($structure['indexes'])) {
390 foreach ($structure['indexes'] as $indexName => $fieldNames) {
391 $sql_index = self::createIndex($indexName, $fieldNames, '');
392 if (!is_null($sql_index)) {
393 $sql_rows[] = $sql_index;
398 foreach ($foreign_keys as $fieldName => $parameters) {
399 $sql_rows[] = self::foreignCommand($name, $fieldName, $parameters);
402 if (isset($structure['engine'])) {
403 $engine = ' ENGINE=' . $structure['engine'];
406 if (isset($structure['comment'])) {
407 $comment = " COMMENT='" . DBA::escape($structure['comment']) . "'";
410 $sql = implode(",\n\t", $sql_rows);
412 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
413 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
426 * Returns SQL statement for field
428 * @param array $parameters Parameters for SQL statement
429 * @param boolean $create Whether to include PRIMARY KEY statement (unused)
430 * @return string SQL statement part
432 private static function FieldCommand(array $parameters, bool $create = true): string
434 $fieldstruct = $parameters['type'];
436 if (isset($parameters['Collation'])) {
437 $fieldstruct .= ' COLLATE ' . $parameters['Collation'];
440 if (isset($parameters['not null'])) {
441 $fieldstruct .= ' NOT NULL';
444 if (isset($parameters['default'])) {
445 if (strpos(strtolower($parameters['type']), 'int') !== false) {
446 $fieldstruct .= ' DEFAULT ' . $parameters['default'];
448 $fieldstruct .= " DEFAULT '" . $parameters['default'] . "'";
451 if (isset($parameters['extra'])) {
452 $fieldstruct .= ' ' . $parameters['extra'];
455 if (isset($parameters['comment'])) {
456 $fieldstruct .= " COMMENT '" . DBA::escape($parameters['comment']) . "'";
459 /*if (($parameters['primary'] != '') && $create)
460 $fieldstruct .= ' PRIMARY KEY';*/
465 private static function createIndex(string $indexName, array $fieldNames, string $method = 'ADD')
467 $method = strtoupper(trim($method));
468 if ($method != "" && $method != "ADD") {
469 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
472 if (in_array($fieldNames[0], ["UNIQUE", "FULLTEXT"])) {
473 $index_type = array_shift($fieldNames);
474 $method .= " " . $index_type;
478 foreach ($fieldNames as $fieldName) {
483 if (preg_match('|(.+)\((\d+)\)|', $fieldName, $matches)) {
484 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
486 $names .= "`" . DBA::escape($fieldName) . "`";
490 if ($indexName == "PRIMARY") {
491 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
495 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexName), $names);
500 * Perform a database structure dryrun (means: just simulating)
504 public static function dryRun()
506 self::update(DI::app()->getBasePath(), true, false);
510 * Updates DB structure and returns eventual errors messages
512 * @param bool $enable_maintenance_mode Set the maintenance mode
513 * @param bool $verbose Display the SQL commands
515 * @return string Empty string if the update is successful, error messages otherwise
518 public static function performUpdate(bool $enable_maintenance_mode = true, bool $verbose = false)
520 if ($enable_maintenance_mode) {
521 DI::config()->set('system', 'maintenance', 1);
524 $status = self::update(DI::app()->getBasePath(), $verbose, true);
526 if ($enable_maintenance_mode) {
527 DI::config()->set('system', 'maintenance', 0);
528 DI::config()->set('system', 'maintenance_reason', '');
535 * Updates DB structure from the installation and returns eventual errors messages
537 * @param string $basePath The base path of this application
539 * @return string Empty string if the update is successful, error messages otherwise
542 public static function install(string $basePath)
544 return self::update($basePath, false, true, true);
548 * Updates DB structure and returns eventual errors messages
550 * @param string $basePath The base path of this application
551 * @param bool $verbose
552 * @param bool $action Whether to actually apply the update
553 * @param bool $install Is this the initial update during the installation?
554 * @param array $tables An array of the database tables
555 * @param array $definition An array of the definition tables
556 * @return string Empty string if the update is successful, error messages otherwise
559 private static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
561 $in_maintenance_mode = DI::config()->get('system', 'maintenance');
563 if ($action && !$install && self::isUpdating()) {
564 return DI::l10n()->t('Another database update is currently running.');
567 if ($in_maintenance_mode) {
568 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
571 // ensure that all initial values exist. This test has to be done prior and after the structure check.
572 // Prior is needed if the specific tables already exists - after is needed when they had been created.
573 self::checkInitialValues();
577 Logger::info('updating structure');
579 // Get the current structure
582 if (is_null($tables)) {
583 $tables = DBA::toArray(DBA::p("SHOW TABLES"));
586 if (DBA::isResult($tables)) {
587 foreach ($tables as $table) {
588 $table = current($table);
590 Logger::info('updating structure', ['table' => $table]);
591 $database[$table] = self::tableStructure($table);
595 // Get the definition
596 if (is_null($definition)) {
597 $definition = self::definition($basePath);
600 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
601 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
602 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
609 foreach ($definition as $name => $structure) {
610 $is_new_table = false;
612 if (!isset($database[$name])) {
613 $r = self::createTable($name, $structure, $verbose, $action);
614 if (!DBA::isResult($r)) {
615 $errors .= self::printUpdateError($name);
617 $is_new_table = true;
620 * Drop the index if it isn't present in the definition
621 * or the definition differ from current status
622 * and index name doesn't start with "local_"
624 foreach ($database[$name]["indexes"] as $indexName => $fieldNames) {
625 $current_index_definition = implode(",", $fieldNames);
626 if (isset($structure["indexes"][$indexName])) {
627 $new_index_definition = implode(",", $structure["indexes"][$indexName]);
629 $new_index_definition = "__NOT_SET__";
631 if ($current_index_definition != $new_index_definition && substr($indexName, 0, 6) != 'local_') {
632 $sql2 = self::dropIndex($indexName);
634 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
636 $sql3 .= ", " . $sql2;
640 // Compare the field structure field by field
641 foreach ($structure["fields"] as $fieldName => $parameters) {
642 if (!isset($database[$name]["fields"][$fieldName])) {
643 $sql2 = self::addTableField($fieldName, $parameters);
645 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
647 $sql3 .= ", " . $sql2;
650 // Compare the field definition
651 $field_definition = $database[$name]["fields"][$fieldName];
653 // Remove the relation data that is used for the referential integrity
654 unset($parameters['relation']);
655 unset($parameters['foreign']);
657 // We change the collation after the indexes had been changed.
658 // This is done to avoid index length problems.
659 // So here we always ensure that there is no need to change it.
660 unset($parameters['Collation']);
661 unset($field_definition['Collation']);
663 // Only update the comment when it is defined
664 if (!isset($parameters['comment'])) {
665 $parameters['comment'] = "";
668 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
669 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
670 if ($current_field_definition != $new_field_definition) {
671 $sql2 = self::modifyTableField($fieldName, $parameters);
673 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
675 $sql3 .= ", " . $sql2;
683 * Create the index if the index don't exists in database
684 * or the definition differ from the current status.
685 * Don't create keys if table is new
687 if (!$is_new_table) {
688 foreach ($structure["indexes"] as $indexName => $fieldNames) {
689 if (isset($database[$name]["indexes"][$indexName])) {
690 $current_index_definition = implode(",", $database[$name]["indexes"][$indexName]);
692 $current_index_definition = "__NOT_SET__";
694 $new_index_definition = implode(",", $fieldNames);
695 if ($current_index_definition != $new_index_definition) {
696 $sql2 = self::createIndex($indexName, $fieldNames);
700 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
702 $sql3 .= ", " . $sql2;
708 $existing_foreign_keys = $database[$name]['foreign_keys'];
711 // Compare the field structure field by field
712 foreach ($structure["fields"] as $fieldName => $parameters) {
713 if (empty($parameters['foreign'])) {
717 $constraint = self::getConstraintName($name, $fieldName, $parameters);
719 unset($existing_foreign_keys[$constraint]);
721 if (empty($database[$name]['foreign_keys'][$constraint])) {
722 $sql2 = self::addForeignKey($name, $fieldName, $parameters);
725 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
727 $sql3 .= ", " . $sql2;
732 foreach ($existing_foreign_keys as $param) {
733 $sql2 = self::dropForeignKey($param['CONSTRAINT_NAME']);
736 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
738 $sql3 .= ", " . $sql2;
742 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
743 $structurecomment = $structure["comment"] ?? '';
744 if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
745 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
748 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
750 $sql3 .= ", " . $sql2;
755 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
756 if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
757 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
760 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
762 $sql3 .= ", " . $sql2;
767 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
768 if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
769 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
772 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
774 $sql3 .= ", " . $sql2;
783 // Now have a look at the field collations
784 // Compare the field structure field by field
785 foreach ($structure["fields"] as $fieldName => $parameters) {
786 // Compare the field definition
787 $field_definition = ($database[$name]["fields"][$fieldName] ?? '') ?: ['Collation' => ''];
789 // Define the default collation if not given
790 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
791 $parameters['Collation'] = 'utf8mb4_general_ci';
793 $parameters['Collation'] = null;
796 if ($field_definition['Collation'] != $parameters['Collation']) {
797 $sql2 = self::modifyTableField($fieldName, $parameters);
798 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
799 $sql3 .= "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
801 $sql3 .= ", " . $sql2;
808 if (substr($sql3, -2, 2) != "; ") {
817 if ($in_maintenance_mode) {
818 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
822 if (!DBA::isResult($r)) {
823 $errors .= self::printUpdateError($sql3);
829 View::create(false, $action);
831 self::checkInitialValues();
833 if ($action && !$install) {
835 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
837 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
844 private static function tableStructure($table)
846 // This query doesn't seem to be executable as a prepared statement
847 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
849 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
850 ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
851 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
852 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
853 DBA::databaseName(), $table]);
855 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
856 ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
857 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
858 DBA::databaseName(), $table]);
860 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
861 ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
862 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
863 DBA::databaseName(), $table]);
869 if (DBA::isResult($foreign_keys)) {
870 foreach ($foreign_keys as $foreign_key) {
871 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
872 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
873 $foreigndata[$constraint] = $foreign_key;
877 if (DBA::isResult($indexes)) {
878 foreach ($indexes as $index) {
879 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
880 $indexdata[$index["Key_name"]] = ["UNIQUE"];
883 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
884 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
887 $column = $index["Column_name"];
889 if ($index["Sub_part"] != "") {
890 $column .= "(" . $index["Sub_part"] . ")";
893 $indexdata[$index["Key_name"]][] = $column;
898 if (DBA::isResult($fields)) {
899 foreach ($fields as $field) {
900 $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)'];
901 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
902 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
904 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
906 if ($field['IS_NULLABLE'] == 'NO') {
907 $fielddata[$field['COLUMN_NAME']]['not null'] = true;
910 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
911 $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
914 if (!empty($field['EXTRA'])) {
915 $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
918 if ($field['COLUMN_KEY'] == 'PRI') {
919 $fielddata[$field['COLUMN_NAME']]['primary'] = true;
922 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
923 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
928 'fields' => $fielddata,
929 'indexes' => $indexdata,
930 'foreign_keys' => $foreigndata,
931 'table_status' => $table_status
935 private static function dropIndex(string $indexName): string
937 return sprintf("DROP INDEX `%s`", DBA::escape($indexName));
940 private static function addTableField(string $fieldName, array $parameters): string
942 return sprintf("ADD `%s` %s", DBA::escape($fieldName), self::FieldCommand($parameters));
945 private static function modifyTableField(string $fieldName, array $parameters): string
947 return sprintf("MODIFY `%s` %s", DBA::escape($fieldName), self::FieldCommand($parameters, false));
950 private static function getConstraintName(string $tableName, string $fieldName, array $parameters): string
952 $foreign_table = array_keys($parameters['foreign'])[0];
953 $foreign_field = array_values($parameters['foreign'])[0];
955 return $tableName . '-' . $fieldName. '-' . $foreign_table. '-' . $foreign_field;
958 private static function foreignCommand(string $tableName, string $fieldName, array $parameters) {
959 $foreign_table = array_keys($parameters['foreign'])[0];
960 $foreign_field = array_values($parameters['foreign'])[0];
962 $sql = "FOREIGN KEY (`" . $fieldName . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
964 if (!empty($parameters['foreign']['on update'])) {
965 $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
967 $sql .= " ON UPDATE RESTRICT";
970 if (!empty($parameters['foreign']['on delete'])) {
971 $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
973 $sql .= " ON DELETE CASCADE";
979 private static function addForeignKey(string $tableName, string $fieldName, array $parameters): string
981 return sprintf("ADD %s", self::foreignCommand($tableName, $fieldName, $parameters));
984 private static function dropForeignKey(string $constraint): string
986 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
990 * Renames columns or the primary key of a table
992 * @todo You cannot rename a primary key if "auto increment" is set
994 * @param string $table Table name
995 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
996 * Syntax for Primary Key: [ $col1, $col2, ...]
997 * @param int $type The type of renaming (Default is Column)
999 * @return boolean Was the renaming successful?
1002 public static function rename(string $table, array $columns, int $type = self::RENAME_COLUMN): bool
1004 if (empty($table) || empty($columns)) {
1008 if (!is_array($columns)) {
1012 $table = DBA::escape($table);
1014 $sql = "ALTER TABLE `" . $table . "`";
1016 case self::RENAME_COLUMN:
1017 if (!self::existsColumn($table, array_keys($columns))) {
1020 $sql .= implode(',', array_map(
1021 function ($to, $from) {
1022 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
1025 array_keys($columns)
1028 case self::RENAME_PRIMARY_KEY:
1029 if (!self::existsColumn($table, $columns)) {
1032 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
1040 $stmt = DBA::p($sql);
1042 if (is_bool($stmt)) {
1054 * Check if the columns of the table exists
1056 * @param string $table Table name
1057 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
1059 * @return boolean Does the table exist?
1062 public static function existsColumn($table, $columns = [])
1064 if (empty($table)) {
1068 if (is_null($columns) || empty($columns)) {
1069 return self::existsTable($table);
1072 $table = DBA::escape($table);
1074 foreach ($columns as $column) {
1075 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
1077 $stmt = DBA::p($sql);
1079 if (is_bool($stmt)) {
1082 $retval = (DBA::numRows($stmt) > 0);
1096 * Check if a foreign key exists for the given table field
1098 * @param string $table Table name
1099 * @param string $field Field name
1100 * @return boolean Wether a foreign key exists
1102 public static function existsForeignKeyForField(string $table, string $field): bool
1104 return DBA::exists(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
1105 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
1106 DBA::databaseName(), $table, $field]);
1110 * Check if a table exists
1112 * @param string $table Single table name (please loop yourself)
1113 * @return boolean Does the table exist?
1116 public static function existsTable(string $table): bool
1118 if (empty($table)) {
1122 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
1124 return DBA::exists(['information_schema' => 'tables'], $condition);
1128 * Returns the columns of a table
1130 * @param string $table Table name
1132 * @return array An array of the table columns
1135 public static function getColumns(string $table): array
1137 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
1138 return DBA::toArray($stmtColumns);
1142 * Check if initial database values do exist - or create them
1144 * @param bool $verbose Whether to output messages
1147 public static function checkInitialValues(bool $verbose = false)
1149 if (self::existsTable('verb')) {
1150 if (!DBA::exists('verb', ['id' => 1])) {
1151 foreach (Item::ACTIVITIES as $index => $activity) {
1152 DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], Database::INSERT_IGNORE);
1155 echo "verb: activities added\n";
1157 } elseif ($verbose) {
1158 echo "verb: activities already added\n";
1161 if (!DBA::exists('verb', ['id' => 0])) {
1162 DBA::insert('verb', ['name' => '']);
1163 $lastid = DBA::lastInsertId();
1165 DBA::update('verb', ['id' => 0], ['id' => $lastid]);
1167 echo "Zero verb added\n";
1170 } elseif ($verbose) {
1171 echo "Zero verb already added\n";
1173 } elseif ($verbose) {
1174 echo "verb: Table not found\n";
1177 if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) {
1180 "page-flags" => User::PAGE_FLAGS_SOAPBOX,
1181 "account-type" => User::ACCOUNT_TYPE_RELAY,
1183 DBA::insert('user', $user);
1184 $lastid = DBA::lastInsertId();
1186 DBA::update('user', ['uid' => 0], ['uid' => $lastid]);
1188 echo "Zero user added\n";
1191 } elseif (self::existsTable('user') && $verbose) {
1192 echo "Zero user already added\n";
1193 } elseif ($verbose) {
1194 echo "user: Table not found\n";
1197 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
1198 DBA::insert('contact', ['nurl' => '']);
1199 $lastid = DBA::lastInsertId();
1201 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
1203 echo "Zero contact added\n";
1206 } elseif (self::existsTable('contact') && $verbose) {
1207 echo "Zero contact already added\n";
1208 } elseif ($verbose) {
1209 echo "contact: Table not found\n";
1212 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
1213 DBA::insert('tag', ['name' => '']);
1214 $lastid = DBA::lastInsertId();
1216 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
1218 echo "Zero tag added\n";
1221 } elseif (self::existsTable('tag') && $verbose) {
1222 echo "Zero tag already added\n";
1223 } elseif ($verbose) {
1224 echo "tag: Table not found\n";
1227 if (self::existsTable('permissionset')) {
1228 if (!DBA::exists('permissionset', ['id' => 0])) {
1229 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
1230 $lastid = DBA::lastInsertId();
1232 DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
1234 echo "Zero permissionset added\n";
1237 } elseif ($verbose) {
1238 echo "Zero permissionset already added\n";
1240 if (self::existsTable('item') && !self::existsForeignKeyForField('item', 'psid')) {
1241 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
1242 LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
1243 WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
1244 while ($set = DBA::fetch($sets)) {
1245 if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
1246 $owner = User::getOwnerDataById($set['uid']);
1248 $permission = '<' . $owner['id'] . '>';
1255 $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
1256 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
1257 DBA::insert('permissionset', $fields);
1261 } elseif ($verbose) {
1262 echo "permissionset: Table not found\n";
1265 if (self::existsTable('tokens') && self::existsTable('clients') && !self::existsForeignKeyForField('tokens', 'client_id')) {
1266 $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
1267 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
1268 WHERE `clients`.`client_id` IS NULL");
1269 while ($token = DBA::fetch($tokens)) {
1270 DBA::delete('tokens', ['id' => $token['id']]);
1272 DBA::close($tokens);
1277 * Checks if a database update is currently running
1281 private static function isUpdating(): bool
1285 $processes = DBA::select(['information_schema' => 'processlist'], ['info'],
1286 ['db' => DBA::databaseName(), 'command' => ['Query', 'Execute']]);
1288 while ($process = DBA::fetch($processes)) {
1289 $parts = explode(' ', $process['info']);
1290 if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
1295 DBA::close($processes);