3 * @copyright Copyright (C) 2020, Friendica
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;
28 use Friendica\Model\Item;
29 use Friendica\Model\User;
30 use Friendica\Util\DateTimeFormat;
33 * This class contains functions that doesn't need to know if pdo, mysqli or whatever is used.
37 const UPDATE_NOT_CHECKED = 0; // Database check wasn't executed before
38 const UPDATE_SUCCESSFUL = 1; // Database check was successful
39 const UPDATE_FAILED = 2; // Database check failed
41 const RENAME_COLUMN = 0;
42 const RENAME_PRIMARY_KEY = 1;
45 * Database structure definition loaded from config/dbstructure.config.php
49 private static $definition = [];
52 * Converts all tables from MyISAM/InnoDB Antelope to InnoDB Barracuda
54 public static function convertToInnoDB()
56 $tables = DBA::selectToArray(
57 ['information_schema' => 'tables'],
59 ['engine' => 'MyISAM', 'table_schema' => DBA::databaseName()]
62 $tables = array_merge($tables, DBA::selectToArray(
63 ['information_schema' => 'tables'],
65 ['engine' => 'InnoDB', 'ROW_FORMAT' => ['COMPACT', 'REDUNDANT'], 'table_schema' => DBA::databaseName()]
68 if (!DBA::isResult($tables)) {
69 echo DI::l10n()->t('There are no tables on MyISAM or InnoDB with the Antelope file format.') . "\n";
73 foreach ($tables AS $table) {
74 $sql = "ALTER TABLE " . DBA::quoteIdentifier($table['table_name']) . " ENGINE=InnoDB ROW_FORMAT=DYNAMIC;";
77 $result = DBA::e($sql);
78 if (!DBA::isResult($result)) {
79 self::printUpdateError($sql);
85 * Print out database error messages
87 * @param string $message Message to be added to the error message
89 * @return string Error message
91 private static function printUpdateError($message)
93 echo DI::l10n()->t("\nError %d occurred during database update:\n%s\n",
94 DBA::errorNo(), DBA::errorMessage());
96 return DI::l10n()->t('Errors encountered performing database changes: ') . $message . EOL;
99 public static function printStructure($basePath)
101 $database = self::definition($basePath, false);
103 echo "-- ------------------------------------------\n";
104 echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n";
105 echo "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
106 echo "-- ------------------------------------------\n\n\n";
107 foreach ($database AS $name => $structure) {
109 echo "-- TABLE $name\n";
111 self::createTable($name, $structure, true, false);
116 View::printStructure($basePath);
120 * Loads the database structure definition from the static/dbstructure.config.php file.
121 * On first pass, defines DB_UPDATE_VERSION constant.
123 * @see static/dbstructure.config.php
124 * @param boolean $with_addons_structure Whether to tack on addons additional tables
125 * @param string $basePath The base path of this application
129 public static function definition($basePath, $with_addons_structure = true)
131 if (!self::$definition) {
133 $filename = $basePath . '/static/dbstructure.config.php';
135 if (!is_readable($filename)) {
136 throw new Exception('Missing database structure config file static/dbstructure.config.php');
139 $definition = require $filename;
142 throw new Exception('Corrupted database structure config file static/dbstructure.config.php');
145 self::$definition = $definition;
147 $definition = self::$definition;
150 if ($with_addons_structure) {
151 Hook::callAll('dbstructure_definition', $definition);
157 private static function createTable($name, $structure, $verbose, $action)
167 foreach ($structure["fields"] AS $fieldname => $field) {
168 $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
169 if (!empty($field['primary'])) {
170 $primary_keys[] = $fieldname;
172 if (!empty($field['foreign'])) {
173 $foreign_keys[$fieldname] = $field;
177 if (!empty($structure["indexes"])) {
178 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
179 $sql_index = self::createIndex($indexname, $fieldnames, "");
180 if (!is_null($sql_index)) {
181 $sql_rows[] = $sql_index;
186 foreach ($foreign_keys AS $fieldname => $parameters) {
187 $sql_rows[] = self::foreignCommand($name, $fieldname, $parameters);
190 if (isset($structure["engine"])) {
191 $engine = " ENGINE=" . $structure["engine"];
194 if (isset($structure["comment"])) {
195 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
198 $sql = implode(",\n\t", $sql_rows);
200 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
201 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
213 private static function FieldCommand($parameters, $create = true)
215 $fieldstruct = $parameters["type"];
217 if (isset($parameters["Collation"])) {
218 $fieldstruct .= " COLLATE " . $parameters["Collation"];
221 if (isset($parameters["not null"])) {
222 $fieldstruct .= " NOT NULL";
225 if (isset($parameters["default"])) {
226 if (strpos(strtolower($parameters["type"]), "int") !== false) {
227 $fieldstruct .= " DEFAULT " . $parameters["default"];
229 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
232 if (isset($parameters["extra"])) {
233 $fieldstruct .= " " . $parameters["extra"];
236 if (isset($parameters["comment"])) {
237 $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
240 /*if (($parameters["primary"] != "") && $create)
241 $fieldstruct .= " PRIMARY KEY";*/
243 return ($fieldstruct);
246 private static function createIndex($indexname, $fieldnames, $method = "ADD")
248 $method = strtoupper(trim($method));
249 if ($method != "" && $method != "ADD") {
250 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
253 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
254 $index_type = array_shift($fieldnames);
255 $method .= " " . $index_type;
259 foreach ($fieldnames AS $fieldname) {
264 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
265 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
267 $names .= "`" . DBA::escape($fieldname) . "`";
271 if ($indexname == "PRIMARY") {
272 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
276 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
281 * Updates DB structure and returns eventual errors messages
283 * @param string $basePath The base path of this application
284 * @param bool $verbose
285 * @param bool $action Whether to actually apply the update
286 * @param bool $install Is this the initial update during the installation?
287 * @param array $tables An array of the database tables
288 * @param array $definition An array of the definition tables
289 * @return string Empty string if the update is successful, error messages otherwise
292 public static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
294 if ($action && !$install) {
295 if (self::isUpdating()) {
296 return DI::l10n()->t('Another database update is currently running.');
299 DI::config()->set('system', 'maintenance', 1);
300 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
303 // ensure that all initial values exist. This test has to be done prior and after the structure check.
304 // Prior is needed if the specific tables already exists - after is needed when they had been created.
305 self::checkInitialValues();
309 Logger::log('updating structure', Logger::DEBUG);
311 // Get the current structure
314 if (is_null($tables)) {
315 $tables = DBA::toArray(DBA::p("SHOW TABLES"));
318 if (DBA::isResult($tables)) {
319 foreach ($tables AS $table) {
320 $table = current($table);
322 Logger::log(sprintf('updating structure for table %s ...', $table), Logger::DEBUG);
323 $database[$table] = self::tableStructure($table);
327 // Get the definition
328 if (is_null($definition)) {
329 $definition = self::definition($basePath);
332 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
333 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
334 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
341 foreach ($definition AS $name => $structure) {
342 $is_new_table = false;
347 if (!isset($database[$name])) {
348 $r = self::createTable($name, $structure, $verbose, $action);
349 if (!DBA::isResult($r)) {
350 $errors .= self::printUpdateError($name);
352 $is_new_table = true;
354 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
355 if (isset($database[$name]["indexes"][$indexname])) {
356 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
358 $current_index_definition = "__NOT_SET__";
360 $new_index_definition = implode(",", $fieldnames);
361 if ($current_index_definition != $new_index_definition) {
362 if ($fieldnames[0] == "UNIQUE") {
365 $temp_name = "temp-" . $name;
372 * Drop the index if it isn't present in the definition
373 * or the definition differ from current status
374 * and index name doesn't start with "local_"
376 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
377 $current_index_definition = implode(",", $fieldnames);
378 if (isset($structure["indexes"][$indexname])) {
379 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
381 $new_index_definition = "__NOT_SET__";
383 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
384 $sql2 = self::dropIndex($indexname);
386 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
388 $sql3 .= ", " . $sql2;
392 // Compare the field structure field by field
393 foreach ($structure["fields"] AS $fieldname => $parameters) {
394 if (!isset($database[$name]["fields"][$fieldname])) {
395 $sql2 = self::addTableField($fieldname, $parameters);
397 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
399 $sql3 .= ", " . $sql2;
402 // Compare the field definition
403 $field_definition = $database[$name]["fields"][$fieldname];
405 // Remove the relation data that is used for the referential integrity
406 unset($parameters['relation']);
407 unset($parameters['foreign']);
409 // We change the collation after the indexes had been changed.
410 // This is done to avoid index length problems.
411 // So here we always ensure that there is no need to change it.
412 unset($parameters['Collation']);
413 unset($field_definition['Collation']);
415 // Only update the comment when it is defined
416 if (!isset($parameters['comment'])) {
417 $parameters['comment'] = "";
420 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
421 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
422 if ($current_field_definition != $new_field_definition) {
423 $sql2 = self::modifyTableField($fieldname, $parameters);
425 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
427 $sql3 .= ", " . $sql2;
435 * Create the index if the index don't exists in database
436 * or the definition differ from the current status.
437 * Don't create keys if table is new
439 if (!$is_new_table) {
440 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
441 if (isset($database[$name]["indexes"][$indexname])) {
442 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
444 $current_index_definition = "__NOT_SET__";
446 $new_index_definition = implode(",", $fieldnames);
447 if ($current_index_definition != $new_index_definition) {
448 $sql2 = self::createIndex($indexname, $fieldnames);
450 // Fetch the "group by" fields for unique indexes
451 $group_by = self::groupBy($fieldnames);
454 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
456 $sql3 .= ", " . $sql2;
462 $existing_foreign_keys = $database[$name]['foreign_keys'];
465 // Compare the field structure field by field
466 foreach ($structure["fields"] AS $fieldname => $parameters) {
467 if (empty($parameters['foreign'])) {
471 $constraint = self::getConstraintName($name, $fieldname, $parameters);
473 unset($existing_foreign_keys[$constraint]);
475 if (empty($database[$name]['foreign_keys'][$constraint])) {
476 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
479 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
481 $sql3 .= ", " . $sql2;
486 foreach ($existing_foreign_keys as $param) {
487 $sql2 = self::dropForeignKey($param['CONSTRAINT_NAME']);
490 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
492 $sql3 .= ", " . $sql2;
496 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
497 $structurecomment = $structure["comment"] ?? '';
498 if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
499 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
502 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
504 $sql3 .= ", " . $sql2;
509 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
510 if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
511 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
514 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
516 $sql3 .= ", " . $sql2;
521 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
522 if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
523 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
526 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
528 $sql3 .= ", " . $sql2;
537 // Now have a look at the field collations
538 // Compare the field structure field by field
539 foreach ($structure["fields"] AS $fieldname => $parameters) {
540 // Compare the field definition
541 $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
543 // Define the default collation if not given
544 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
545 $parameters['Collation'] = 'utf8mb4_general_ci';
547 $parameters['Collation'] = null;
550 if ($field_definition['Collation'] != $parameters['Collation']) {
551 $sql2 = self::modifyTableField($fieldname, $parameters);
552 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
553 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
555 $sql3 .= ", " . $sql2;
562 if (substr($sql3, -2, 2) != "; ") {
567 if ($is_unique && $ignore == '') {
568 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
569 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
571 $field_list = rtrim($field_list, ',');
575 // Ensure index conversion to unique removes duplicates
576 if ($is_unique && ($temp_name != $name)) {
578 echo "SET session old_alter_table=1;\n";
580 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
581 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
587 if ($is_unique && ($temp_name != $name)) {
589 echo "SET session old_alter_table=0;\n";
591 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
592 echo "DROP TABLE `" . $name . "`;\n";
593 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
600 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
603 // Ensure index conversion to unique removes duplicates
604 if ($is_unique && ($temp_name != $name)) {
606 DBA::e("SET session old_alter_table=1;");
608 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
609 if (!DBA::isResult($r)) {
610 $errors .= self::printUpdateError($sql3);
614 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
615 if (!DBA::isResult($r)) {
616 $errors .= self::printUpdateError($sql3);
623 if (!DBA::isResult($r)) {
624 $errors .= self::printUpdateError($sql3);
626 if ($is_unique && ($temp_name != $name)) {
628 DBA::e("SET session old_alter_table=0;");
630 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
631 if (!DBA::isResult($r)) {
632 $errors .= self::printUpdateError($sql3);
635 $r = DBA::e("DROP TABLE `" . $name . "`;");
636 if (!DBA::isResult($r)) {
637 $errors .= self::printUpdateError($sql3);
640 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
641 if (!DBA::isResult($r)) {
642 $errors .= self::printUpdateError($sql3);
651 View::create(false, $action);
653 self::checkInitialValues();
655 if ($action && !$install) {
656 DI::config()->set('system', 'maintenance', 0);
657 DI::config()->set('system', 'maintenance_reason', '');
660 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
662 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
669 private static function tableStructure($table)
671 // This query doesn't seem to be executable as a prepared statement
672 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
674 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
675 ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
676 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
677 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
678 DBA::databaseName(), $table]);
680 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
681 ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
682 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
683 DBA::databaseName(), $table]);
685 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
686 ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
687 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
688 DBA::databaseName(), $table]);
694 if (DBA::isResult($foreign_keys)) {
695 foreach ($foreign_keys as $foreign_key) {
696 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
697 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
698 $foreigndata[$constraint] = $foreign_key;
702 if (DBA::isResult($indexes)) {
703 foreach ($indexes AS $index) {
704 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
705 $indexdata[$index["Key_name"]] = ["UNIQUE"];
708 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
709 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
712 $column = $index["Column_name"];
714 if ($index["Sub_part"] != "") {
715 $column .= "(" . $index["Sub_part"] . ")";
718 $indexdata[$index["Key_name"]][] = $column;
723 if (DBA::isResult($fields)) {
724 foreach ($fields AS $field) {
725 $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)'];
726 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
727 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
729 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
731 if ($field['IS_NULLABLE'] == 'NO') {
732 $fielddata[$field['COLUMN_NAME']]['not null'] = true;
735 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
736 $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
739 if (!empty($field['EXTRA'])) {
740 $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
743 if ($field['COLUMN_KEY'] == 'PRI') {
744 $fielddata[$field['COLUMN_NAME']]['primary'] = true;
747 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
748 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
752 return ["fields" => $fielddata, "indexes" => $indexdata,
753 "foreign_keys" => $foreigndata, "table_status" => $table_status];
756 private static function dropIndex($indexname)
758 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
762 private static function addTableField($fieldname, $parameters)
764 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
768 private static function modifyTableField($fieldname, $parameters)
770 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
774 private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
776 $foreign_table = array_keys($parameters['foreign'])[0];
777 $foreign_field = array_values($parameters['foreign'])[0];
779 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
782 private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
783 $foreign_table = array_keys($parameters['foreign'])[0];
784 $foreign_field = array_values($parameters['foreign'])[0];
786 $sql = "FOREIGN KEY (`" . $fieldname . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
788 if (!empty($parameters['foreign']['on update'])) {
789 $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
791 $sql .= " ON UPDATE RESTRICT";
794 if (!empty($parameters['foreign']['on delete'])) {
795 $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
797 $sql .= " ON DELETE CASCADE";
803 private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
805 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
808 private static function dropForeignKey(string $constraint)
810 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
814 * Constructs a GROUP BY clause from a UNIQUE index definition.
816 * @param array $fieldnames
819 private static function groupBy(array $fieldnames)
821 if ($fieldnames[0] != "UNIQUE") {
825 array_shift($fieldnames);
828 foreach ($fieldnames AS $fieldname) {
833 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
834 $names .= "`" . DBA::escape($matches[1]) . "`";
836 $names .= "`" . DBA::escape($fieldname) . "`";
840 $sql = sprintf(" GROUP BY %s", $names);
845 * Renames columns or the primary key of a table
847 * @todo You cannot rename a primary key if "auto increment" is set
849 * @param string $table Table name
850 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
851 * Syntax for Primary Key: [ $col1, $col2, ...]
852 * @param int $type The type of renaming (Default is Column)
854 * @return boolean Was the renaming successful?
857 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
859 if (empty($table) || empty($columns)) {
863 if (!is_array($columns)) {
867 $table = DBA::escape($table);
869 $sql = "ALTER TABLE `" . $table . "`";
871 case self::RENAME_COLUMN:
872 if (!self::existsColumn($table, array_keys($columns))) {
875 $sql .= implode(',', array_map(
876 function ($to, $from) {
877 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
883 case self::RENAME_PRIMARY_KEY:
884 if (!self::existsColumn($table, $columns)) {
887 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
895 $stmt = DBA::p($sql);
897 if (is_bool($stmt)) {
909 * Check if the columns of the table exists
911 * @param string $table Table name
912 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
914 * @return boolean Does the table exist?
917 public static function existsColumn($table, $columns = [])
923 if (is_null($columns) || empty($columns)) {
924 return self::existsTable($table);
927 $table = DBA::escape($table);
929 foreach ($columns AS $column) {
930 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
932 $stmt = DBA::p($sql);
934 if (is_bool($stmt)) {
937 $retval = (DBA::numRows($stmt) > 0);
951 * Check if a foreign key exists for the given table field
953 * @param string $table
954 * @param string $field
957 public static function existsForeignKeyForField(string $table, string $field)
959 return DBA::exists(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
960 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
961 DBA::databaseName(), $table, $field]);
964 * Check if a table exists
966 * @param string|array $table Table name
968 * @return boolean Does the table exist?
971 public static function existsTable($table)
977 if (is_array($table)) {
978 $condition = ['table_schema' => key($table), 'table_name' => current($table)];
980 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
983 $result = DBA::exists(['information_schema' => 'tables'], $condition);
989 * Returns the columns of a table
991 * @param string $table Table name
993 * @return array An array of the table columns
996 public static function getColumns($table)
998 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
999 return DBA::toArray($stmtColumns);
1003 * Check if initial database values do exist - or create them
1005 public static function checkInitialValues()
1007 if (self::existsTable('verb') && !DBA::exists('verb', ['id' => 1])) {
1008 foreach (Item::ACTIVITIES as $index => $activity) {
1009 DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], true);
1013 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
1014 DBA::insert('contact', ['nurl' => '']);
1015 $lastid = DBA::lastInsertId();
1017 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
1021 if (self::existsTable('permissionset')) {
1022 if (!DBA::exists('permissionset', ['id' => 0])) {
1023 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
1024 $lastid = DBA::lastInsertId();
1026 DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
1029 if (!self::existsForeignKeyForField('item', 'psid')) {
1030 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
1031 LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
1032 WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
1033 while ($set = DBA::fetch($sets)) {
1034 if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
1035 $owner = User::getOwnerDataById($set['uid']);
1037 $permission = '<' . $owner['id'] . '>';
1044 $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
1045 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
1046 DBA::insert('permissionset', $fields);
1052 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
1053 DBA::insert('tag', ['name' => '']);
1054 $lastid = DBA::lastInsertId();
1056 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
1060 if (!self::existsForeignKeyForField('tokens', 'client_id')) {
1061 $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
1062 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
1063 WHERE `clients`.`client_id` IS NULL");
1064 while ($token = DBA::fetch($tokens)) {
1065 DBA::delete('tokens', ['id' => $token['id']]);
1067 DBA::close($tokens);
1072 * Checks if a database update is currently running
1076 private static function isUpdating()
1080 $processes = DBA::select(['information_schema' => 'processlist'], ['info'],
1081 ['db' => DBA::databaseName(), 'command' => ['Query', 'Execute']]);
1083 while ($process = DBA::fetch($processes)) {
1084 $parts = explode(' ', $process['info']);
1085 if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
1090 DBA::close($processes);