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 return sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexName), $names);
499 * Perform a database structure dryrun (means: just simulating)
503 public static function dryRun()
505 self::update(DI::app()->getBasePath(), true, false);
509 * Updates DB structure and returns eventual errors messages
511 * @param bool $enable_maintenance_mode Set the maintenance mode
512 * @param bool $verbose Display the SQL commands
514 * @return string Empty string if the update is successful, error messages otherwise
517 public static function performUpdate(bool $enable_maintenance_mode = true, bool $verbose = false): string
519 if ($enable_maintenance_mode) {
520 DI::config()->set('system', 'maintenance', 1);
523 $status = self::update(DI::app()->getBasePath(), $verbose, true);
525 if ($enable_maintenance_mode) {
526 DI::config()->set('system', 'maintenance', 0);
527 DI::config()->set('system', 'maintenance_reason', '');
534 * Updates DB structure from the installation and returns eventual errors messages
536 * @param string $basePath The base path of this application
538 * @return string Empty string if the update is successful, error messages otherwise
541 public static function install(string $basePath): string
543 return self::update($basePath, false, true, true);
547 * Updates DB structure and returns eventual errors messages
549 * @param string $basePath The base path of this application
550 * @param bool $verbose
551 * @param bool $action Whether to actually apply the update
552 * @param bool $install Is this the initial update during the installation?
553 * @param array $tables An array of the database tables
554 * @param array $definition An array of the definition tables
555 * @return string Empty string if the update is successful, error messages otherwise
558 private static function update(string $basePath, bool $verbose, bool $action, bool $install = false, array $tables = null, array $definition = null): string
560 $in_maintenance_mode = DI::config()->get('system', 'maintenance');
562 if ($action && !$install && self::isUpdating()) {
563 return DI::l10n()->t('Another database update is currently running.');
566 if ($in_maintenance_mode) {
567 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
570 // ensure that all initial values exist. This test has to be done prior and after the structure check.
571 // Prior is needed if the specific tables already exists - after is needed when they had been created.
572 self::checkInitialValues();
576 Logger::info('updating structure');
578 // Get the current structure
581 if (is_null($tables)) {
582 $tables = DBA::toArray(DBA::p("SHOW TABLES"));
585 if (DBA::isResult($tables)) {
586 foreach ($tables as $table) {
587 $table = current($table);
589 Logger::info('updating structure', ['table' => $table]);
590 $database[$table] = self::tableStructure($table);
594 // Get the definition
595 if (is_null($definition)) {
596 $definition = self::definition($basePath);
599 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
600 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
601 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
608 foreach ($definition as $name => $structure) {
609 $is_new_table = false;
611 if (!isset($database[$name])) {
612 $r = self::createTable($name, $structure, $verbose, $action);
613 if (!DBA::isResult($r)) {
614 $errors .= self::printUpdateError($name);
616 $is_new_table = true;
619 * Drop the index if it isn't present in the definition
620 * or the definition differ from current status
621 * and index name doesn't start with "local_"
623 foreach ($database[$name]["indexes"] as $indexName => $fieldNames) {
624 $current_index_definition = implode(",", $fieldNames);
625 if (isset($structure["indexes"][$indexName])) {
626 $new_index_definition = implode(",", $structure["indexes"][$indexName]);
628 $new_index_definition = "__NOT_SET__";
630 if ($current_index_definition != $new_index_definition && substr($indexName, 0, 6) != 'local_') {
631 $sql2 = self::dropIndex($indexName);
633 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
635 $sql3 .= ", " . $sql2;
639 // Compare the field structure field by field
640 foreach ($structure["fields"] as $fieldName => $parameters) {
641 if (!isset($database[$name]["fields"][$fieldName])) {
642 $sql2 = self::addTableField($fieldName, $parameters);
644 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
646 $sql3 .= ", " . $sql2;
649 // Compare the field definition
650 $field_definition = $database[$name]["fields"][$fieldName];
652 // Remove the relation data that is used for the referential integrity
653 unset($parameters['relation']);
654 unset($parameters['foreign']);
656 // We change the collation after the indexes had been changed.
657 // This is done to avoid index length problems.
658 // So here we always ensure that there is no need to change it.
659 unset($parameters['Collation']);
660 unset($field_definition['Collation']);
662 // Only update the comment when it is defined
663 if (!isset($parameters['comment'])) {
664 $parameters['comment'] = "";
667 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
668 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
669 if ($current_field_definition != $new_field_definition) {
670 $sql2 = self::modifyTableField($fieldName, $parameters);
672 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
674 $sql3 .= ", " . $sql2;
682 * Create the index if the index don't exists in database
683 * or the definition differ from the current status.
684 * Don't create keys if table is new
686 if (!$is_new_table) {
687 foreach ($structure["indexes"] as $indexName => $fieldNames) {
688 if (isset($database[$name]["indexes"][$indexName])) {
689 $current_index_definition = implode(",", $database[$name]["indexes"][$indexName]);
691 $current_index_definition = "__NOT_SET__";
693 $new_index_definition = implode(",", $fieldNames);
694 if ($current_index_definition != $new_index_definition) {
695 $sql2 = self::createIndex($indexName, $fieldNames);
699 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
701 $sql3 .= ", " . $sql2;
707 $existing_foreign_keys = $database[$name]['foreign_keys'];
710 // Compare the field structure field by field
711 foreach ($structure["fields"] as $fieldName => $parameters) {
712 if (empty($parameters['foreign'])) {
716 $constraint = self::getConstraintName($name, $fieldName, $parameters);
718 unset($existing_foreign_keys[$constraint]);
720 if (empty($database[$name]['foreign_keys'][$constraint])) {
721 $sql2 = self::addForeignKey($name, $fieldName, $parameters);
724 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
726 $sql3 .= ", " . $sql2;
731 foreach ($existing_foreign_keys as $param) {
732 $sql2 = self::dropForeignKey($param['CONSTRAINT_NAME']);
735 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
737 $sql3 .= ", " . $sql2;
741 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
742 $structurecomment = $structure["comment"] ?? '';
743 if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
744 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
747 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
749 $sql3 .= ", " . $sql2;
754 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
755 if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
756 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
759 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
761 $sql3 .= ", " . $sql2;
766 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
767 if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
768 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
771 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
773 $sql3 .= ", " . $sql2;
782 // Now have a look at the field collations
783 // Compare the field structure field by field
784 foreach ($structure["fields"] as $fieldName => $parameters) {
785 // Compare the field definition
786 $field_definition = ($database[$name]["fields"][$fieldName] ?? '') ?: ['Collation' => ''];
788 // Define the default collation if not given
789 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
790 $parameters['Collation'] = 'utf8mb4_general_ci';
792 $parameters['Collation'] = null;
795 if ($field_definition['Collation'] != $parameters['Collation']) {
796 $sql2 = self::modifyTableField($fieldName, $parameters);
797 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
798 $sql3 .= "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
800 $sql3 .= ", " . $sql2;
807 if (substr($sql3, -2, 2) != "; ") {
816 if ($in_maintenance_mode) {
817 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
821 if (!DBA::isResult($r)) {
822 $errors .= self::printUpdateError($sql3);
828 View::create(false, $action);
830 self::checkInitialValues();
832 if ($action && !$install) {
834 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
836 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
844 * Returns an array with table structure information
846 * @param string $table Name of table
847 * @return array Table structure information
849 private static function tableStructure(string $table): array
851 // This query doesn't seem to be executable as a prepared statement
852 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
854 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
855 ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
856 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
857 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
858 DBA::databaseName(), $table]);
860 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
861 ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
862 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
863 DBA::databaseName(), $table]);
865 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
866 ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
867 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
868 DBA::databaseName(), $table]);
874 if (DBA::isResult($foreign_keys)) {
875 foreach ($foreign_keys as $foreign_key) {
876 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
877 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
878 $foreigndata[$constraint] = $foreign_key;
882 if (DBA::isResult($indexes)) {
883 foreach ($indexes as $index) {
884 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
885 $indexdata[$index["Key_name"]] = ["UNIQUE"];
888 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
889 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
892 $column = $index["Column_name"];
894 if ($index["Sub_part"] != "") {
895 $column .= "(" . $index["Sub_part"] . ")";
898 $indexdata[$index["Key_name"]][] = $column;
903 if (DBA::isResult($fields)) {
904 foreach ($fields as $field) {
905 $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)'];
906 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
907 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
909 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
911 if ($field['IS_NULLABLE'] == 'NO') {
912 $fielddata[$field['COLUMN_NAME']]['not null'] = true;
915 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
916 $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
919 if (!empty($field['EXTRA'])) {
920 $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
923 if ($field['COLUMN_KEY'] == 'PRI') {
924 $fielddata[$field['COLUMN_NAME']]['primary'] = true;
927 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
928 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
933 'fields' => $fielddata,
934 'indexes' => $indexdata,
935 'foreign_keys' => $foreigndata,
936 'table_status' => $table_status
940 private static function dropIndex(string $indexName): string
942 return sprintf("DROP INDEX `%s`", DBA::escape($indexName));
945 private static function addTableField(string $fieldName, array $parameters): string
947 return sprintf("ADD `%s` %s", DBA::escape($fieldName), self::FieldCommand($parameters));
950 private static function modifyTableField(string $fieldName, array $parameters): string
952 return sprintf("MODIFY `%s` %s", DBA::escape($fieldName), self::FieldCommand($parameters, false));
955 private static function getConstraintName(string $tableName, string $fieldName, array $parameters): string
957 $foreign_table = array_keys($parameters['foreign'])[0];
958 $foreign_field = array_values($parameters['foreign'])[0];
960 return $tableName . '-' . $fieldName. '-' . $foreign_table. '-' . $foreign_field;
963 private static function foreignCommand(string $tableName, string $fieldName, array $parameters) {
964 $foreign_table = array_keys($parameters['foreign'])[0];
965 $foreign_field = array_values($parameters['foreign'])[0];
967 $sql = "FOREIGN KEY (`" . $fieldName . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
969 if (!empty($parameters['foreign']['on update'])) {
970 $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
972 $sql .= " ON UPDATE RESTRICT";
975 if (!empty($parameters['foreign']['on delete'])) {
976 $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
978 $sql .= " ON DELETE CASCADE";
984 private static function addForeignKey(string $tableName, string $fieldName, array $parameters): string
986 return sprintf("ADD %s", self::foreignCommand($tableName, $fieldName, $parameters));
989 private static function dropForeignKey(string $constraint): string
991 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
995 * Renames columns or the primary key of a table
997 * @todo You cannot rename a primary key if "auto increment" is set
999 * @param string $table Table name
1000 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
1001 * Syntax for Primary Key: [ $col1, $col2, ...]
1002 * @param int $type The type of renaming (Default is Column)
1004 * @return boolean Was the renaming successful?
1007 public static function rename(string $table, array $columns, int $type = self::RENAME_COLUMN): bool
1009 if (empty($table) || empty($columns)) {
1013 if (!is_array($columns)) {
1017 $table = DBA::escape($table);
1019 $sql = "ALTER TABLE `" . $table . "`";
1021 case self::RENAME_COLUMN:
1022 if (!self::existsColumn($table, array_keys($columns))) {
1025 $sql .= implode(',', array_map(
1026 function ($to, $from) {
1027 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
1030 array_keys($columns)
1033 case self::RENAME_PRIMARY_KEY:
1034 if (!self::existsColumn($table, $columns)) {
1037 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
1045 $stmt = DBA::p($sql);
1047 if (is_bool($stmt)) {
1059 * Check if the columns of the table exists
1061 * @param string $table Table name
1062 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
1064 * @return boolean Does the table exist?
1067 public static function existsColumn($table, $columns = [])
1069 if (empty($table)) {
1073 if (is_null($columns) || empty($columns)) {
1074 return self::existsTable($table);
1077 $table = DBA::escape($table);
1079 foreach ($columns as $column) {
1080 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
1082 $stmt = DBA::p($sql);
1084 if (is_bool($stmt)) {
1087 $retval = (DBA::numRows($stmt) > 0);
1101 * Check if a foreign key exists for the given table field
1103 * @param string $table Table name
1104 * @param string $field Field name
1105 * @return boolean Wether a foreign key exists
1107 public static function existsForeignKeyForField(string $table, string $field): bool
1109 return DBA::exists(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
1110 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
1111 DBA::databaseName(), $table, $field]);
1115 * Check if a table exists
1117 * @param string $table Single table name (please loop yourself)
1118 * @return boolean Does the table exist?
1121 public static function existsTable(string $table): bool
1123 if (empty($table)) {
1127 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
1129 return DBA::exists(['information_schema' => 'tables'], $condition);
1133 * Returns the columns of a table
1135 * @param string $table Table name
1137 * @return array An array of the table columns
1140 public static function getColumns(string $table): array
1142 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
1143 return DBA::toArray($stmtColumns);
1147 * Check if initial database values do exist - or create them
1149 * @param bool $verbose Whether to output messages
1152 public static function checkInitialValues(bool $verbose = false)
1154 if (self::existsTable('verb')) {
1155 if (!DBA::exists('verb', ['id' => 1])) {
1156 foreach (Item::ACTIVITIES as $index => $activity) {
1157 DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], Database::INSERT_IGNORE);
1160 echo "verb: activities added\n";
1162 } elseif ($verbose) {
1163 echo "verb: activities already added\n";
1166 if (!DBA::exists('verb', ['id' => 0])) {
1167 DBA::insert('verb', ['name' => '']);
1168 $lastid = DBA::lastInsertId();
1170 DBA::update('verb', ['id' => 0], ['id' => $lastid]);
1172 echo "Zero verb added\n";
1175 } elseif ($verbose) {
1176 echo "Zero verb already added\n";
1178 } elseif ($verbose) {
1179 echo "verb: Table not found\n";
1182 if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) {
1185 "page-flags" => User::PAGE_FLAGS_SOAPBOX,
1186 "account-type" => User::ACCOUNT_TYPE_RELAY,
1188 DBA::insert('user', $user);
1189 $lastid = DBA::lastInsertId();
1191 DBA::update('user', ['uid' => 0], ['uid' => $lastid]);
1193 echo "Zero user added\n";
1196 } elseif (self::existsTable('user') && $verbose) {
1197 echo "Zero user already added\n";
1198 } elseif ($verbose) {
1199 echo "user: Table not found\n";
1202 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
1203 DBA::insert('contact', ['nurl' => '']);
1204 $lastid = DBA::lastInsertId();
1206 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
1208 echo "Zero contact added\n";
1211 } elseif (self::existsTable('contact') && $verbose) {
1212 echo "Zero contact already added\n";
1213 } elseif ($verbose) {
1214 echo "contact: Table not found\n";
1217 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
1218 DBA::insert('tag', ['name' => '']);
1219 $lastid = DBA::lastInsertId();
1221 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
1223 echo "Zero tag added\n";
1226 } elseif (self::existsTable('tag') && $verbose) {
1227 echo "Zero tag already added\n";
1228 } elseif ($verbose) {
1229 echo "tag: Table not found\n";
1232 if (self::existsTable('permissionset')) {
1233 if (!DBA::exists('permissionset', ['id' => 0])) {
1234 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
1235 $lastid = DBA::lastInsertId();
1237 DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
1239 echo "Zero permissionset added\n";
1242 } elseif ($verbose) {
1243 echo "Zero permissionset already added\n";
1245 if (self::existsTable('item') && !self::existsForeignKeyForField('item', 'psid')) {
1246 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
1247 LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
1248 WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
1249 while ($set = DBA::fetch($sets)) {
1250 if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
1251 $owner = User::getOwnerDataById($set['uid']);
1253 $permission = '<' . $owner['id'] . '>';
1260 $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
1261 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
1262 DBA::insert('permissionset', $fields);
1266 } elseif ($verbose) {
1267 echo "permissionset: Table not found\n";
1270 if (self::existsTable('tokens') && self::existsTable('clients') && !self::existsForeignKeyForField('tokens', 'client_id')) {
1271 $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
1272 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
1273 WHERE `clients`.`client_id` IS NULL");
1274 while ($token = DBA::fetch($tokens)) {
1275 DBA::delete('tokens', ['id' => $token['id']]);
1277 DBA::close($tokens);
1282 * Checks if a database update is currently running
1286 private static function isUpdating(): bool
1290 $processes = DBA::select(['information_schema' => 'processlist'], ['info'],
1291 ['db' => DBA::databaseName(), 'command' => ['Query', 'Execute']]);
1293 while ($process = DBA::fetch($processes)) {
1294 $parts = explode(' ', $process['info']);
1295 if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
1300 DBA::close($processes);