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 'comment' => 'Description',
175 'default' => 'Default',
196 foreach ($definition['fields'] as $key => $value) {
198 $field['name'] = $key;
199 $field['comment'] = $value['comment'] ?? '';
200 $field['type'] = $value['type'];
201 $field['null'] = ($value['not null'] ?? false) ? 'NO' : 'YES';
202 $field['primary'] = ($value['primary'] ?? false) ? 'PRI' : '';
203 $field['default'] = $value['default'] ?? 'NULL';
204 $field['extra'] = $value['extra'] ?? '';
206 foreach ($field as $fieldname => $fieldvalue) {
207 $lengths[$fieldname] = max($lengths[$fieldname] ?? 0, strlen($fieldvalue));
212 array_walk_recursive($fields, function(&$value, $key) use ($lengths)
214 $value = str_pad($value, $lengths[$key], $value === '-' ? '-' : ' ');
217 $tables[] = ['name' => $name, 'comment' => $definition['comment']];
218 $content = Renderer::replaceMacros(Renderer::getMarkupTemplate('structure.tpl'), [
220 '$comment' => $definition['comment'],
221 '$fields' => $fields,
223 $filename = DI::basePath() . '/doc/database/db_' . $name . '.md';
224 file_put_contents($filename, $content);
227 $content = Renderer::replaceMacros(Renderer::getMarkupTemplate('tables.tpl'), [
228 '$tables' => $tables,
230 $filename = DI::basePath() . '/doc/database.md';
231 file_put_contents($filename, $content);
234 public static function printStructure($basePath)
236 $database = self::definition($basePath, false);
238 echo "-- ------------------------------------------\n";
239 echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n";
240 echo "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
241 echo "-- ------------------------------------------\n\n\n";
242 foreach ($database AS $name => $structure) {
244 echo "-- TABLE $name\n";
246 self::createTable($name, $structure, true, false);
251 View::printStructure($basePath);
255 * Loads the database structure definition from the static/dbstructure.config.php file.
256 * On first pass, defines DB_UPDATE_VERSION constant.
258 * @see static/dbstructure.config.php
259 * @param boolean $with_addons_structure Whether to tack on addons additional tables
260 * @param string $basePath The base path of this application
264 public static function definition($basePath, $with_addons_structure = true)
266 if (!self::$definition) {
267 if (empty($basePath)) {
268 $basePath = DI::app()->getBasePath();
271 $filename = $basePath . '/static/dbstructure.config.php';
273 if (!is_readable($filename)) {
274 throw new Exception('Missing database structure config file static/dbstructure.config.php');
277 $definition = require $filename;
280 throw new Exception('Corrupted database structure config file static/dbstructure.config.php');
283 self::$definition = $definition;
285 $definition = self::$definition;
288 if ($with_addons_structure) {
289 Hook::callAll('dbstructure_definition', $definition);
296 * Get field data for the given table
298 * @param string $table
299 * @param array $data data fields
300 * @return array fields for the given
302 public static function getFieldsForTable(string $table, array $data = [])
304 $definition = DBStructure::definition('', false);
305 if (empty($definition[$table])) {
309 $fieldnames = array_keys($definition[$table]['fields']);
313 // Assign all field that are present in the table
314 foreach ($fieldnames as $field) {
315 if (isset($data[$field])) {
316 // Limit the length of varchar, varbinary, char and binrary fields
317 if (is_string($data[$field]) && preg_match("/char\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
318 $data[$field] = mb_substr($data[$field], 0, $result[1]);
319 } elseif (is_string($data[$field]) && preg_match("/binary\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
320 $data[$field] = substr($data[$field], 0, $result[1]);
322 $fields[$field] = $data[$field];
329 private static function createTable($name, $structure, $verbose, $action)
339 foreach ($structure["fields"] AS $fieldname => $field) {
340 $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
341 if (!empty($field['primary'])) {
342 $primary_keys[] = $fieldname;
344 if (!empty($field['foreign'])) {
345 $foreign_keys[$fieldname] = $field;
349 if (!empty($structure["indexes"])) {
350 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
351 $sql_index = self::createIndex($indexname, $fieldnames, "");
352 if (!is_null($sql_index)) {
353 $sql_rows[] = $sql_index;
358 foreach ($foreign_keys AS $fieldname => $parameters) {
359 $sql_rows[] = self::foreignCommand($name, $fieldname, $parameters);
362 if (isset($structure["engine"])) {
363 $engine = " ENGINE=" . $structure["engine"];
366 if (isset($structure["comment"])) {
367 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
370 $sql = implode(",\n\t", $sql_rows);
372 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
373 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
385 private static function FieldCommand($parameters, $create = true)
387 $fieldstruct = $parameters["type"];
389 if (isset($parameters["Collation"])) {
390 $fieldstruct .= " COLLATE " . $parameters["Collation"];
393 if (isset($parameters["not null"])) {
394 $fieldstruct .= " NOT NULL";
397 if (isset($parameters["default"])) {
398 if (strpos(strtolower($parameters["type"]), "int") !== false) {
399 $fieldstruct .= " DEFAULT " . $parameters["default"];
401 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
404 if (isset($parameters["extra"])) {
405 $fieldstruct .= " " . $parameters["extra"];
408 if (isset($parameters["comment"])) {
409 $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
412 /*if (($parameters["primary"] != "") && $create)
413 $fieldstruct .= " PRIMARY KEY";*/
415 return ($fieldstruct);
418 private static function createIndex($indexname, $fieldnames, $method = "ADD")
420 $method = strtoupper(trim($method));
421 if ($method != "" && $method != "ADD") {
422 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
425 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
426 $index_type = array_shift($fieldnames);
427 $method .= " " . $index_type;
431 foreach ($fieldnames AS $fieldname) {
436 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
437 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
439 $names .= "`" . DBA::escape($fieldname) . "`";
443 if ($indexname == "PRIMARY") {
444 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
448 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
453 * Perform a database structure dryrun (means: just simulating)
457 public static function dryRun()
459 self::update(DI::app()->getBasePath(), true, false);
463 * Updates DB structure and returns eventual errors messages
465 * @param bool $enable_maintenance_mode Set the maintenance mode
466 * @param bool $verbose Display the SQL commands
468 * @return string Empty string if the update is successful, error messages otherwise
471 public static function performUpdate(bool $enable_maintenance_mode = true, bool $verbose = false)
473 if ($enable_maintenance_mode) {
474 DI::config()->set('system', 'maintenance', 1);
477 $status = self::update(DI::app()->getBasePath(), $verbose, true);
479 if ($enable_maintenance_mode) {
480 DI::config()->set('system', 'maintenance', 0);
481 DI::config()->set('system', 'maintenance_reason', '');
488 * Updates DB structure from the installation and returns eventual errors messages
490 * @param string $basePath The base path of this application
492 * @return string Empty string if the update is successful, error messages otherwise
495 public static function install(string $basePath)
497 return self::update($basePath, false, true, true);
501 * Updates DB structure and returns eventual errors messages
503 * @param string $basePath The base path of this application
504 * @param bool $verbose
505 * @param bool $action Whether to actually apply the update
506 * @param bool $install Is this the initial update during the installation?
507 * @param array $tables An array of the database tables
508 * @param array $definition An array of the definition tables
509 * @return string Empty string if the update is successful, error messages otherwise
512 private static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
514 $in_maintenance_mode = DI::config()->get('system', 'maintenance');
516 if ($action && !$install && self::isUpdating()) {
517 return DI::l10n()->t('Another database update is currently running.');
520 if ($in_maintenance_mode) {
521 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
524 // ensure that all initial values exist. This test has to be done prior and after the structure check.
525 // Prior is needed if the specific tables already exists - after is needed when they had been created.
526 self::checkInitialValues();
530 Logger::info('updating structure');
532 // Get the current structure
535 if (is_null($tables)) {
536 $tables = DBA::toArray(DBA::p("SHOW TABLES"));
539 if (DBA::isResult($tables)) {
540 foreach ($tables AS $table) {
541 $table = current($table);
543 Logger::info('updating structure', ['table' => $table]);
544 $database[$table] = self::tableStructure($table);
548 // Get the definition
549 if (is_null($definition)) {
550 $definition = self::definition($basePath);
553 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
554 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
555 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
562 foreach ($definition AS $name => $structure) {
563 $is_new_table = false;
568 if (!isset($database[$name])) {
569 $r = self::createTable($name, $structure, $verbose, $action);
570 if (!DBA::isResult($r)) {
571 $errors .= self::printUpdateError($name);
573 $is_new_table = true;
575 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
576 if (isset($database[$name]["indexes"][$indexname])) {
577 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
579 $current_index_definition = "__NOT_SET__";
581 $new_index_definition = implode(",", $fieldnames);
582 if ($current_index_definition != $new_index_definition) {
583 if ($fieldnames[0] == "UNIQUE") {
586 $temp_name = "temp-" . $name;
593 * Drop the index if it isn't present in the definition
594 * or the definition differ from current status
595 * and index name doesn't start with "local_"
597 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
598 $current_index_definition = implode(",", $fieldnames);
599 if (isset($structure["indexes"][$indexname])) {
600 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
602 $new_index_definition = "__NOT_SET__";
604 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
605 $sql2 = self::dropIndex($indexname);
607 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
609 $sql3 .= ", " . $sql2;
613 // Compare the field structure field by field
614 foreach ($structure["fields"] AS $fieldname => $parameters) {
615 if (!isset($database[$name]["fields"][$fieldname])) {
616 $sql2 = self::addTableField($fieldname, $parameters);
618 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
620 $sql3 .= ", " . $sql2;
623 // Compare the field definition
624 $field_definition = $database[$name]["fields"][$fieldname];
626 // Remove the relation data that is used for the referential integrity
627 unset($parameters['relation']);
628 unset($parameters['foreign']);
630 // We change the collation after the indexes had been changed.
631 // This is done to avoid index length problems.
632 // So here we always ensure that there is no need to change it.
633 unset($parameters['Collation']);
634 unset($field_definition['Collation']);
636 // Only update the comment when it is defined
637 if (!isset($parameters['comment'])) {
638 $parameters['comment'] = "";
641 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
642 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
643 if ($current_field_definition != $new_field_definition) {
644 $sql2 = self::modifyTableField($fieldname, $parameters);
646 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
648 $sql3 .= ", " . $sql2;
656 * Create the index if the index don't exists in database
657 * or the definition differ from the current status.
658 * Don't create keys if table is new
660 if (!$is_new_table) {
661 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
662 if (isset($database[$name]["indexes"][$indexname])) {
663 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
665 $current_index_definition = "__NOT_SET__";
667 $new_index_definition = implode(",", $fieldnames);
668 if ($current_index_definition != $new_index_definition) {
669 $sql2 = self::createIndex($indexname, $fieldnames);
671 // Fetch the "group by" fields for unique indexes
672 $group_by = self::groupBy($fieldnames);
675 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
677 $sql3 .= ", " . $sql2;
683 $existing_foreign_keys = $database[$name]['foreign_keys'];
686 // Compare the field structure field by field
687 foreach ($structure["fields"] AS $fieldname => $parameters) {
688 if (empty($parameters['foreign'])) {
692 $constraint = self::getConstraintName($name, $fieldname, $parameters);
694 unset($existing_foreign_keys[$constraint]);
696 if (empty($database[$name]['foreign_keys'][$constraint])) {
697 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
700 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
702 $sql3 .= ", " . $sql2;
707 foreach ($existing_foreign_keys as $param) {
708 $sql2 = self::dropForeignKey($param['CONSTRAINT_NAME']);
711 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
713 $sql3 .= ", " . $sql2;
717 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
718 $structurecomment = $structure["comment"] ?? '';
719 if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
720 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
723 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
725 $sql3 .= ", " . $sql2;
730 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
731 if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
732 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
735 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
737 $sql3 .= ", " . $sql2;
742 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
743 if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
744 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
747 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
749 $sql3 .= ", " . $sql2;
758 // Now have a look at the field collations
759 // Compare the field structure field by field
760 foreach ($structure["fields"] AS $fieldname => $parameters) {
761 // Compare the field definition
762 $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
764 // Define the default collation if not given
765 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
766 $parameters['Collation'] = 'utf8mb4_general_ci';
768 $parameters['Collation'] = null;
771 if ($field_definition['Collation'] != $parameters['Collation']) {
772 $sql2 = self::modifyTableField($fieldname, $parameters);
773 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
774 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
776 $sql3 .= ", " . $sql2;
783 if (substr($sql3, -2, 2) != "; ") {
788 if ($is_unique && $ignore == '') {
789 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
790 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
792 $field_list = rtrim($field_list, ',');
796 // Ensure index conversion to unique removes duplicates
797 if ($is_unique && ($temp_name != $name)) {
799 echo "SET session old_alter_table=1;\n";
801 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
802 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
808 if ($is_unique && ($temp_name != $name)) {
810 echo "SET session old_alter_table=0;\n";
812 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
813 echo "DROP TABLE `" . $name . "`;\n";
814 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
820 if ($in_maintenance_mode) {
821 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
824 // Ensure index conversion to unique removes duplicates
825 if ($is_unique && ($temp_name != $name)) {
827 DBA::e("SET session old_alter_table=1;");
829 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
830 if (!DBA::isResult($r)) {
831 $errors .= self::printUpdateError($sql3);
835 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
836 if (!DBA::isResult($r)) {
837 $errors .= self::printUpdateError($sql3);
844 if (!DBA::isResult($r)) {
845 $errors .= self::printUpdateError($sql3);
847 if ($is_unique && ($temp_name != $name)) {
849 DBA::e("SET session old_alter_table=0;");
851 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
852 if (!DBA::isResult($r)) {
853 $errors .= self::printUpdateError($sql3);
856 $r = DBA::e("DROP TABLE `" . $name . "`;");
857 if (!DBA::isResult($r)) {
858 $errors .= self::printUpdateError($sql3);
861 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
862 if (!DBA::isResult($r)) {
863 $errors .= self::printUpdateError($sql3);
872 View::create(false, $action);
874 self::checkInitialValues();
876 if ($action && !$install) {
878 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
880 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
887 private static function tableStructure($table)
889 // This query doesn't seem to be executable as a prepared statement
890 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
892 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
893 ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
894 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
895 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
896 DBA::databaseName(), $table]);
898 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
899 ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
900 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
901 DBA::databaseName(), $table]);
903 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
904 ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
905 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
906 DBA::databaseName(), $table]);
912 if (DBA::isResult($foreign_keys)) {
913 foreach ($foreign_keys as $foreign_key) {
914 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
915 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
916 $foreigndata[$constraint] = $foreign_key;
920 if (DBA::isResult($indexes)) {
921 foreach ($indexes AS $index) {
922 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
923 $indexdata[$index["Key_name"]] = ["UNIQUE"];
926 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
927 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
930 $column = $index["Column_name"];
932 if ($index["Sub_part"] != "") {
933 $column .= "(" . $index["Sub_part"] . ")";
936 $indexdata[$index["Key_name"]][] = $column;
941 if (DBA::isResult($fields)) {
942 foreach ($fields AS $field) {
943 $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)'];
944 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
945 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
947 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
949 if ($field['IS_NULLABLE'] == 'NO') {
950 $fielddata[$field['COLUMN_NAME']]['not null'] = true;
953 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
954 $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
957 if (!empty($field['EXTRA'])) {
958 $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
961 if ($field['COLUMN_KEY'] == 'PRI') {
962 $fielddata[$field['COLUMN_NAME']]['primary'] = true;
965 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
966 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
970 return ["fields" => $fielddata, "indexes" => $indexdata,
971 "foreign_keys" => $foreigndata, "table_status" => $table_status];
974 private static function dropIndex($indexname)
976 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
980 private static function addTableField($fieldname, $parameters)
982 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
986 private static function modifyTableField($fieldname, $parameters)
988 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
992 private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
994 $foreign_table = array_keys($parameters['foreign'])[0];
995 $foreign_field = array_values($parameters['foreign'])[0];
997 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
1000 private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
1001 $foreign_table = array_keys($parameters['foreign'])[0];
1002 $foreign_field = array_values($parameters['foreign'])[0];
1004 $sql = "FOREIGN KEY (`" . $fieldname . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
1006 if (!empty($parameters['foreign']['on update'])) {
1007 $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
1009 $sql .= " ON UPDATE RESTRICT";
1012 if (!empty($parameters['foreign']['on delete'])) {
1013 $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
1015 $sql .= " ON DELETE CASCADE";
1021 private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
1023 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
1026 private static function dropForeignKey(string $constraint)
1028 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
1032 * Constructs a GROUP BY clause from a UNIQUE index definition.
1034 * @param array $fieldnames
1037 private static function groupBy(array $fieldnames)
1039 if ($fieldnames[0] != "UNIQUE") {
1043 array_shift($fieldnames);
1046 foreach ($fieldnames AS $fieldname) {
1051 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
1052 $names .= "`" . DBA::escape($matches[1]) . "`";
1054 $names .= "`" . DBA::escape($fieldname) . "`";
1058 $sql = sprintf(" GROUP BY %s", $names);
1063 * Renames columns or the primary key of a table
1065 * @todo You cannot rename a primary key if "auto increment" is set
1067 * @param string $table Table name
1068 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
1069 * Syntax for Primary Key: [ $col1, $col2, ...]
1070 * @param int $type The type of renaming (Default is Column)
1072 * @return boolean Was the renaming successful?
1075 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
1077 if (empty($table) || empty($columns)) {
1081 if (!is_array($columns)) {
1085 $table = DBA::escape($table);
1087 $sql = "ALTER TABLE `" . $table . "`";
1089 case self::RENAME_COLUMN:
1090 if (!self::existsColumn($table, array_keys($columns))) {
1093 $sql .= implode(',', array_map(
1094 function ($to, $from) {
1095 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
1098 array_keys($columns)
1101 case self::RENAME_PRIMARY_KEY:
1102 if (!self::existsColumn($table, $columns)) {
1105 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
1113 $stmt = DBA::p($sql);
1115 if (is_bool($stmt)) {
1127 * Check if the columns of the table exists
1129 * @param string $table Table name
1130 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
1132 * @return boolean Does the table exist?
1135 public static function existsColumn($table, $columns = [])
1137 if (empty($table)) {
1141 if (is_null($columns) || empty($columns)) {
1142 return self::existsTable($table);
1145 $table = DBA::escape($table);
1147 foreach ($columns AS $column) {
1148 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
1150 $stmt = DBA::p($sql);
1152 if (is_bool($stmt)) {
1155 $retval = (DBA::numRows($stmt) > 0);
1169 * Check if a foreign key exists for the given table field
1171 * @param string $table
1172 * @param string $field
1175 public static function existsForeignKeyForField(string $table, string $field)
1177 return DBA::exists(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
1178 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
1179 DBA::databaseName(), $table, $field]);
1182 * Check if a table exists
1184 * @param string|array $table Table name
1186 * @return boolean Does the table exist?
1189 public static function existsTable($table)
1191 if (empty($table)) {
1195 if (is_array($table)) {
1196 $condition = ['table_schema' => key($table), 'table_name' => current($table)];
1198 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
1201 $result = DBA::exists(['information_schema' => 'tables'], $condition);
1207 * Returns the columns of a table
1209 * @param string $table Table name
1211 * @return array An array of the table columns
1214 public static function getColumns($table)
1216 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
1217 return DBA::toArray($stmtColumns);
1221 * Check if initial database values do exist - or create them
1223 public static function checkInitialValues(bool $verbose = false)
1225 if (self::existsTable('verb')) {
1226 if (!DBA::exists('verb', ['id' => 1])) {
1227 foreach (Item::ACTIVITIES as $index => $activity) {
1228 DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], Database::INSERT_IGNORE);
1231 echo "verb: activities added\n";
1233 } elseif ($verbose) {
1234 echo "verb: activities already added\n";
1237 if (!DBA::exists('verb', ['id' => 0])) {
1238 DBA::insert('verb', ['name' => '']);
1239 $lastid = DBA::lastInsertId();
1241 DBA::update('verb', ['id' => 0], ['id' => $lastid]);
1243 echo "Zero verb added\n";
1246 } elseif ($verbose) {
1247 echo "Zero verb already added\n";
1249 } elseif ($verbose) {
1250 echo "verb: Table not found\n";
1253 if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) {
1256 "page-flags" => User::PAGE_FLAGS_SOAPBOX,
1257 "account-type" => User::ACCOUNT_TYPE_RELAY,
1259 DBA::insert('user', $user);
1260 $lastid = DBA::lastInsertId();
1262 DBA::update('user', ['uid' => 0], ['uid' => $lastid]);
1264 echo "Zero user added\n";
1267 } elseif (self::existsTable('user') && $verbose) {
1268 echo "Zero user already added\n";
1269 } elseif ($verbose) {
1270 echo "user: Table not found\n";
1273 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
1274 DBA::insert('contact', ['nurl' => '']);
1275 $lastid = DBA::lastInsertId();
1277 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
1279 echo "Zero contact added\n";
1282 } elseif (self::existsTable('contact') && $verbose) {
1283 echo "Zero contact already added\n";
1284 } elseif ($verbose) {
1285 echo "contact: Table not found\n";
1288 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
1289 DBA::insert('tag', ['name' => '']);
1290 $lastid = DBA::lastInsertId();
1292 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
1294 echo "Zero tag added\n";
1297 } elseif (self::existsTable('tag') && $verbose) {
1298 echo "Zero tag already added\n";
1299 } elseif ($verbose) {
1300 echo "tag: Table not found\n";
1303 if (self::existsTable('permissionset')) {
1304 if (!DBA::exists('permissionset', ['id' => 0])) {
1305 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
1306 $lastid = DBA::lastInsertId();
1308 DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
1310 echo "Zero permissionset added\n";
1313 } elseif ($verbose) {
1314 echo "Zero permissionset already added\n";
1316 if (self::existsTable('item') && !self::existsForeignKeyForField('item', 'psid')) {
1317 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
1318 LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
1319 WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
1320 while ($set = DBA::fetch($sets)) {
1321 if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
1322 $owner = User::getOwnerDataById($set['uid']);
1324 $permission = '<' . $owner['id'] . '>';
1331 $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
1332 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
1333 DBA::insert('permissionset', $fields);
1337 } elseif ($verbose) {
1338 echo "permissionset: Table not found\n";
1341 if (!self::existsForeignKeyForField('tokens', 'client_id')) {
1342 $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
1343 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
1344 WHERE `clients`.`client_id` IS NULL");
1345 while ($token = DBA::fetch($tokens)) {
1346 DBA::delete('tokens', ['id' => $token['id']]);
1348 DBA::close($tokens);
1353 * Checks if a database update is currently running
1357 private static function isUpdating()
1361 $processes = DBA::select(['information_schema' => 'processlist'], ['info'],
1362 ['db' => DBA::databaseName(), 'command' => ['Query', 'Execute']]);
1364 while ($process = DBA::fetch($processes)) {
1365 $parts = explode(' ', $process['info']);
1366 if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
1371 DBA::close($processes);