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) {
170 foreach ($definition['fields'] as $key => $value) {
172 $field['name'] = $key;
173 $field['comment'] = $value['comment'] ?? '';
174 $field['type'] = $value['type'];
175 $field['notnull'] = ($value['not null'] ?? false) ? 'YES' : 'NO';
176 $field['primary'] = ($value['primary'] ?? false) ? 'PRI' : '';
177 $field['default'] = $value['default'] ?? 'NULL';
178 $field['extra'] = $value['extra'] ?? '';
182 $tables[] = ['name' => $name, 'comment' => $definition['comment']];
183 $content = Renderer::replaceMacros(Renderer::getMarkupTemplate('structure.tpl'), [
185 '$comment' => $definition['comment'],
186 '$fields' => $fields,
188 $filename = DI::basePath() . '/doc/database/db_' . $name . '.md';
189 file_put_contents($filename, $content);
192 $content = Renderer::replaceMacros(Renderer::getMarkupTemplate('tables.tpl'), [
193 '$tables' => $tables,
195 $filename = DI::basePath() . '/doc/database.md';
196 file_put_contents($filename, $content);
199 public static function printStructure($basePath)
201 $database = self::definition($basePath, false);
203 echo "-- ------------------------------------------\n";
204 echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n";
205 echo "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
206 echo "-- ------------------------------------------\n\n\n";
207 foreach ($database AS $name => $structure) {
209 echo "-- TABLE $name\n";
211 self::createTable($name, $structure, true, false);
216 View::printStructure($basePath);
220 * Loads the database structure definition from the static/dbstructure.config.php file.
221 * On first pass, defines DB_UPDATE_VERSION constant.
223 * @see static/dbstructure.config.php
224 * @param boolean $with_addons_structure Whether to tack on addons additional tables
225 * @param string $basePath The base path of this application
229 public static function definition($basePath, $with_addons_structure = true)
231 if (!self::$definition) {
232 if (empty($basePath)) {
233 $basePath = DI::app()->getBasePath();
236 $filename = $basePath . '/static/dbstructure.config.php';
238 if (!is_readable($filename)) {
239 throw new Exception('Missing database structure config file static/dbstructure.config.php');
242 $definition = require $filename;
245 throw new Exception('Corrupted database structure config file static/dbstructure.config.php');
248 self::$definition = $definition;
250 $definition = self::$definition;
253 if ($with_addons_structure) {
254 Hook::callAll('dbstructure_definition', $definition);
261 * Get field data for the given table
263 * @param string $table
264 * @param array $data data fields
265 * @return array fields for the given
267 public static function getFieldsForTable(string $table, array $data = [])
269 $definition = DBStructure::definition('', false);
270 if (empty($definition[$table])) {
274 $fieldnames = array_keys($definition[$table]['fields']);
278 // Assign all field that are present in the table
279 foreach ($fieldnames as $field) {
280 if (isset($data[$field])) {
281 // Limit the length of varchar, varbinary, char and binrary fields
282 if (is_string($data[$field]) && preg_match("/char\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
283 $data[$field] = mb_substr($data[$field], 0, $result[1]);
284 } elseif (is_string($data[$field]) && preg_match("/binary\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
285 $data[$field] = substr($data[$field], 0, $result[1]);
287 $fields[$field] = $data[$field];
294 private static function createTable($name, $structure, $verbose, $action)
304 foreach ($structure["fields"] AS $fieldname => $field) {
305 $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
306 if (!empty($field['primary'])) {
307 $primary_keys[] = $fieldname;
309 if (!empty($field['foreign'])) {
310 $foreign_keys[$fieldname] = $field;
314 if (!empty($structure["indexes"])) {
315 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
316 $sql_index = self::createIndex($indexname, $fieldnames, "");
317 if (!is_null($sql_index)) {
318 $sql_rows[] = $sql_index;
323 foreach ($foreign_keys AS $fieldname => $parameters) {
324 $sql_rows[] = self::foreignCommand($name, $fieldname, $parameters);
327 if (isset($structure["engine"])) {
328 $engine = " ENGINE=" . $structure["engine"];
331 if (isset($structure["comment"])) {
332 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
335 $sql = implode(",\n\t", $sql_rows);
337 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
338 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
350 private static function FieldCommand($parameters, $create = true)
352 $fieldstruct = $parameters["type"];
354 if (isset($parameters["Collation"])) {
355 $fieldstruct .= " COLLATE " . $parameters["Collation"];
358 if (isset($parameters["not null"])) {
359 $fieldstruct .= " NOT NULL";
362 if (isset($parameters["default"])) {
363 if (strpos(strtolower($parameters["type"]), "int") !== false) {
364 $fieldstruct .= " DEFAULT " . $parameters["default"];
366 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
369 if (isset($parameters["extra"])) {
370 $fieldstruct .= " " . $parameters["extra"];
373 if (isset($parameters["comment"])) {
374 $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
377 /*if (($parameters["primary"] != "") && $create)
378 $fieldstruct .= " PRIMARY KEY";*/
380 return ($fieldstruct);
383 private static function createIndex($indexname, $fieldnames, $method = "ADD")
385 $method = strtoupper(trim($method));
386 if ($method != "" && $method != "ADD") {
387 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
390 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
391 $index_type = array_shift($fieldnames);
392 $method .= " " . $index_type;
396 foreach ($fieldnames AS $fieldname) {
401 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
402 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
404 $names .= "`" . DBA::escape($fieldname) . "`";
408 if ($indexname == "PRIMARY") {
409 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
413 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
418 * Perform a database structure dryrun (means: just simulating)
422 public static function dryRun()
424 self::update(DI::app()->getBasePath(), true, false);
428 * Updates DB structure and returns eventual errors messages
430 * @param bool $enable_maintenance_mode Set the maintenance mode
431 * @param bool $verbose Display the SQL commands
433 * @return string Empty string if the update is successful, error messages otherwise
436 public static function performUpdate(bool $enable_maintenance_mode = true, bool $verbose = false)
438 if ($enable_maintenance_mode) {
439 DI::config()->set('system', 'maintenance', 1);
442 $status = self::update(DI::app()->getBasePath(), $verbose, true);
444 if ($enable_maintenance_mode) {
445 DI::config()->set('system', 'maintenance', 0);
446 DI::config()->set('system', 'maintenance_reason', '');
453 * Updates DB structure from the installation and returns eventual errors messages
455 * @param string $basePath The base path of this application
457 * @return string Empty string if the update is successful, error messages otherwise
460 public static function install(string $basePath)
462 return self::update($basePath, false, true, true);
466 * Updates DB structure and returns eventual errors messages
468 * @param string $basePath The base path of this application
469 * @param bool $verbose
470 * @param bool $action Whether to actually apply the update
471 * @param bool $install Is this the initial update during the installation?
472 * @param array $tables An array of the database tables
473 * @param array $definition An array of the definition tables
474 * @return string Empty string if the update is successful, error messages otherwise
477 private static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
479 $in_maintenance_mode = DI::config()->get('system', 'maintenance');
481 if ($action && !$install && self::isUpdating()) {
482 return DI::l10n()->t('Another database update is currently running.');
485 if ($in_maintenance_mode) {
486 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
489 // ensure that all initial values exist. This test has to be done prior and after the structure check.
490 // Prior is needed if the specific tables already exists - after is needed when they had been created.
491 self::checkInitialValues();
495 Logger::info('updating structure');
497 // Get the current structure
500 if (is_null($tables)) {
501 $tables = DBA::toArray(DBA::p("SHOW TABLES"));
504 if (DBA::isResult($tables)) {
505 foreach ($tables AS $table) {
506 $table = current($table);
508 Logger::info('updating structure', ['table' => $table]);
509 $database[$table] = self::tableStructure($table);
513 // Get the definition
514 if (is_null($definition)) {
515 $definition = self::definition($basePath);
518 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
519 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
520 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
527 foreach ($definition AS $name => $structure) {
528 $is_new_table = false;
533 if (!isset($database[$name])) {
534 $r = self::createTable($name, $structure, $verbose, $action);
535 if (!DBA::isResult($r)) {
536 $errors .= self::printUpdateError($name);
538 $is_new_table = true;
540 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
541 if (isset($database[$name]["indexes"][$indexname])) {
542 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
544 $current_index_definition = "__NOT_SET__";
546 $new_index_definition = implode(",", $fieldnames);
547 if ($current_index_definition != $new_index_definition) {
548 if ($fieldnames[0] == "UNIQUE") {
551 $temp_name = "temp-" . $name;
558 * Drop the index if it isn't present in the definition
559 * or the definition differ from current status
560 * and index name doesn't start with "local_"
562 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
563 $current_index_definition = implode(",", $fieldnames);
564 if (isset($structure["indexes"][$indexname])) {
565 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
567 $new_index_definition = "__NOT_SET__";
569 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
570 $sql2 = self::dropIndex($indexname);
572 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
574 $sql3 .= ", " . $sql2;
578 // Compare the field structure field by field
579 foreach ($structure["fields"] AS $fieldname => $parameters) {
580 if (!isset($database[$name]["fields"][$fieldname])) {
581 $sql2 = self::addTableField($fieldname, $parameters);
583 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
585 $sql3 .= ", " . $sql2;
588 // Compare the field definition
589 $field_definition = $database[$name]["fields"][$fieldname];
591 // Remove the relation data that is used for the referential integrity
592 unset($parameters['relation']);
593 unset($parameters['foreign']);
595 // We change the collation after the indexes had been changed.
596 // This is done to avoid index length problems.
597 // So here we always ensure that there is no need to change it.
598 unset($parameters['Collation']);
599 unset($field_definition['Collation']);
601 // Only update the comment when it is defined
602 if (!isset($parameters['comment'])) {
603 $parameters['comment'] = "";
606 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
607 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
608 if ($current_field_definition != $new_field_definition) {
609 $sql2 = self::modifyTableField($fieldname, $parameters);
611 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
613 $sql3 .= ", " . $sql2;
621 * Create the index if the index don't exists in database
622 * or the definition differ from the current status.
623 * Don't create keys if table is new
625 if (!$is_new_table) {
626 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
627 if (isset($database[$name]["indexes"][$indexname])) {
628 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
630 $current_index_definition = "__NOT_SET__";
632 $new_index_definition = implode(",", $fieldnames);
633 if ($current_index_definition != $new_index_definition) {
634 $sql2 = self::createIndex($indexname, $fieldnames);
636 // Fetch the "group by" fields for unique indexes
637 $group_by = self::groupBy($fieldnames);
640 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
642 $sql3 .= ", " . $sql2;
648 $existing_foreign_keys = $database[$name]['foreign_keys'];
651 // Compare the field structure field by field
652 foreach ($structure["fields"] AS $fieldname => $parameters) {
653 if (empty($parameters['foreign'])) {
657 $constraint = self::getConstraintName($name, $fieldname, $parameters);
659 unset($existing_foreign_keys[$constraint]);
661 if (empty($database[$name]['foreign_keys'][$constraint])) {
662 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
665 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
667 $sql3 .= ", " . $sql2;
672 foreach ($existing_foreign_keys as $param) {
673 $sql2 = self::dropForeignKey($param['CONSTRAINT_NAME']);
676 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
678 $sql3 .= ", " . $sql2;
682 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
683 $structurecomment = $structure["comment"] ?? '';
684 if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
685 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
688 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
690 $sql3 .= ", " . $sql2;
695 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
696 if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
697 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
700 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
702 $sql3 .= ", " . $sql2;
707 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
708 if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
709 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
712 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
714 $sql3 .= ", " . $sql2;
723 // Now have a look at the field collations
724 // Compare the field structure field by field
725 foreach ($structure["fields"] AS $fieldname => $parameters) {
726 // Compare the field definition
727 $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
729 // Define the default collation if not given
730 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
731 $parameters['Collation'] = 'utf8mb4_general_ci';
733 $parameters['Collation'] = null;
736 if ($field_definition['Collation'] != $parameters['Collation']) {
737 $sql2 = self::modifyTableField($fieldname, $parameters);
738 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
739 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
741 $sql3 .= ", " . $sql2;
748 if (substr($sql3, -2, 2) != "; ") {
753 if ($is_unique && $ignore == '') {
754 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
755 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
757 $field_list = rtrim($field_list, ',');
761 // Ensure index conversion to unique removes duplicates
762 if ($is_unique && ($temp_name != $name)) {
764 echo "SET session old_alter_table=1;\n";
766 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
767 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
773 if ($is_unique && ($temp_name != $name)) {
775 echo "SET session old_alter_table=0;\n";
777 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
778 echo "DROP TABLE `" . $name . "`;\n";
779 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
785 if ($in_maintenance_mode) {
786 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
789 // Ensure index conversion to unique removes duplicates
790 if ($is_unique && ($temp_name != $name)) {
792 DBA::e("SET session old_alter_table=1;");
794 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
795 if (!DBA::isResult($r)) {
796 $errors .= self::printUpdateError($sql3);
800 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
801 if (!DBA::isResult($r)) {
802 $errors .= self::printUpdateError($sql3);
809 if (!DBA::isResult($r)) {
810 $errors .= self::printUpdateError($sql3);
812 if ($is_unique && ($temp_name != $name)) {
814 DBA::e("SET session old_alter_table=0;");
816 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
817 if (!DBA::isResult($r)) {
818 $errors .= self::printUpdateError($sql3);
821 $r = DBA::e("DROP TABLE `" . $name . "`;");
822 if (!DBA::isResult($r)) {
823 $errors .= self::printUpdateError($sql3);
826 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
827 if (!DBA::isResult($r)) {
828 $errors .= self::printUpdateError($sql3);
837 View::create(false, $action);
839 self::checkInitialValues();
841 if ($action && !$install) {
843 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
845 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
852 private static function tableStructure($table)
854 // This query doesn't seem to be executable as a prepared statement
855 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
857 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
858 ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
859 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
860 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
861 DBA::databaseName(), $table]);
863 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
864 ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
865 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
866 DBA::databaseName(), $table]);
868 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
869 ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
870 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
871 DBA::databaseName(), $table]);
877 if (DBA::isResult($foreign_keys)) {
878 foreach ($foreign_keys as $foreign_key) {
879 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
880 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
881 $foreigndata[$constraint] = $foreign_key;
885 if (DBA::isResult($indexes)) {
886 foreach ($indexes AS $index) {
887 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
888 $indexdata[$index["Key_name"]] = ["UNIQUE"];
891 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
892 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
895 $column = $index["Column_name"];
897 if ($index["Sub_part"] != "") {
898 $column .= "(" . $index["Sub_part"] . ")";
901 $indexdata[$index["Key_name"]][] = $column;
906 if (DBA::isResult($fields)) {
907 foreach ($fields AS $field) {
908 $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)'];
909 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
910 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
912 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
914 if ($field['IS_NULLABLE'] == 'NO') {
915 $fielddata[$field['COLUMN_NAME']]['not null'] = true;
918 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
919 $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
922 if (!empty($field['EXTRA'])) {
923 $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
926 if ($field['COLUMN_KEY'] == 'PRI') {
927 $fielddata[$field['COLUMN_NAME']]['primary'] = true;
930 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
931 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
935 return ["fields" => $fielddata, "indexes" => $indexdata,
936 "foreign_keys" => $foreigndata, "table_status" => $table_status];
939 private static function dropIndex($indexname)
941 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
945 private static function addTableField($fieldname, $parameters)
947 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
951 private static function modifyTableField($fieldname, $parameters)
953 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
957 private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
959 $foreign_table = array_keys($parameters['foreign'])[0];
960 $foreign_field = array_values($parameters['foreign'])[0];
962 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
965 private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
966 $foreign_table = array_keys($parameters['foreign'])[0];
967 $foreign_field = array_values($parameters['foreign'])[0];
969 $sql = "FOREIGN KEY (`" . $fieldname . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
971 if (!empty($parameters['foreign']['on update'])) {
972 $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
974 $sql .= " ON UPDATE RESTRICT";
977 if (!empty($parameters['foreign']['on delete'])) {
978 $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
980 $sql .= " ON DELETE CASCADE";
986 private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
988 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
991 private static function dropForeignKey(string $constraint)
993 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
997 * Constructs a GROUP BY clause from a UNIQUE index definition.
999 * @param array $fieldnames
1002 private static function groupBy(array $fieldnames)
1004 if ($fieldnames[0] != "UNIQUE") {
1008 array_shift($fieldnames);
1011 foreach ($fieldnames AS $fieldname) {
1016 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
1017 $names .= "`" . DBA::escape($matches[1]) . "`";
1019 $names .= "`" . DBA::escape($fieldname) . "`";
1023 $sql = sprintf(" GROUP BY %s", $names);
1028 * Renames columns or the primary key of a table
1030 * @todo You cannot rename a primary key if "auto increment" is set
1032 * @param string $table Table name
1033 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
1034 * Syntax for Primary Key: [ $col1, $col2, ...]
1035 * @param int $type The type of renaming (Default is Column)
1037 * @return boolean Was the renaming successful?
1040 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
1042 if (empty($table) || empty($columns)) {
1046 if (!is_array($columns)) {
1050 $table = DBA::escape($table);
1052 $sql = "ALTER TABLE `" . $table . "`";
1054 case self::RENAME_COLUMN:
1055 if (!self::existsColumn($table, array_keys($columns))) {
1058 $sql .= implode(',', array_map(
1059 function ($to, $from) {
1060 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
1063 array_keys($columns)
1066 case self::RENAME_PRIMARY_KEY:
1067 if (!self::existsColumn($table, $columns)) {
1070 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
1078 $stmt = DBA::p($sql);
1080 if (is_bool($stmt)) {
1092 * Check if the columns of the table exists
1094 * @param string $table Table name
1095 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
1097 * @return boolean Does the table exist?
1100 public static function existsColumn($table, $columns = [])
1102 if (empty($table)) {
1106 if (is_null($columns) || empty($columns)) {
1107 return self::existsTable($table);
1110 $table = DBA::escape($table);
1112 foreach ($columns AS $column) {
1113 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
1115 $stmt = DBA::p($sql);
1117 if (is_bool($stmt)) {
1120 $retval = (DBA::numRows($stmt) > 0);
1134 * Check if a foreign key exists for the given table field
1136 * @param string $table
1137 * @param string $field
1140 public static function existsForeignKeyForField(string $table, string $field)
1142 return DBA::exists(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
1143 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
1144 DBA::databaseName(), $table, $field]);
1147 * Check if a table exists
1149 * @param string|array $table Table name
1151 * @return boolean Does the table exist?
1154 public static function existsTable($table)
1156 if (empty($table)) {
1160 if (is_array($table)) {
1161 $condition = ['table_schema' => key($table), 'table_name' => current($table)];
1163 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
1166 $result = DBA::exists(['information_schema' => 'tables'], $condition);
1172 * Returns the columns of a table
1174 * @param string $table Table name
1176 * @return array An array of the table columns
1179 public static function getColumns($table)
1181 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
1182 return DBA::toArray($stmtColumns);
1186 * Check if initial database values do exist - or create them
1188 public static function checkInitialValues(bool $verbose = false)
1190 if (self::existsTable('verb')) {
1191 if (!DBA::exists('verb', ['id' => 1])) {
1192 foreach (Item::ACTIVITIES as $index => $activity) {
1193 DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], Database::INSERT_IGNORE);
1196 echo "verb: activities added\n";
1198 } elseif ($verbose) {
1199 echo "verb: activities already added\n";
1202 if (!DBA::exists('verb', ['id' => 0])) {
1203 DBA::insert('verb', ['name' => '']);
1204 $lastid = DBA::lastInsertId();
1206 DBA::update('verb', ['id' => 0], ['id' => $lastid]);
1208 echo "Zero verb added\n";
1211 } elseif ($verbose) {
1212 echo "Zero verb already added\n";
1214 } elseif ($verbose) {
1215 echo "verb: Table not found\n";
1218 if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) {
1221 "page-flags" => User::PAGE_FLAGS_SOAPBOX,
1222 "account-type" => User::ACCOUNT_TYPE_RELAY,
1224 DBA::insert('user', $user);
1225 $lastid = DBA::lastInsertId();
1227 DBA::update('user', ['uid' => 0], ['uid' => $lastid]);
1229 echo "Zero user added\n";
1232 } elseif (self::existsTable('user') && $verbose) {
1233 echo "Zero user already added\n";
1234 } elseif ($verbose) {
1235 echo "user: Table not found\n";
1238 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
1239 DBA::insert('contact', ['nurl' => '']);
1240 $lastid = DBA::lastInsertId();
1242 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
1244 echo "Zero contact added\n";
1247 } elseif (self::existsTable('contact') && $verbose) {
1248 echo "Zero contact already added\n";
1249 } elseif ($verbose) {
1250 echo "contact: Table not found\n";
1253 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
1254 DBA::insert('tag', ['name' => '']);
1255 $lastid = DBA::lastInsertId();
1257 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
1259 echo "Zero tag added\n";
1262 } elseif (self::existsTable('tag') && $verbose) {
1263 echo "Zero tag already added\n";
1264 } elseif ($verbose) {
1265 echo "tag: Table not found\n";
1268 if (self::existsTable('permissionset')) {
1269 if (!DBA::exists('permissionset', ['id' => 0])) {
1270 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
1271 $lastid = DBA::lastInsertId();
1273 DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
1275 echo "Zero permissionset added\n";
1278 } elseif ($verbose) {
1279 echo "Zero permissionset already added\n";
1281 if (self::existsTable('item') && !self::existsForeignKeyForField('item', 'psid')) {
1282 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
1283 LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
1284 WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
1285 while ($set = DBA::fetch($sets)) {
1286 if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
1287 $owner = User::getOwnerDataById($set['uid']);
1289 $permission = '<' . $owner['id'] . '>';
1296 $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
1297 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
1298 DBA::insert('permissionset', $fields);
1302 } elseif ($verbose) {
1303 echo "permissionset: Table not found\n";
1306 if (!self::existsForeignKeyForField('tokens', 'client_id')) {
1307 $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
1308 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
1309 WHERE `clients`.`client_id` IS NULL");
1310 while ($token = DBA::fetch($tokens)) {
1311 DBA::delete('tokens', ['id' => $token['id']]);
1313 DBA::close($tokens);
1318 * Checks if a database update is currently running
1322 private static function isUpdating()
1326 $processes = DBA::select(['information_schema' => 'processlist'], ['info'],
1327 ['db' => DBA::databaseName(), 'command' => ['Query', 'Execute']]);
1329 while ($process = DBA::fetch($processes)) {
1330 $parts = explode(' ', $process['info']);
1331 if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
1336 DBA::close($processes);