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 * Set a database version to trigger update functions
54 * @param string $version
57 public static function setDatabaseVersion(string $version)
59 if (!is_numeric($version)) {
60 throw new \Asika\SimpleConsole\CommandArgsException('The version number must be numeric');
63 DI::config()->set('system', 'build', $version);
64 echo DI::l10n()->t('The database version had been set to %s.', $version);
68 * Converts all tables from MyISAM/InnoDB Antelope to InnoDB Barracuda
70 public static function convertToInnoDB()
72 $tables = DBA::selectToArray(
73 ['information_schema' => 'tables'],
75 ['engine' => 'MyISAM', 'table_schema' => DBA::databaseName()]
78 $tables = array_merge($tables, DBA::selectToArray(
79 ['information_schema' => 'tables'],
81 ['engine' => 'InnoDB', 'ROW_FORMAT' => ['COMPACT', 'REDUNDANT'], 'table_schema' => DBA::databaseName()]
84 if (!DBA::isResult($tables)) {
85 echo DI::l10n()->t('There are no tables on MyISAM or InnoDB with the Antelope file format.') . "\n";
89 foreach ($tables AS $table) {
90 $sql = "ALTER TABLE " . DBA::quoteIdentifier($table['table_name']) . " ENGINE=InnoDB ROW_FORMAT=DYNAMIC;";
93 $result = DBA::e($sql);
94 if (!DBA::isResult($result)) {
95 self::printUpdateError($sql);
101 * Print out database error messages
103 * @param string $message Message to be added to the error message
105 * @return string Error message
107 private static function printUpdateError($message)
109 echo DI::l10n()->t("\nError %d occurred during database update:\n%s\n",
110 DBA::errorNo(), DBA::errorMessage());
112 return DI::l10n()->t('Errors encountered performing database changes: ') . $message . EOL;
115 public static function printStructure($basePath)
117 $database = self::definition($basePath, false);
119 echo "-- ------------------------------------------\n";
120 echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n";
121 echo "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
122 echo "-- ------------------------------------------\n\n\n";
123 foreach ($database AS $name => $structure) {
125 echo "-- TABLE $name\n";
127 self::createTable($name, $structure, true, false);
132 View::printStructure($basePath);
136 * Loads the database structure definition from the static/dbstructure.config.php file.
137 * On first pass, defines DB_UPDATE_VERSION constant.
139 * @see static/dbstructure.config.php
140 * @param boolean $with_addons_structure Whether to tack on addons additional tables
141 * @param string $basePath The base path of this application
145 public static function definition($basePath, $with_addons_structure = true)
147 if (!self::$definition) {
149 $filename = $basePath . '/static/dbstructure.config.php';
151 if (!is_readable($filename)) {
152 throw new Exception('Missing database structure config file static/dbstructure.config.php');
155 $definition = require $filename;
158 throw new Exception('Corrupted database structure config file static/dbstructure.config.php');
161 self::$definition = $definition;
163 $definition = self::$definition;
166 if ($with_addons_structure) {
167 Hook::callAll('dbstructure_definition', $definition);
173 private static function createTable($name, $structure, $verbose, $action)
183 foreach ($structure["fields"] AS $fieldname => $field) {
184 $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
185 if (!empty($field['primary'])) {
186 $primary_keys[] = $fieldname;
188 if (!empty($field['foreign'])) {
189 $foreign_keys[$fieldname] = $field;
193 if (!empty($structure["indexes"])) {
194 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
195 $sql_index = self::createIndex($indexname, $fieldnames, "");
196 if (!is_null($sql_index)) {
197 $sql_rows[] = $sql_index;
202 foreach ($foreign_keys AS $fieldname => $parameters) {
203 $sql_rows[] = self::foreignCommand($name, $fieldname, $parameters);
206 if (isset($structure["engine"])) {
207 $engine = " ENGINE=" . $structure["engine"];
210 if (isset($structure["comment"])) {
211 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
214 $sql = implode(",\n\t", $sql_rows);
216 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
217 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
229 private static function FieldCommand($parameters, $create = true)
231 $fieldstruct = $parameters["type"];
233 if (isset($parameters["Collation"])) {
234 $fieldstruct .= " COLLATE " . $parameters["Collation"];
237 if (isset($parameters["not null"])) {
238 $fieldstruct .= " NOT NULL";
241 if (isset($parameters["default"])) {
242 if (strpos(strtolower($parameters["type"]), "int") !== false) {
243 $fieldstruct .= " DEFAULT " . $parameters["default"];
245 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
248 if (isset($parameters["extra"])) {
249 $fieldstruct .= " " . $parameters["extra"];
252 if (isset($parameters["comment"])) {
253 $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
256 /*if (($parameters["primary"] != "") && $create)
257 $fieldstruct .= " PRIMARY KEY";*/
259 return ($fieldstruct);
262 private static function createIndex($indexname, $fieldnames, $method = "ADD")
264 $method = strtoupper(trim($method));
265 if ($method != "" && $method != "ADD") {
266 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
269 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
270 $index_type = array_shift($fieldnames);
271 $method .= " " . $index_type;
275 foreach ($fieldnames AS $fieldname) {
280 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
281 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
283 $names .= "`" . DBA::escape($fieldname) . "`";
287 if ($indexname == "PRIMARY") {
288 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
292 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
297 * Updates DB structure and returns eventual errors messages
299 * @param string $basePath The base path of this application
300 * @param bool $verbose
301 * @param bool $action Whether to actually apply the update
302 * @param bool $install Is this the initial update during the installation?
303 * @param array $tables An array of the database tables
304 * @param array $definition An array of the definition tables
305 * @return string Empty string if the update is successful, error messages otherwise
308 public static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
310 if ($action && !$install) {
311 if (self::isUpdating()) {
312 return DI::l10n()->t('Another database update is currently running.');
315 DI::config()->set('system', 'maintenance', 1);
316 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
319 // ensure that all initial values exist. This test has to be done prior and after the structure check.
320 // Prior is needed if the specific tables already exists - after is needed when they had been created.
321 self::checkInitialValues();
325 Logger::log('updating structure', Logger::DEBUG);
327 // Get the current structure
330 if (is_null($tables)) {
331 $tables = DBA::toArray(DBA::p("SHOW TABLES"));
334 if (DBA::isResult($tables)) {
335 foreach ($tables AS $table) {
336 $table = current($table);
338 Logger::log(sprintf('updating structure for table %s ...', $table), Logger::DEBUG);
339 $database[$table] = self::tableStructure($table);
343 // Get the definition
344 if (is_null($definition)) {
345 $definition = self::definition($basePath);
348 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
349 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
350 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
357 foreach ($definition AS $name => $structure) {
358 $is_new_table = false;
363 if (!isset($database[$name])) {
364 $r = self::createTable($name, $structure, $verbose, $action);
365 if (!DBA::isResult($r)) {
366 $errors .= self::printUpdateError($name);
368 $is_new_table = true;
370 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
371 if (isset($database[$name]["indexes"][$indexname])) {
372 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
374 $current_index_definition = "__NOT_SET__";
376 $new_index_definition = implode(",", $fieldnames);
377 if ($current_index_definition != $new_index_definition) {
378 if ($fieldnames[0] == "UNIQUE") {
381 $temp_name = "temp-" . $name;
388 * Drop the index if it isn't present in the definition
389 * or the definition differ from current status
390 * and index name doesn't start with "local_"
392 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
393 $current_index_definition = implode(",", $fieldnames);
394 if (isset($structure["indexes"][$indexname])) {
395 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
397 $new_index_definition = "__NOT_SET__";
399 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
400 $sql2 = self::dropIndex($indexname);
402 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
404 $sql3 .= ", " . $sql2;
408 // Compare the field structure field by field
409 foreach ($structure["fields"] AS $fieldname => $parameters) {
410 if (!isset($database[$name]["fields"][$fieldname])) {
411 $sql2 = self::addTableField($fieldname, $parameters);
413 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
415 $sql3 .= ", " . $sql2;
418 // Compare the field definition
419 $field_definition = $database[$name]["fields"][$fieldname];
421 // Remove the relation data that is used for the referential integrity
422 unset($parameters['relation']);
423 unset($parameters['foreign']);
425 // We change the collation after the indexes had been changed.
426 // This is done to avoid index length problems.
427 // So here we always ensure that there is no need to change it.
428 unset($parameters['Collation']);
429 unset($field_definition['Collation']);
431 // Only update the comment when it is defined
432 if (!isset($parameters['comment'])) {
433 $parameters['comment'] = "";
436 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
437 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
438 if ($current_field_definition != $new_field_definition) {
439 $sql2 = self::modifyTableField($fieldname, $parameters);
441 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
443 $sql3 .= ", " . $sql2;
451 * Create the index if the index don't exists in database
452 * or the definition differ from the current status.
453 * Don't create keys if table is new
455 if (!$is_new_table) {
456 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
457 if (isset($database[$name]["indexes"][$indexname])) {
458 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
460 $current_index_definition = "__NOT_SET__";
462 $new_index_definition = implode(",", $fieldnames);
463 if ($current_index_definition != $new_index_definition) {
464 $sql2 = self::createIndex($indexname, $fieldnames);
466 // Fetch the "group by" fields for unique indexes
467 $group_by = self::groupBy($fieldnames);
470 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
472 $sql3 .= ", " . $sql2;
478 $existing_foreign_keys = $database[$name]['foreign_keys'];
481 // Compare the field structure field by field
482 foreach ($structure["fields"] AS $fieldname => $parameters) {
483 if (empty($parameters['foreign'])) {
487 $constraint = self::getConstraintName($name, $fieldname, $parameters);
489 unset($existing_foreign_keys[$constraint]);
491 if (empty($database[$name]['foreign_keys'][$constraint])) {
492 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
495 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
497 $sql3 .= ", " . $sql2;
502 foreach ($existing_foreign_keys as $param) {
503 $sql2 = self::dropForeignKey($param['CONSTRAINT_NAME']);
506 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
508 $sql3 .= ", " . $sql2;
512 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
513 $structurecomment = $structure["comment"] ?? '';
514 if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
515 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
518 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
520 $sql3 .= ", " . $sql2;
525 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
526 if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
527 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
530 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
532 $sql3 .= ", " . $sql2;
537 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
538 if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
539 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
542 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
544 $sql3 .= ", " . $sql2;
553 // Now have a look at the field collations
554 // Compare the field structure field by field
555 foreach ($structure["fields"] AS $fieldname => $parameters) {
556 // Compare the field definition
557 $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
559 // Define the default collation if not given
560 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
561 $parameters['Collation'] = 'utf8mb4_general_ci';
563 $parameters['Collation'] = null;
566 if ($field_definition['Collation'] != $parameters['Collation']) {
567 $sql2 = self::modifyTableField($fieldname, $parameters);
568 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
569 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
571 $sql3 .= ", " . $sql2;
578 if (substr($sql3, -2, 2) != "; ") {
583 if ($is_unique && $ignore == '') {
584 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
585 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
587 $field_list = rtrim($field_list, ',');
591 // Ensure index conversion to unique removes duplicates
592 if ($is_unique && ($temp_name != $name)) {
594 echo "SET session old_alter_table=1;\n";
596 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
597 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
603 if ($is_unique && ($temp_name != $name)) {
605 echo "SET session old_alter_table=0;\n";
607 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
608 echo "DROP TABLE `" . $name . "`;\n";
609 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
616 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
619 // Ensure index conversion to unique removes duplicates
620 if ($is_unique && ($temp_name != $name)) {
622 DBA::e("SET session old_alter_table=1;");
624 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
625 if (!DBA::isResult($r)) {
626 $errors .= self::printUpdateError($sql3);
630 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
631 if (!DBA::isResult($r)) {
632 $errors .= self::printUpdateError($sql3);
639 if (!DBA::isResult($r)) {
640 $errors .= self::printUpdateError($sql3);
642 if ($is_unique && ($temp_name != $name)) {
644 DBA::e("SET session old_alter_table=0;");
646 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
647 if (!DBA::isResult($r)) {
648 $errors .= self::printUpdateError($sql3);
651 $r = DBA::e("DROP TABLE `" . $name . "`;");
652 if (!DBA::isResult($r)) {
653 $errors .= self::printUpdateError($sql3);
656 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
657 if (!DBA::isResult($r)) {
658 $errors .= self::printUpdateError($sql3);
667 View::create(false, $action);
669 self::checkInitialValues();
671 if ($action && !$install) {
672 DI::config()->set('system', 'maintenance', 0);
673 DI::config()->set('system', 'maintenance_reason', '');
676 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
678 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
685 private static function tableStructure($table)
687 // This query doesn't seem to be executable as a prepared statement
688 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
690 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
691 ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
692 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
693 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
694 DBA::databaseName(), $table]);
696 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
697 ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
698 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
699 DBA::databaseName(), $table]);
701 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
702 ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
703 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
704 DBA::databaseName(), $table]);
710 if (DBA::isResult($foreign_keys)) {
711 foreach ($foreign_keys as $foreign_key) {
712 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
713 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
714 $foreigndata[$constraint] = $foreign_key;
718 if (DBA::isResult($indexes)) {
719 foreach ($indexes AS $index) {
720 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
721 $indexdata[$index["Key_name"]] = ["UNIQUE"];
724 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
725 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
728 $column = $index["Column_name"];
730 if ($index["Sub_part"] != "") {
731 $column .= "(" . $index["Sub_part"] . ")";
734 $indexdata[$index["Key_name"]][] = $column;
739 if (DBA::isResult($fields)) {
740 foreach ($fields AS $field) {
741 $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)'];
742 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
743 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
745 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
747 if ($field['IS_NULLABLE'] == 'NO') {
748 $fielddata[$field['COLUMN_NAME']]['not null'] = true;
751 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
752 $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
755 if (!empty($field['EXTRA'])) {
756 $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
759 if ($field['COLUMN_KEY'] == 'PRI') {
760 $fielddata[$field['COLUMN_NAME']]['primary'] = true;
763 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
764 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
768 return ["fields" => $fielddata, "indexes" => $indexdata,
769 "foreign_keys" => $foreigndata, "table_status" => $table_status];
772 private static function dropIndex($indexname)
774 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
778 private static function addTableField($fieldname, $parameters)
780 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
784 private static function modifyTableField($fieldname, $parameters)
786 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
790 private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
792 $foreign_table = array_keys($parameters['foreign'])[0];
793 $foreign_field = array_values($parameters['foreign'])[0];
795 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
798 private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
799 $foreign_table = array_keys($parameters['foreign'])[0];
800 $foreign_field = array_values($parameters['foreign'])[0];
802 $sql = "FOREIGN KEY (`" . $fieldname . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
804 if (!empty($parameters['foreign']['on update'])) {
805 $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
807 $sql .= " ON UPDATE RESTRICT";
810 if (!empty($parameters['foreign']['on delete'])) {
811 $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
813 $sql .= " ON DELETE CASCADE";
819 private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
821 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
824 private static function dropForeignKey(string $constraint)
826 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
830 * Constructs a GROUP BY clause from a UNIQUE index definition.
832 * @param array $fieldnames
835 private static function groupBy(array $fieldnames)
837 if ($fieldnames[0] != "UNIQUE") {
841 array_shift($fieldnames);
844 foreach ($fieldnames AS $fieldname) {
849 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
850 $names .= "`" . DBA::escape($matches[1]) . "`";
852 $names .= "`" . DBA::escape($fieldname) . "`";
856 $sql = sprintf(" GROUP BY %s", $names);
861 * Renames columns or the primary key of a table
863 * @todo You cannot rename a primary key if "auto increment" is set
865 * @param string $table Table name
866 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
867 * Syntax for Primary Key: [ $col1, $col2, ...]
868 * @param int $type The type of renaming (Default is Column)
870 * @return boolean Was the renaming successful?
873 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
875 if (empty($table) || empty($columns)) {
879 if (!is_array($columns)) {
883 $table = DBA::escape($table);
885 $sql = "ALTER TABLE `" . $table . "`";
887 case self::RENAME_COLUMN:
888 if (!self::existsColumn($table, array_keys($columns))) {
891 $sql .= implode(',', array_map(
892 function ($to, $from) {
893 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
899 case self::RENAME_PRIMARY_KEY:
900 if (!self::existsColumn($table, $columns)) {
903 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
911 $stmt = DBA::p($sql);
913 if (is_bool($stmt)) {
925 * Check if the columns of the table exists
927 * @param string $table Table name
928 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
930 * @return boolean Does the table exist?
933 public static function existsColumn($table, $columns = [])
939 if (is_null($columns) || empty($columns)) {
940 return self::existsTable($table);
943 $table = DBA::escape($table);
945 foreach ($columns AS $column) {
946 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
948 $stmt = DBA::p($sql);
950 if (is_bool($stmt)) {
953 $retval = (DBA::numRows($stmt) > 0);
967 * Check if a foreign key exists for the given table field
969 * @param string $table
970 * @param string $field
973 public static function existsForeignKeyForField(string $table, string $field)
975 return DBA::exists(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
976 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
977 DBA::databaseName(), $table, $field]);
980 * Check if a table exists
982 * @param string|array $table Table name
984 * @return boolean Does the table exist?
987 public static function existsTable($table)
993 if (is_array($table)) {
994 $condition = ['table_schema' => key($table), 'table_name' => current($table)];
996 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
999 $result = DBA::exists(['information_schema' => 'tables'], $condition);
1005 * Returns the columns of a table
1007 * @param string $table Table name
1009 * @return array An array of the table columns
1012 public static function getColumns($table)
1014 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
1015 return DBA::toArray($stmtColumns);
1019 * Check if initial database values do exist - or create them
1021 public static function checkInitialValues()
1023 if (self::existsTable('verb') && !DBA::exists('verb', ['id' => 1])) {
1024 foreach (Item::ACTIVITIES as $index => $activity) {
1025 DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], true);
1029 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
1030 DBA::insert('contact', ['nurl' => '']);
1031 $lastid = DBA::lastInsertId();
1033 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
1037 if (self::existsTable('permissionset')) {
1038 if (!DBA::exists('permissionset', ['id' => 0])) {
1039 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
1040 $lastid = DBA::lastInsertId();
1042 DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
1045 if (!self::existsForeignKeyForField('item', 'psid')) {
1046 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
1047 LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
1048 WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
1049 while ($set = DBA::fetch($sets)) {
1050 if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
1051 $owner = User::getOwnerDataById($set['uid']);
1053 $permission = '<' . $owner['id'] . '>';
1060 $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
1061 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
1062 DBA::insert('permissionset', $fields);
1068 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
1069 DBA::insert('tag', ['name' => '']);
1070 $lastid = DBA::lastInsertId();
1072 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
1076 if (!self::existsForeignKeyForField('tokens', 'client_id')) {
1077 $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
1078 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
1079 WHERE `clients`.`client_id` IS NULL");
1080 while ($token = DBA::fetch($tokens)) {
1081 DBA::delete('tokens', ['id' => $token['id']]);
1083 DBA::close($tokens);
1088 * Checks if a database update is currently running
1092 private static function isUpdating()
1096 $processes = DBA::select(['information_schema' => 'processlist'], ['info'],
1097 ['db' => DBA::databaseName(), 'command' => ['Query', 'Execute']]);
1099 while ($process = DBA::fetch($processes)) {
1100 $parts = explode(' ', $process['info']);
1101 if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
1106 DBA::close($processes);