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\Util\DateTimeFormat;
31 * This class contains functions that doesn't need to know if pdo, mysqli or whatever is used.
35 const UPDATE_NOT_CHECKED = 0; // Database check wasn't executed before
36 const UPDATE_SUCCESSFUL = 1; // Database check was successful
37 const UPDATE_FAILED = 2; // Database check failed
39 const RENAME_COLUMN = 0;
40 const RENAME_PRIMARY_KEY = 1;
43 * Database structure definition loaded from config/dbstructure.config.php
47 private static $definition = [];
50 * Converts all tables from MyISAM/InnoDB Antelope to InnoDB Barracuda
52 public static function convertToInnoDB()
54 $tables = DBA::selectToArray(
55 ['information_schema' => 'tables'],
57 ['engine' => 'MyISAM', 'table_schema' => DBA::databaseName()]
60 $tables = array_merge($tables, DBA::selectToArray(
61 ['information_schema' => 'tables'],
63 ['engine' => 'InnoDB', 'ROW_FORMAT' => ['COMPACT', 'REDUNDANT'], 'table_schema' => DBA::databaseName()]
66 if (!DBA::isResult($tables)) {
67 echo DI::l10n()->t('There are no tables on MyISAM or InnoDB with the Antelope file format.') . "\n";
71 foreach ($tables AS $table) {
72 $sql = "ALTER TABLE " . DBA::quoteIdentifier($table['table_name']) . " ENGINE=InnoDB ROW_FORMAT=DYNAMIC;";
75 $result = DBA::e($sql);
76 if (!DBA::isResult($result)) {
77 self::printUpdateError($sql);
83 * Print out database error messages
85 * @param string $message Message to be added to the error message
87 * @return string Error message
89 private static function printUpdateError($message)
91 echo DI::l10n()->t("\nError %d occurred during database update:\n%s\n",
92 DBA::errorNo(), DBA::errorMessage());
94 return DI::l10n()->t('Errors encountered performing database changes: ') . $message . EOL;
97 public static function printStructure($basePath)
99 $database = self::definition($basePath, false);
101 echo "-- ------------------------------------------\n";
102 echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n";
103 echo "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
104 echo "-- ------------------------------------------\n\n\n";
105 foreach ($database AS $name => $structure) {
107 echo "-- TABLE $name\n";
109 self::createTable($name, $structure, true, false);
114 View::printStructure($basePath);
118 * Loads the database structure definition from the static/dbstructure.config.php file.
119 * On first pass, defines DB_UPDATE_VERSION constant.
121 * @see static/dbstructure.config.php
122 * @param boolean $with_addons_structure Whether to tack on addons additional tables
123 * @param string $basePath The base path of this application
127 public static function definition($basePath, $with_addons_structure = true)
129 if (!self::$definition) {
131 $filename = $basePath . '/static/dbstructure.config.php';
133 if (!is_readable($filename)) {
134 throw new Exception('Missing database structure config file static/dbstructure.config.php');
137 $definition = require $filename;
140 throw new Exception('Corrupted database structure config file static/dbstructure.config.php');
143 self::$definition = $definition;
145 $definition = self::$definition;
148 if ($with_addons_structure) {
149 Hook::callAll('dbstructure_definition', $definition);
155 private static function createTable($name, $structure, $verbose, $action)
165 foreach ($structure["fields"] AS $fieldname => $field) {
166 $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
167 if (!empty($field['primary'])) {
168 $primary_keys[] = $fieldname;
170 if (!empty($field['foreign'])) {
171 $foreign_keys[$fieldname] = $field;
175 if (!empty($structure["indexes"])) {
176 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
177 $sql_index = self::createIndex($indexname, $fieldnames, "");
178 if (!is_null($sql_index)) {
179 $sql_rows[] = $sql_index;
184 foreach ($foreign_keys AS $fieldname => $parameters) {
185 $sql_rows[] = self::foreignCommand($name, $fieldname, $parameters);
188 if (isset($structure["engine"])) {
189 $engine = " ENGINE=" . $structure["engine"];
192 if (isset($structure["comment"])) {
193 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
196 $sql = implode(",\n\t", $sql_rows);
198 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
199 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
211 private static function FieldCommand($parameters, $create = true)
213 $fieldstruct = $parameters["type"];
215 if (isset($parameters["Collation"])) {
216 $fieldstruct .= " COLLATE " . $parameters["Collation"];
219 if (isset($parameters["not null"])) {
220 $fieldstruct .= " NOT NULL";
223 if (isset($parameters["default"])) {
224 if (strpos(strtolower($parameters["type"]), "int") !== false) {
225 $fieldstruct .= " DEFAULT " . $parameters["default"];
227 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
230 if (isset($parameters["extra"])) {
231 $fieldstruct .= " " . $parameters["extra"];
234 if (isset($parameters["comment"])) {
235 $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
238 /*if (($parameters["primary"] != "") && $create)
239 $fieldstruct .= " PRIMARY KEY";*/
241 return ($fieldstruct);
244 private static function createIndex($indexname, $fieldnames, $method = "ADD")
246 $method = strtoupper(trim($method));
247 if ($method != "" && $method != "ADD") {
248 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
251 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
252 $index_type = array_shift($fieldnames);
253 $method .= " " . $index_type;
257 foreach ($fieldnames AS $fieldname) {
262 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
263 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
265 $names .= "`" . DBA::escape($fieldname) . "`";
269 if ($indexname == "PRIMARY") {
270 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
274 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
279 * Updates DB structure and returns eventual errors messages
281 * @param string $basePath The base path of this application
282 * @param bool $verbose
283 * @param bool $action Whether to actually apply the update
284 * @param bool $install Is this the initial update during the installation?
285 * @param array $tables An array of the database tables
286 * @param array $definition An array of the definition tables
287 * @return string Empty string if the update is successful, error messages otherwise
290 public static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
292 if ($action && !$install) {
293 DI::config()->set('system', 'maintenance', 1);
294 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
297 // ensure that all initial values exist. This test has to be done prior and after the structure check.
298 // Prior is needed if the specific tables already exists - after is needed when they had been created.
299 self::checkInitialValues();
303 Logger::log('updating structure', Logger::DEBUG);
305 // Get the current structure
308 if (is_null($tables)) {
309 $tables = DBA::toArray(DBA::p("SHOW TABLES"));
312 if (DBA::isResult($tables)) {
313 foreach ($tables AS $table) {
314 $table = current($table);
316 Logger::log(sprintf('updating structure for table %s ...', $table), Logger::DEBUG);
317 $database[$table] = self::tableStructure($table);
321 // Get the definition
322 if (is_null($definition)) {
323 $definition = self::definition($basePath);
326 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
327 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
328 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
335 foreach ($definition AS $name => $structure) {
336 $is_new_table = false;
341 if (!isset($database[$name])) {
342 $r = self::createTable($name, $structure, $verbose, $action);
343 if (!DBA::isResult($r)) {
344 $errors .= self::printUpdateError($name);
346 $is_new_table = true;
348 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
349 if (isset($database[$name]["indexes"][$indexname])) {
350 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
352 $current_index_definition = "__NOT_SET__";
354 $new_index_definition = implode(",", $fieldnames);
355 if ($current_index_definition != $new_index_definition) {
356 if ($fieldnames[0] == "UNIQUE") {
359 $temp_name = "temp-" . $name;
366 * Drop the index if it isn't present in the definition
367 * or the definition differ from current status
368 * and index name doesn't start with "local_"
370 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
371 $current_index_definition = implode(",", $fieldnames);
372 if (isset($structure["indexes"][$indexname])) {
373 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
375 $new_index_definition = "__NOT_SET__";
377 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
378 $sql2 = self::dropIndex($indexname);
380 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
382 $sql3 .= ", " . $sql2;
386 // Compare the field structure field by field
387 foreach ($structure["fields"] AS $fieldname => $parameters) {
388 if (!isset($database[$name]["fields"][$fieldname])) {
389 $sql2 = self::addTableField($fieldname, $parameters);
391 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
393 $sql3 .= ", " . $sql2;
396 // Compare the field definition
397 $field_definition = $database[$name]["fields"][$fieldname];
399 // Remove the relation data that is used for the referential integrity
400 unset($parameters['relation']);
401 unset($parameters['foreign']);
403 // We change the collation after the indexes had been changed.
404 // This is done to avoid index length problems.
405 // So here we always ensure that there is no need to change it.
406 unset($parameters['Collation']);
407 unset($field_definition['Collation']);
409 // Only update the comment when it is defined
410 if (!isset($parameters['comment'])) {
411 $parameters['comment'] = "";
414 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
415 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
416 if ($current_field_definition != $new_field_definition) {
417 $sql2 = self::modifyTableField($fieldname, $parameters);
419 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
421 $sql3 .= ", " . $sql2;
429 * Create the index if the index don't exists in database
430 * or the definition differ from the current status.
431 * Don't create keys if table is new
433 if (!$is_new_table) {
434 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
435 if (isset($database[$name]["indexes"][$indexname])) {
436 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
438 $current_index_definition = "__NOT_SET__";
440 $new_index_definition = implode(",", $fieldnames);
441 if ($current_index_definition != $new_index_definition) {
442 $sql2 = self::createIndex($indexname, $fieldnames);
444 // Fetch the "group by" fields for unique indexes
445 $group_by = self::groupBy($fieldnames);
448 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
450 $sql3 .= ", " . $sql2;
456 $existing_foreign_keys = $database[$name]['foreign_keys'];
459 // Compare the field structure field by field
460 foreach ($structure["fields"] AS $fieldname => $parameters) {
461 if (empty($parameters['foreign'])) {
465 $constraint = self::getConstraintName($name, $fieldname, $parameters);
467 unset($existing_foreign_keys[$constraint]);
469 if (empty($database[$name]['foreign_keys'][$constraint])) {
470 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
473 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
475 $sql3 .= ", " . $sql2;
480 foreach ($existing_foreign_keys as $constraint => $param) {
481 $sql2 = self::dropForeignKey($constraint);
484 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
486 $sql3 .= ", " . $sql2;
490 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
491 $structurecomment = $structure["comment"] ?? '';
492 if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
493 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
496 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
498 $sql3 .= ", " . $sql2;
503 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
504 if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
505 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
508 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
510 $sql3 .= ", " . $sql2;
515 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
516 if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
517 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
520 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
522 $sql3 .= ", " . $sql2;
531 // Now have a look at the field collations
532 // Compare the field structure field by field
533 foreach ($structure["fields"] AS $fieldname => $parameters) {
534 // Compare the field definition
535 $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
537 // Define the default collation if not given
538 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
539 $parameters['Collation'] = 'utf8mb4_general_ci';
541 $parameters['Collation'] = null;
544 if ($field_definition['Collation'] != $parameters['Collation']) {
545 $sql2 = self::modifyTableField($fieldname, $parameters);
546 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
547 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
549 $sql3 .= ", " . $sql2;
556 if (substr($sql3, -2, 2) != "; ") {
561 if ($is_unique && $ignore == '') {
562 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
563 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
565 $field_list = rtrim($field_list, ',');
569 // Ensure index conversion to unique removes duplicates
570 if ($is_unique && ($temp_name != $name)) {
572 echo "SET session old_alter_table=1;\n";
574 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
575 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
581 if ($is_unique && ($temp_name != $name)) {
583 echo "SET session old_alter_table=0;\n";
585 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
586 echo "DROP TABLE `" . $name . "`;\n";
587 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
594 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
597 // Ensure index conversion to unique removes duplicates
598 if ($is_unique && ($temp_name != $name)) {
600 DBA::e("SET session old_alter_table=1;");
602 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
603 if (!DBA::isResult($r)) {
604 $errors .= self::printUpdateError($sql3);
608 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
609 if (!DBA::isResult($r)) {
610 $errors .= self::printUpdateError($sql3);
617 if (!DBA::isResult($r)) {
618 $errors .= self::printUpdateError($sql3);
620 if ($is_unique && ($temp_name != $name)) {
622 DBA::e("SET session old_alter_table=0;");
624 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
625 if (!DBA::isResult($r)) {
626 $errors .= self::printUpdateError($sql3);
629 $r = DBA::e("DROP TABLE `" . $name . "`;");
630 if (!DBA::isResult($r)) {
631 $errors .= self::printUpdateError($sql3);
634 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
635 if (!DBA::isResult($r)) {
636 $errors .= self::printUpdateError($sql3);
645 View::create(false, $action);
647 self::checkInitialValues();
649 if ($action && !$install) {
650 DI::config()->set('system', 'maintenance', 0);
651 DI::config()->set('system', 'maintenance_reason', '');
654 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
656 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
663 private static function tableStructure($table)
665 // This query doesn't seem to be executable as a prepared statement
666 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
668 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
669 ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
670 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
671 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
672 DBA::databaseName(), $table]);
674 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
675 ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
676 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
677 DBA::databaseName(), $table]);
679 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
680 ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
681 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
682 DBA::databaseName(), $table]);
688 if (DBA::isResult($foreign_keys)) {
689 foreach ($foreign_keys as $foreign_key) {
690 $constraint = $foreign_key['CONSTRAINT_NAME'];
691 unset($foreign_key['CONSTRAINT_NAME']);
692 $foreigndata[$constraint] = $foreign_key;
696 if (DBA::isResult($indexes)) {
697 foreach ($indexes AS $index) {
698 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
699 $indexdata[$index["Key_name"]] = ["UNIQUE"];
702 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
703 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
706 $column = $index["Column_name"];
708 if ($index["Sub_part"] != "") {
709 $column .= "(" . $index["Sub_part"] . ")";
712 $indexdata[$index["Key_name"]][] = $column;
717 if (DBA::isResult($fields)) {
718 foreach ($fields AS $field) {
719 $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)'];
720 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
721 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
723 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
725 if ($field['IS_NULLABLE'] == 'NO') {
726 $fielddata[$field['COLUMN_NAME']]['not null'] = true;
729 if (isset($field['COLUMN_DEFAULT'])) {
730 $fielddata[$field['COLUMN_NAME']]['default'] = $field['COLUMN_DEFAULT'];
733 if (!empty($field['EXTRA'])) {
734 $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
737 if ($field['COLUMN_KEY'] == 'PRI') {
738 $fielddata[$field['COLUMN_NAME']]['primary'] = true;
741 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
742 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
746 return ["fields" => $fielddata, "indexes" => $indexdata,
747 "foreign_keys" => $foreigndata, "table_status" => $table_status];
750 private static function dropIndex($indexname)
752 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
756 private static function addTableField($fieldname, $parameters)
758 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
762 private static function modifyTableField($fieldname, $parameters)
764 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
768 private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
770 $foreign_table = array_keys($parameters['foreign'])[0];
771 $foreign_field = array_values($parameters['foreign'])[0];
773 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
776 private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
777 $foreign_table = array_keys($parameters['foreign'])[0];
778 $foreign_field = array_values($parameters['foreign'])[0];
780 $constraint = self::getConstraintName($tablename, $fieldname, $parameters);
782 $sql = "CONSTRAINT `" . $constraint . "` FOREIGN KEY (`" . $fieldname . "`)" .
783 " REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
785 if (!empty($parameters['foreign']['on update'])) {
786 $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
788 $sql .= " ON UPDATE RESTRICT";
791 if (!empty($parameters['foreign']['on delete'])) {
792 $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
794 $sql .= " ON DELETE CASCADE";
800 private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
802 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
805 private static function dropForeignKey(string $constraint)
807 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
811 * Constructs a GROUP BY clause from a UNIQUE index definition.
813 * @param array $fieldnames
816 private static function groupBy(array $fieldnames)
818 if ($fieldnames[0] != "UNIQUE") {
822 array_shift($fieldnames);
825 foreach ($fieldnames AS $fieldname) {
830 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
831 $names .= "`" . DBA::escape($matches[1]) . "`";
833 $names .= "`" . DBA::escape($fieldname) . "`";
837 $sql = sprintf(" GROUP BY %s", $names);
842 * Renames columns or the primary key of a table
844 * @todo You cannot rename a primary key if "auto increment" is set
846 * @param string $table Table name
847 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
848 * Syntax for Primary Key: [ $col1, $col2, ...]
849 * @param int $type The type of renaming (Default is Column)
851 * @return boolean Was the renaming successful?
854 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
856 if (empty($table) || empty($columns)) {
860 if (!is_array($columns)) {
864 $table = DBA::escape($table);
866 $sql = "ALTER TABLE `" . $table . "`";
868 case self::RENAME_COLUMN:
869 if (!self::existsColumn($table, array_keys($columns))) {
872 $sql .= implode(',', array_map(
873 function ($to, $from) {
874 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
880 case self::RENAME_PRIMARY_KEY:
881 if (!self::existsColumn($table, $columns)) {
884 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
892 $stmt = DBA::p($sql);
894 if (is_bool($stmt)) {
906 * Check if the columns of the table exists
908 * @param string $table Table name
909 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
911 * @return boolean Does the table exist?
914 public static function existsColumn($table, $columns = [])
920 if (is_null($columns) || empty($columns)) {
921 return self::existsTable($table);
924 $table = DBA::escape($table);
926 foreach ($columns AS $column) {
927 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
929 $stmt = DBA::p($sql);
931 if (is_bool($stmt)) {
934 $retval = (DBA::numRows($stmt) > 0);
948 * Check if a table exists
950 * @param string|array $table Table name
952 * @return boolean Does the table exist?
955 public static function existsTable($table)
961 if (is_array($table)) {
962 $condition = ['table_schema' => key($table), 'table_name' => current($table)];
964 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
967 $result = DBA::exists(['information_schema' => 'tables'], $condition);
973 * Returns the columns of a table
975 * @param string $table Table name
977 * @return array An array of the table columns
980 public static function getColumns($table)
982 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
983 return DBA::toArray($stmtColumns);
987 * Check if initial database values do exist - or create them
989 public static function checkInitialValues()
991 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
992 DBA::insert('contact', ['nurl' => '']);
993 $lastid = DBA::lastInsertId();
995 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
999 if (self::existsTable('permissionset') && !DBA::exists('permissionset', ['id' => 0])) {
1000 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
1001 $lastid = DBA::lastInsertId();
1003 DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
1007 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
1008 DBA::insert('tag', ['name' => '']);
1009 $lastid = DBA::lastInsertId();
1011 DBA::update('tag', ['id' => 0], ['id' => $lastid]);