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')));
299 Logger::log('updating structure', Logger::DEBUG);
301 // Get the current structure
304 if (is_null($tables)) {
305 $tables = DBA::toArray(DBA::p("SHOW TABLES"));
308 if (DBA::isResult($tables)) {
309 foreach ($tables AS $table) {
310 $table = current($table);
312 Logger::log(sprintf('updating structure for table %s ...', $table), Logger::DEBUG);
313 $database[$table] = self::tableStructure($table);
317 // Get the definition
318 if (is_null($definition)) {
319 $definition = self::definition($basePath);
322 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
323 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
324 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
331 foreach ($definition AS $name => $structure) {
332 $is_new_table = false;
337 if (!isset($database[$name])) {
338 $r = self::createTable($name, $structure, $verbose, $action);
339 if (!DBA::isResult($r)) {
340 $errors .= self::printUpdateError($name);
342 $is_new_table = true;
344 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
345 if (isset($database[$name]["indexes"][$indexname])) {
346 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
348 $current_index_definition = "__NOT_SET__";
350 $new_index_definition = implode(",", $fieldnames);
351 if ($current_index_definition != $new_index_definition) {
352 if ($fieldnames[0] == "UNIQUE") {
355 $temp_name = "temp-" . $name;
362 * Drop the index if it isn't present in the definition
363 * or the definition differ from current status
364 * and index name doesn't start with "local_"
366 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
367 $current_index_definition = implode(",", $fieldnames);
368 if (isset($structure["indexes"][$indexname])) {
369 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
371 $new_index_definition = "__NOT_SET__";
373 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
374 $sql2 = self::dropIndex($indexname);
376 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
378 $sql3 .= ", " . $sql2;
382 // Compare the field structure field by field
383 foreach ($structure["fields"] AS $fieldname => $parameters) {
384 if (!isset($database[$name]["fields"][$fieldname])) {
385 $sql2 = self::addTableField($fieldname, $parameters);
387 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
389 $sql3 .= ", " . $sql2;
392 // Compare the field definition
393 $field_definition = $database[$name]["fields"][$fieldname];
395 // Remove the relation data that is used for the referential integrity
396 unset($parameters['relation']);
397 unset($parameters['foreign']);
399 // We change the collation after the indexes had been changed.
400 // This is done to avoid index length problems.
401 // So here we always ensure that there is no need to change it.
402 unset($parameters['Collation']);
403 unset($field_definition['Collation']);
405 // Only update the comment when it is defined
406 if (!isset($parameters['comment'])) {
407 $parameters['comment'] = "";
410 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
411 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
412 if ($current_field_definition != $new_field_definition) {
413 $sql2 = self::modifyTableField($fieldname, $parameters);
415 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
417 $sql3 .= ", " . $sql2;
425 * Create the index if the index don't exists in database
426 * or the definition differ from the current status.
427 * Don't create keys if table is new
429 if (!$is_new_table) {
430 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
431 if (isset($database[$name]["indexes"][$indexname])) {
432 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
434 $current_index_definition = "__NOT_SET__";
436 $new_index_definition = implode(",", $fieldnames);
437 if ($current_index_definition != $new_index_definition) {
438 $sql2 = self::createIndex($indexname, $fieldnames);
440 // Fetch the "group by" fields for unique indexes
441 $group_by = self::groupBy($fieldnames);
444 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
446 $sql3 .= ", " . $sql2;
452 $existing_foreign_keys = $database[$name]['foreign_keys'];
455 // Compare the field structure field by field
456 foreach ($structure["fields"] AS $fieldname => $parameters) {
457 if (empty($parameters['foreign'])) {
461 $constraint = self::getConstraintName($name, $fieldname, $parameters);
463 unset($existing_foreign_keys[$constraint]);
465 if (empty($database[$name]['foreign_keys'][$constraint])) {
466 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
469 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
471 $sql3 .= ", " . $sql2;
476 foreach ($existing_foreign_keys as $constraint => $param) {
477 $sql2 = self::dropForeignKey($constraint);
480 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
482 $sql3 .= ", " . $sql2;
486 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
487 $structurecomment = $structure["comment"] ?? '';
488 if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
489 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
492 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
494 $sql3 .= ", " . $sql2;
499 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
500 if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
501 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
504 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
506 $sql3 .= ", " . $sql2;
511 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
512 if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
513 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
516 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
518 $sql3 .= ", " . $sql2;
527 // Now have a look at the field collations
528 // Compare the field structure field by field
529 foreach ($structure["fields"] AS $fieldname => $parameters) {
530 // Compare the field definition
531 $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
533 // Define the default collation if not given
534 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
535 $parameters['Collation'] = 'utf8mb4_general_ci';
537 $parameters['Collation'] = null;
540 if ($field_definition['Collation'] != $parameters['Collation']) {
541 $sql2 = self::modifyTableField($fieldname, $parameters);
542 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
543 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
545 $sql3 .= ", " . $sql2;
552 if (substr($sql3, -2, 2) != "; ") {
557 if ($is_unique && $ignore == '') {
558 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
559 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
561 $field_list = rtrim($field_list, ',');
565 // Ensure index conversion to unique removes duplicates
566 if ($is_unique && ($temp_name != $name)) {
568 echo "SET session old_alter_table=1;\n";
570 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
571 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
577 if ($is_unique && ($temp_name != $name)) {
579 echo "SET session old_alter_table=0;\n";
581 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
582 echo "DROP TABLE `" . $name . "`;\n";
583 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
590 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
593 // Ensure index conversion to unique removes duplicates
594 if ($is_unique && ($temp_name != $name)) {
596 DBA::e("SET session old_alter_table=1;");
598 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
599 if (!DBA::isResult($r)) {
600 $errors .= self::printUpdateError($sql3);
604 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
605 if (!DBA::isResult($r)) {
606 $errors .= self::printUpdateError($sql3);
613 if (!DBA::isResult($r)) {
614 $errors .= self::printUpdateError($sql3);
616 if ($is_unique && ($temp_name != $name)) {
618 DBA::e("SET session old_alter_table=0;");
620 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
621 if (!DBA::isResult($r)) {
622 $errors .= self::printUpdateError($sql3);
625 $r = DBA::e("DROP TABLE `" . $name . "`;");
626 if (!DBA::isResult($r)) {
627 $errors .= self::printUpdateError($sql3);
630 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
631 if (!DBA::isResult($r)) {
632 $errors .= self::printUpdateError($sql3);
641 View::create(false, $action);
643 if ($action && !$install) {
644 DI::config()->set('system', 'maintenance', 0);
645 DI::config()->set('system', 'maintenance_reason', '');
648 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
650 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
657 private static function tableStructure($table)
659 // This query doesn't seem to be executable as a prepared statement
660 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
662 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
663 ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
664 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
665 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
666 DBA::databaseName(), $table]);
668 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
669 ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
670 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
671 DBA::databaseName(), $table]);
673 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
674 ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
675 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
676 DBA::databaseName(), $table]);
682 if (DBA::isResult($foreign_keys)) {
683 foreach ($foreign_keys as $foreign_key) {
684 $constraint = $foreign_key['CONSTRAINT_NAME'];
685 unset($foreign_key['CONSTRAINT_NAME']);
686 $foreigndata[$constraint] = $foreign_key;
690 if (DBA::isResult($indexes)) {
691 foreach ($indexes AS $index) {
692 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
693 $indexdata[$index["Key_name"]] = ["UNIQUE"];
696 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
697 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
700 $column = $index["Column_name"];
702 if ($index["Sub_part"] != "") {
703 $column .= "(" . $index["Sub_part"] . ")";
706 $indexdata[$index["Key_name"]][] = $column;
711 if (DBA::isResult($fields)) {
712 foreach ($fields AS $field) {
713 $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)'];
714 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
715 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
717 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
719 if ($field['IS_NULLABLE'] == 'NO') {
720 $fielddata[$field['COLUMN_NAME']]['not null'] = true;
723 if (isset($field['COLUMN_DEFAULT'])) {
724 $fielddata[$field['COLUMN_NAME']]['default'] = $field['COLUMN_DEFAULT'];
727 if (!empty($field['EXTRA'])) {
728 $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
731 if ($field['COLUMN_KEY'] == 'PRI') {
732 $fielddata[$field['COLUMN_NAME']]['primary'] = true;
735 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
736 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
740 return ["fields" => $fielddata, "indexes" => $indexdata,
741 "foreign_keys" => $foreigndata, "table_status" => $table_status];
744 private static function dropIndex($indexname)
746 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
750 private static function addTableField($fieldname, $parameters)
752 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
756 private static function modifyTableField($fieldname, $parameters)
758 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
762 private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
764 $foreign_table = array_keys($parameters['foreign'])[0];
765 $foreign_field = array_values($parameters['foreign'])[0];
767 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
770 private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
771 $foreign_table = array_keys($parameters['foreign'])[0];
772 $foreign_field = array_values($parameters['foreign'])[0];
774 $constraint = self::getConstraintName($tablename, $fieldname, $parameters);
776 $sql = "CONSTRAINT `" . $constraint . "` FOREIGN KEY (`" . $fieldname . "`)" .
777 " REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
779 if (!empty($parameters['foreign']['on update'])) {
780 $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
782 $sql .= " ON UPDATE RESTRICT";
785 if (!empty($parameters['foreign']['on delete'])) {
786 $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
788 $sql .= " ON DELETE CASCADE";
794 private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
796 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
799 private static function dropForeignKey(string $constraint)
801 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
805 * Constructs a GROUP BY clause from a UNIQUE index definition.
807 * @param array $fieldnames
810 private static function groupBy(array $fieldnames)
812 if ($fieldnames[0] != "UNIQUE") {
816 array_shift($fieldnames);
819 foreach ($fieldnames AS $fieldname) {
824 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
825 $names .= "`" . DBA::escape($matches[1]) . "`";
827 $names .= "`" . DBA::escape($fieldname) . "`";
831 $sql = sprintf(" GROUP BY %s", $names);
836 * Renames columns or the primary key of a table
838 * @todo You cannot rename a primary key if "auto increment" is set
840 * @param string $table Table name
841 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
842 * Syntax for Primary Key: [ $col1, $col2, ...]
843 * @param int $type The type of renaming (Default is Column)
845 * @return boolean Was the renaming successful?
848 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
850 if (empty($table) || empty($columns)) {
854 if (!is_array($columns)) {
858 $table = DBA::escape($table);
860 $sql = "ALTER TABLE `" . $table . "`";
862 case self::RENAME_COLUMN:
863 if (!self::existsColumn($table, array_keys($columns))) {
866 $sql .= implode(',', array_map(
867 function ($to, $from) {
868 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
874 case self::RENAME_PRIMARY_KEY:
875 if (!self::existsColumn($table, $columns)) {
878 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
886 $stmt = DBA::p($sql);
888 if (is_bool($stmt)) {
900 * Check if the columns of the table exists
902 * @param string $table Table name
903 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
905 * @return boolean Does the table exist?
908 public static function existsColumn($table, $columns = [])
914 if (is_null($columns) || empty($columns)) {
915 return self::existsTable($table);
918 $table = DBA::escape($table);
920 foreach ($columns AS $column) {
921 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
923 $stmt = DBA::p($sql);
925 if (is_bool($stmt)) {
928 $retval = (DBA::numRows($stmt) > 0);
942 * Check if a table exists
944 * @param string|array $table Table name
946 * @return boolean Does the table exist?
949 public static function existsTable($table)
955 if (is_array($table)) {
956 $condition = ['table_schema' => key($table), 'table_name' => current($table)];
958 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
961 $result = DBA::exists(['information_schema' => 'tables'], $condition);
967 * Returns the columns of a table
969 * @param string $table Table name
971 * @return array An array of the table columns
974 public static function getColumns($table)
976 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
977 return DBA::toArray($stmtColumns);