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'];
86 $tables = DBA::selectToArray(['INFORMATION_SCHEMA' => 'TABLES'], ['TABLE_NAME'],
87 ['TABLE_SCHEMA' => DBA::databaseName(), 'TABLE_TYPE' => 'BASE TABLE']);
90 echo DI::l10n()->t('No unused tables found.');
95 echo DI::l10n()->t('These tables are not used for friendica and will be deleted when you execute "dbstructure drop -e":') . "\n\n";
98 foreach ($tables as $table) {
99 if (in_array($table['TABLE_NAME'], $old_tables)) {
101 $sql = 'DROP TABLE ' . DBA::quoteIdentifier($table['TABLE_NAME']) . ';';
104 $result = DBA::e($sql);
105 if (!DBA::isResult($result)) {
106 self::printUpdateError($sql);
109 echo $table['TABLE_NAME'] . "\n";
116 * Converts all tables from MyISAM/InnoDB Antelope to InnoDB Barracuda
118 public static function convertToInnoDB()
120 $tables = DBA::selectToArray(
121 ['information_schema' => 'tables'],
123 ['engine' => 'MyISAM', 'table_schema' => DBA::databaseName()]
126 $tables = array_merge($tables, DBA::selectToArray(
127 ['information_schema' => 'tables'],
129 ['engine' => 'InnoDB', 'ROW_FORMAT' => ['COMPACT', 'REDUNDANT'], 'table_schema' => DBA::databaseName()]
132 if (!DBA::isResult($tables)) {
133 echo DI::l10n()->t('There are no tables on MyISAM or InnoDB with the Antelope file format.') . "\n";
137 foreach ($tables AS $table) {
138 $sql = "ALTER TABLE " . DBA::quoteIdentifier($table['table_name']) . " ENGINE=InnoDB ROW_FORMAT=DYNAMIC;";
141 $result = DBA::e($sql);
142 if (!DBA::isResult($result)) {
143 self::printUpdateError($sql);
149 * Print out database error messages
151 * @param string $message Message to be added to the error message
153 * @return string Error message
155 private static function printUpdateError($message)
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()
165 Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
168 foreach (self::definition(null) as $name => $definition) {
171 foreach ($definition['fields'] as $key => $value) {
173 $field['name'] = $key;
174 $field['comment'] = $value['comment'] ?? '';
175 $field['type'] = $value['type'];
176 $field['null'] = ($value['not null'] ?? false) ? 'NO' : 'YES';
177 $field['primary'] = ($value['primary'] ?? false) ? 'PRI' : '';
178 $field['default'] = $value['default'] ?? 'NULL';
179 $field['extra'] = $value['extra'] ?? '';
181 foreach ($field as $fieldname => $fieldvalue) {
182 $lengths[$fieldname] = max($lengths[$fieldname] ?? 0, strlen($fieldvalue));
187 array_walk_recursive($fields, function(&$value, $key) use ($lengths)
189 $value = str_pad($value, $lengths[$key]);
192 $tables[] = ['name' => $name, 'comment' => $definition['comment']];
193 $content = Renderer::replaceMacros(Renderer::getMarkupTemplate('structure.tpl'), [
195 '$comment' => $definition['comment'],
196 '$fields' => $fields,
198 $filename = DI::basePath() . '/doc/database/db_' . $name . '.md';
199 file_put_contents($filename, $content);
202 $content = Renderer::replaceMacros(Renderer::getMarkupTemplate('tables.tpl'), [
203 '$tables' => $tables,
205 $filename = DI::basePath() . '/doc/database.md';
206 file_put_contents($filename, $content);
209 public static function printStructure($basePath)
211 $database = self::definition($basePath, false);
213 echo "-- ------------------------------------------\n";
214 echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n";
215 echo "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
216 echo "-- ------------------------------------------\n\n\n";
217 foreach ($database AS $name => $structure) {
219 echo "-- TABLE $name\n";
221 self::createTable($name, $structure, true, false);
226 View::printStructure($basePath);
230 * Loads the database structure definition from the static/dbstructure.config.php file.
231 * On first pass, defines DB_UPDATE_VERSION constant.
233 * @see static/dbstructure.config.php
234 * @param boolean $with_addons_structure Whether to tack on addons additional tables
235 * @param string $basePath The base path of this application
239 public static function definition($basePath, $with_addons_structure = true)
241 if (!self::$definition) {
242 if (empty($basePath)) {
243 $basePath = DI::app()->getBasePath();
246 $filename = $basePath . '/static/dbstructure.config.php';
248 if (!is_readable($filename)) {
249 throw new Exception('Missing database structure config file static/dbstructure.config.php');
252 $definition = require $filename;
255 throw new Exception('Corrupted database structure config file static/dbstructure.config.php');
258 self::$definition = $definition;
260 $definition = self::$definition;
263 if ($with_addons_structure) {
264 Hook::callAll('dbstructure_definition', $definition);
271 * Get field data for the given table
273 * @param string $table
274 * @param array $data data fields
275 * @return array fields for the given
277 public static function getFieldsForTable(string $table, array $data = [])
279 $definition = DBStructure::definition('', false);
280 if (empty($definition[$table])) {
284 $fieldnames = array_keys($definition[$table]['fields']);
288 // Assign all field that are present in the table
289 foreach ($fieldnames as $field) {
290 if (isset($data[$field])) {
291 // Limit the length of varchar, varbinary, char and binrary fields
292 if (is_string($data[$field]) && preg_match("/char\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
293 $data[$field] = mb_substr($data[$field], 0, $result[1]);
294 } elseif (is_string($data[$field]) && preg_match("/binary\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
295 $data[$field] = substr($data[$field], 0, $result[1]);
297 $fields[$field] = $data[$field];
304 private static function createTable($name, $structure, $verbose, $action)
314 foreach ($structure["fields"] AS $fieldname => $field) {
315 $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
316 if (!empty($field['primary'])) {
317 $primary_keys[] = $fieldname;
319 if (!empty($field['foreign'])) {
320 $foreign_keys[$fieldname] = $field;
324 if (!empty($structure["indexes"])) {
325 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
326 $sql_index = self::createIndex($indexname, $fieldnames, "");
327 if (!is_null($sql_index)) {
328 $sql_rows[] = $sql_index;
333 foreach ($foreign_keys AS $fieldname => $parameters) {
334 $sql_rows[] = self::foreignCommand($name, $fieldname, $parameters);
337 if (isset($structure["engine"])) {
338 $engine = " ENGINE=" . $structure["engine"];
341 if (isset($structure["comment"])) {
342 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
345 $sql = implode(",\n\t", $sql_rows);
347 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
348 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
360 private static function FieldCommand($parameters, $create = true)
362 $fieldstruct = $parameters["type"];
364 if (isset($parameters["Collation"])) {
365 $fieldstruct .= " COLLATE " . $parameters["Collation"];
368 if (isset($parameters["not null"])) {
369 $fieldstruct .= " NOT NULL";
372 if (isset($parameters["default"])) {
373 if (strpos(strtolower($parameters["type"]), "int") !== false) {
374 $fieldstruct .= " DEFAULT " . $parameters["default"];
376 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
379 if (isset($parameters["extra"])) {
380 $fieldstruct .= " " . $parameters["extra"];
383 if (isset($parameters["comment"])) {
384 $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
387 /*if (($parameters["primary"] != "") && $create)
388 $fieldstruct .= " PRIMARY KEY";*/
390 return ($fieldstruct);
393 private static function createIndex($indexname, $fieldnames, $method = "ADD")
395 $method = strtoupper(trim($method));
396 if ($method != "" && $method != "ADD") {
397 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
400 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
401 $index_type = array_shift($fieldnames);
402 $method .= " " . $index_type;
406 foreach ($fieldnames AS $fieldname) {
411 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
412 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
414 $names .= "`" . DBA::escape($fieldname) . "`";
418 if ($indexname == "PRIMARY") {
419 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
423 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
428 * Perform a database structure dryrun (means: just simulating)
432 public static function dryRun()
434 self::update(DI::app()->getBasePath(), true, false);
438 * Updates DB structure and returns eventual errors messages
440 * @param bool $enable_maintenance_mode Set the maintenance mode
441 * @param bool $verbose Display the SQL commands
443 * @return string Empty string if the update is successful, error messages otherwise
446 public static function performUpdate(bool $enable_maintenance_mode = true, bool $verbose = false)
448 if ($enable_maintenance_mode) {
449 DI::config()->set('system', 'maintenance', 1);
452 $status = self::update(DI::app()->getBasePath(), $verbose, true);
454 if ($enable_maintenance_mode) {
455 DI::config()->set('system', 'maintenance', 0);
456 DI::config()->set('system', 'maintenance_reason', '');
463 * Updates DB structure from the installation and returns eventual errors messages
465 * @param string $basePath The base path of this application
467 * @return string Empty string if the update is successful, error messages otherwise
470 public static function install(string $basePath)
472 return self::update($basePath, false, true, true);
476 * Updates DB structure and returns eventual errors messages
478 * @param string $basePath The base path of this application
479 * @param bool $verbose
480 * @param bool $action Whether to actually apply the update
481 * @param bool $install Is this the initial update during the installation?
482 * @param array $tables An array of the database tables
483 * @param array $definition An array of the definition tables
484 * @return string Empty string if the update is successful, error messages otherwise
487 private static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
489 $in_maintenance_mode = DI::config()->get('system', 'maintenance');
491 if ($action && !$install && self::isUpdating()) {
492 return DI::l10n()->t('Another database update is currently running.');
495 if ($in_maintenance_mode) {
496 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
499 // ensure that all initial values exist. This test has to be done prior and after the structure check.
500 // Prior is needed if the specific tables already exists - after is needed when they had been created.
501 self::checkInitialValues();
505 Logger::info('updating structure');
507 // Get the current structure
510 if (is_null($tables)) {
511 $tables = DBA::toArray(DBA::p("SHOW TABLES"));
514 if (DBA::isResult($tables)) {
515 foreach ($tables AS $table) {
516 $table = current($table);
518 Logger::info('updating structure', ['table' => $table]);
519 $database[$table] = self::tableStructure($table);
523 // Get the definition
524 if (is_null($definition)) {
525 $definition = self::definition($basePath);
528 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
529 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
530 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
537 foreach ($definition AS $name => $structure) {
538 $is_new_table = false;
543 if (!isset($database[$name])) {
544 $r = self::createTable($name, $structure, $verbose, $action);
545 if (!DBA::isResult($r)) {
546 $errors .= self::printUpdateError($name);
548 $is_new_table = true;
550 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
551 if (isset($database[$name]["indexes"][$indexname])) {
552 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
554 $current_index_definition = "__NOT_SET__";
556 $new_index_definition = implode(",", $fieldnames);
557 if ($current_index_definition != $new_index_definition) {
558 if ($fieldnames[0] == "UNIQUE") {
561 $temp_name = "temp-" . $name;
568 * Drop the index if it isn't present in the definition
569 * or the definition differ from current status
570 * and index name doesn't start with "local_"
572 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
573 $current_index_definition = implode(",", $fieldnames);
574 if (isset($structure["indexes"][$indexname])) {
575 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
577 $new_index_definition = "__NOT_SET__";
579 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
580 $sql2 = self::dropIndex($indexname);
582 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
584 $sql3 .= ", " . $sql2;
588 // Compare the field structure field by field
589 foreach ($structure["fields"] AS $fieldname => $parameters) {
590 if (!isset($database[$name]["fields"][$fieldname])) {
591 $sql2 = self::addTableField($fieldname, $parameters);
593 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
595 $sql3 .= ", " . $sql2;
598 // Compare the field definition
599 $field_definition = $database[$name]["fields"][$fieldname];
601 // Remove the relation data that is used for the referential integrity
602 unset($parameters['relation']);
603 unset($parameters['foreign']);
605 // We change the collation after the indexes had been changed.
606 // This is done to avoid index length problems.
607 // So here we always ensure that there is no need to change it.
608 unset($parameters['Collation']);
609 unset($field_definition['Collation']);
611 // Only update the comment when it is defined
612 if (!isset($parameters['comment'])) {
613 $parameters['comment'] = "";
616 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
617 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
618 if ($current_field_definition != $new_field_definition) {
619 $sql2 = self::modifyTableField($fieldname, $parameters);
621 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
623 $sql3 .= ", " . $sql2;
631 * Create the index if the index don't exists in database
632 * or the definition differ from the current status.
633 * Don't create keys if table is new
635 if (!$is_new_table) {
636 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
637 if (isset($database[$name]["indexes"][$indexname])) {
638 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
640 $current_index_definition = "__NOT_SET__";
642 $new_index_definition = implode(",", $fieldnames);
643 if ($current_index_definition != $new_index_definition) {
644 $sql2 = self::createIndex($indexname, $fieldnames);
646 // Fetch the "group by" fields for unique indexes
647 $group_by = self::groupBy($fieldnames);
650 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
652 $sql3 .= ", " . $sql2;
658 $existing_foreign_keys = $database[$name]['foreign_keys'];
661 // Compare the field structure field by field
662 foreach ($structure["fields"] AS $fieldname => $parameters) {
663 if (empty($parameters['foreign'])) {
667 $constraint = self::getConstraintName($name, $fieldname, $parameters);
669 unset($existing_foreign_keys[$constraint]);
671 if (empty($database[$name]['foreign_keys'][$constraint])) {
672 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
675 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
677 $sql3 .= ", " . $sql2;
682 foreach ($existing_foreign_keys as $param) {
683 $sql2 = self::dropForeignKey($param['CONSTRAINT_NAME']);
686 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
688 $sql3 .= ", " . $sql2;
692 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
693 $structurecomment = $structure["comment"] ?? '';
694 if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
695 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
698 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
700 $sql3 .= ", " . $sql2;
705 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
706 if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
707 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
710 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
712 $sql3 .= ", " . $sql2;
717 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
718 if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
719 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
722 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
724 $sql3 .= ", " . $sql2;
733 // Now have a look at the field collations
734 // Compare the field structure field by field
735 foreach ($structure["fields"] AS $fieldname => $parameters) {
736 // Compare the field definition
737 $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
739 // Define the default collation if not given
740 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
741 $parameters['Collation'] = 'utf8mb4_general_ci';
743 $parameters['Collation'] = null;
746 if ($field_definition['Collation'] != $parameters['Collation']) {
747 $sql2 = self::modifyTableField($fieldname, $parameters);
748 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
749 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
751 $sql3 .= ", " . $sql2;
758 if (substr($sql3, -2, 2) != "; ") {
763 if ($is_unique && $ignore == '') {
764 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
765 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
767 $field_list = rtrim($field_list, ',');
771 // Ensure index conversion to unique removes duplicates
772 if ($is_unique && ($temp_name != $name)) {
774 echo "SET session old_alter_table=1;\n";
776 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
777 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
783 if ($is_unique && ($temp_name != $name)) {
785 echo "SET session old_alter_table=0;\n";
787 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
788 echo "DROP TABLE `" . $name . "`;\n";
789 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
795 if ($in_maintenance_mode) {
796 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
799 // Ensure index conversion to unique removes duplicates
800 if ($is_unique && ($temp_name != $name)) {
802 DBA::e("SET session old_alter_table=1;");
804 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
805 if (!DBA::isResult($r)) {
806 $errors .= self::printUpdateError($sql3);
810 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
811 if (!DBA::isResult($r)) {
812 $errors .= self::printUpdateError($sql3);
819 if (!DBA::isResult($r)) {
820 $errors .= self::printUpdateError($sql3);
822 if ($is_unique && ($temp_name != $name)) {
824 DBA::e("SET session old_alter_table=0;");
826 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
827 if (!DBA::isResult($r)) {
828 $errors .= self::printUpdateError($sql3);
831 $r = DBA::e("DROP TABLE `" . $name . "`;");
832 if (!DBA::isResult($r)) {
833 $errors .= self::printUpdateError($sql3);
836 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
837 if (!DBA::isResult($r)) {
838 $errors .= self::printUpdateError($sql3);
847 View::create(false, $action);
849 self::checkInitialValues();
851 if ($action && !$install) {
853 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
855 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
862 private static function tableStructure($table)
864 // This query doesn't seem to be executable as a prepared statement
865 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
867 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
868 ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
869 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
870 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
871 DBA::databaseName(), $table]);
873 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
874 ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
875 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
876 DBA::databaseName(), $table]);
878 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
879 ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
880 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
881 DBA::databaseName(), $table]);
887 if (DBA::isResult($foreign_keys)) {
888 foreach ($foreign_keys as $foreign_key) {
889 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
890 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
891 $foreigndata[$constraint] = $foreign_key;
895 if (DBA::isResult($indexes)) {
896 foreach ($indexes AS $index) {
897 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
898 $indexdata[$index["Key_name"]] = ["UNIQUE"];
901 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
902 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
905 $column = $index["Column_name"];
907 if ($index["Sub_part"] != "") {
908 $column .= "(" . $index["Sub_part"] . ")";
911 $indexdata[$index["Key_name"]][] = $column;
916 if (DBA::isResult($fields)) {
917 foreach ($fields AS $field) {
918 $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)'];
919 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
920 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
922 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
924 if ($field['IS_NULLABLE'] == 'NO') {
925 $fielddata[$field['COLUMN_NAME']]['not null'] = true;
928 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
929 $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
932 if (!empty($field['EXTRA'])) {
933 $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
936 if ($field['COLUMN_KEY'] == 'PRI') {
937 $fielddata[$field['COLUMN_NAME']]['primary'] = true;
940 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
941 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
945 return ["fields" => $fielddata, "indexes" => $indexdata,
946 "foreign_keys" => $foreigndata, "table_status" => $table_status];
949 private static function dropIndex($indexname)
951 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
955 private static function addTableField($fieldname, $parameters)
957 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
961 private static function modifyTableField($fieldname, $parameters)
963 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
967 private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
969 $foreign_table = array_keys($parameters['foreign'])[0];
970 $foreign_field = array_values($parameters['foreign'])[0];
972 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
975 private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
976 $foreign_table = array_keys($parameters['foreign'])[0];
977 $foreign_field = array_values($parameters['foreign'])[0];
979 $sql = "FOREIGN KEY (`" . $fieldname . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
981 if (!empty($parameters['foreign']['on update'])) {
982 $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
984 $sql .= " ON UPDATE RESTRICT";
987 if (!empty($parameters['foreign']['on delete'])) {
988 $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
990 $sql .= " ON DELETE CASCADE";
996 private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
998 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
1001 private static function dropForeignKey(string $constraint)
1003 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
1007 * Constructs a GROUP BY clause from a UNIQUE index definition.
1009 * @param array $fieldnames
1012 private static function groupBy(array $fieldnames)
1014 if ($fieldnames[0] != "UNIQUE") {
1018 array_shift($fieldnames);
1021 foreach ($fieldnames AS $fieldname) {
1026 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
1027 $names .= "`" . DBA::escape($matches[1]) . "`";
1029 $names .= "`" . DBA::escape($fieldname) . "`";
1033 $sql = sprintf(" GROUP BY %s", $names);
1038 * Renames columns or the primary key of a table
1040 * @todo You cannot rename a primary key if "auto increment" is set
1042 * @param string $table Table name
1043 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
1044 * Syntax for Primary Key: [ $col1, $col2, ...]
1045 * @param int $type The type of renaming (Default is Column)
1047 * @return boolean Was the renaming successful?
1050 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
1052 if (empty($table) || empty($columns)) {
1056 if (!is_array($columns)) {
1060 $table = DBA::escape($table);
1062 $sql = "ALTER TABLE `" . $table . "`";
1064 case self::RENAME_COLUMN:
1065 if (!self::existsColumn($table, array_keys($columns))) {
1068 $sql .= implode(',', array_map(
1069 function ($to, $from) {
1070 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
1073 array_keys($columns)
1076 case self::RENAME_PRIMARY_KEY:
1077 if (!self::existsColumn($table, $columns)) {
1080 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
1088 $stmt = DBA::p($sql);
1090 if (is_bool($stmt)) {
1102 * Check if the columns of the table exists
1104 * @param string $table Table name
1105 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
1107 * @return boolean Does the table exist?
1110 public static function existsColumn($table, $columns = [])
1112 if (empty($table)) {
1116 if (is_null($columns) || empty($columns)) {
1117 return self::existsTable($table);
1120 $table = DBA::escape($table);
1122 foreach ($columns AS $column) {
1123 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
1125 $stmt = DBA::p($sql);
1127 if (is_bool($stmt)) {
1130 $retval = (DBA::numRows($stmt) > 0);
1144 * Check if a foreign key exists for the given table field
1146 * @param string $table
1147 * @param string $field
1150 public static function existsForeignKeyForField(string $table, string $field)
1152 return DBA::exists(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
1153 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
1154 DBA::databaseName(), $table, $field]);
1157 * Check if a table exists
1159 * @param string|array $table Table name
1161 * @return boolean Does the table exist?
1164 public static function existsTable($table)
1166 if (empty($table)) {
1170 if (is_array($table)) {
1171 $condition = ['table_schema' => key($table), 'table_name' => current($table)];
1173 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
1176 $result = DBA::exists(['information_schema' => 'tables'], $condition);
1182 * Returns the columns of a table
1184 * @param string $table Table name
1186 * @return array An array of the table columns
1189 public static function getColumns($table)
1191 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
1192 return DBA::toArray($stmtColumns);
1196 * Check if initial database values do exist - or create them
1198 public static function checkInitialValues(bool $verbose = false)
1200 if (self::existsTable('verb')) {
1201 if (!DBA::exists('verb', ['id' => 1])) {
1202 foreach (Item::ACTIVITIES as $index => $activity) {
1203 DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], Database::INSERT_IGNORE);
1206 echo "verb: activities added\n";
1208 } elseif ($verbose) {
1209 echo "verb: activities already added\n";
1212 if (!DBA::exists('verb', ['id' => 0])) {
1213 DBA::insert('verb', ['name' => '']);
1214 $lastid = DBA::lastInsertId();
1216 DBA::update('verb', ['id' => 0], ['id' => $lastid]);
1218 echo "Zero verb added\n";
1221 } elseif ($verbose) {
1222 echo "Zero verb already added\n";
1224 } elseif ($verbose) {
1225 echo "verb: Table not found\n";
1228 if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) {
1231 "page-flags" => User::PAGE_FLAGS_SOAPBOX,
1232 "account-type" => User::ACCOUNT_TYPE_RELAY,
1234 DBA::insert('user', $user);
1235 $lastid = DBA::lastInsertId();
1237 DBA::update('user', ['uid' => 0], ['uid' => $lastid]);
1239 echo "Zero user added\n";
1242 } elseif (self::existsTable('user') && $verbose) {
1243 echo "Zero user already added\n";
1244 } elseif ($verbose) {
1245 echo "user: Table not found\n";
1248 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
1249 DBA::insert('contact', ['nurl' => '']);
1250 $lastid = DBA::lastInsertId();
1252 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
1254 echo "Zero contact added\n";
1257 } elseif (self::existsTable('contact') && $verbose) {
1258 echo "Zero contact already added\n";
1259 } elseif ($verbose) {
1260 echo "contact: Table not found\n";
1263 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
1264 DBA::insert('tag', ['name' => '']);
1265 $lastid = DBA::lastInsertId();
1267 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
1269 echo "Zero tag added\n";
1272 } elseif (self::existsTable('tag') && $verbose) {
1273 echo "Zero tag already added\n";
1274 } elseif ($verbose) {
1275 echo "tag: Table not found\n";
1278 if (self::existsTable('permissionset')) {
1279 if (!DBA::exists('permissionset', ['id' => 0])) {
1280 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
1281 $lastid = DBA::lastInsertId();
1283 DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
1285 echo "Zero permissionset added\n";
1288 } elseif ($verbose) {
1289 echo "Zero permissionset already added\n";
1291 if (self::existsTable('item') && !self::existsForeignKeyForField('item', 'psid')) {
1292 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
1293 LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
1294 WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
1295 while ($set = DBA::fetch($sets)) {
1296 if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
1297 $owner = User::getOwnerDataById($set['uid']);
1299 $permission = '<' . $owner['id'] . '>';
1306 $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
1307 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
1308 DBA::insert('permissionset', $fields);
1312 } elseif ($verbose) {
1313 echo "permissionset: Table not found\n";
1316 if (!self::existsForeignKeyForField('tokens', 'client_id')) {
1317 $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
1318 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
1319 WHERE `clients`.`client_id` IS NULL");
1320 while ($token = DBA::fetch($tokens)) {
1321 DBA::delete('tokens', ['id' => $token['id']]);
1323 DBA::close($tokens);
1328 * Checks if a database update is currently running
1332 private static function isUpdating()
1336 $processes = DBA::select(['information_schema' => 'processlist'], ['info'],
1337 ['db' => DBA::databaseName(), 'command' => ['Query', 'Execute']]);
1339 while ($process = DBA::fetch($processes)) {
1340 $parts = explode(' ', $process['info']);
1341 if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
1346 DBA::close($processes);