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);
174 * Get field data for the given table
176 * @param string $table
177 * @param array $data data fields
178 * @return array fields for the given
180 public static function getFieldsForTable(string $table, array $data = [])
182 $definition = DBStructure::definition('', false);
183 if (empty($definition[$table])) {
187 $fieldnames = array_keys($definition[$table]['fields']);
191 // Assign all field that are present in the table
192 foreach ($fieldnames as $field) {
193 if (isset($data[$field])) {
194 $fields[$field] = $data[$field];
201 private static function createTable($name, $structure, $verbose, $action)
211 foreach ($structure["fields"] AS $fieldname => $field) {
212 $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
213 if (!empty($field['primary'])) {
214 $primary_keys[] = $fieldname;
216 if (!empty($field['foreign'])) {
217 $foreign_keys[$fieldname] = $field;
221 if (!empty($structure["indexes"])) {
222 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
223 $sql_index = self::createIndex($indexname, $fieldnames, "");
224 if (!is_null($sql_index)) {
225 $sql_rows[] = $sql_index;
230 foreach ($foreign_keys AS $fieldname => $parameters) {
231 $sql_rows[] = self::foreignCommand($name, $fieldname, $parameters);
234 if (isset($structure["engine"])) {
235 $engine = " ENGINE=" . $structure["engine"];
238 if (isset($structure["comment"])) {
239 $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
242 $sql = implode(",\n\t", $sql_rows);
244 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
245 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
257 private static function FieldCommand($parameters, $create = true)
259 $fieldstruct = $parameters["type"];
261 if (isset($parameters["Collation"])) {
262 $fieldstruct .= " COLLATE " . $parameters["Collation"];
265 if (isset($parameters["not null"])) {
266 $fieldstruct .= " NOT NULL";
269 if (isset($parameters["default"])) {
270 if (strpos(strtolower($parameters["type"]), "int") !== false) {
271 $fieldstruct .= " DEFAULT " . $parameters["default"];
273 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
276 if (isset($parameters["extra"])) {
277 $fieldstruct .= " " . $parameters["extra"];
280 if (isset($parameters["comment"])) {
281 $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
284 /*if (($parameters["primary"] != "") && $create)
285 $fieldstruct .= " PRIMARY KEY";*/
287 return ($fieldstruct);
290 private static function createIndex($indexname, $fieldnames, $method = "ADD")
292 $method = strtoupper(trim($method));
293 if ($method != "" && $method != "ADD") {
294 throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
297 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
298 $index_type = array_shift($fieldnames);
299 $method .= " " . $index_type;
303 foreach ($fieldnames AS $fieldname) {
308 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
309 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
311 $names .= "`" . DBA::escape($fieldname) . "`";
315 if ($indexname == "PRIMARY") {
316 return sprintf("%s PRIMARY KEY(%s)", $method, $names);
320 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
325 * Updates DB structure and returns eventual errors messages
327 * @param string $basePath The base path of this application
328 * @param bool $verbose
329 * @param bool $action Whether to actually apply the update
330 * @param bool $install Is this the initial update during the installation?
331 * @param array $tables An array of the database tables
332 * @param array $definition An array of the definition tables
333 * @return string Empty string if the update is successful, error messages otherwise
336 public static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
338 if ($action && !$install) {
339 if (self::isUpdating()) {
340 return DI::l10n()->t('Another database update is currently running.');
343 DI::config()->set('system', 'maintenance', 1);
344 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
347 // ensure that all initial values exist. This test has to be done prior and after the structure check.
348 // Prior is needed if the specific tables already exists - after is needed when they had been created.
349 self::checkInitialValues();
353 Logger::log('updating structure', Logger::DEBUG);
355 // Get the current structure
358 if (is_null($tables)) {
359 $tables = DBA::toArray(DBA::p("SHOW TABLES"));
362 if (DBA::isResult($tables)) {
363 foreach ($tables AS $table) {
364 $table = current($table);
366 Logger::log(sprintf('updating structure for table %s ...', $table), Logger::DEBUG);
367 $database[$table] = self::tableStructure($table);
371 // Get the definition
372 if (is_null($definition)) {
373 $definition = self::definition($basePath);
376 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
377 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
378 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
385 foreach ($definition AS $name => $structure) {
386 $is_new_table = false;
391 if (!isset($database[$name])) {
392 $r = self::createTable($name, $structure, $verbose, $action);
393 if (!DBA::isResult($r)) {
394 $errors .= self::printUpdateError($name);
396 $is_new_table = true;
398 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
399 if (isset($database[$name]["indexes"][$indexname])) {
400 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
402 $current_index_definition = "__NOT_SET__";
404 $new_index_definition = implode(",", $fieldnames);
405 if ($current_index_definition != $new_index_definition) {
406 if ($fieldnames[0] == "UNIQUE") {
409 $temp_name = "temp-" . $name;
416 * Drop the index if it isn't present in the definition
417 * or the definition differ from current status
418 * and index name doesn't start with "local_"
420 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
421 $current_index_definition = implode(",", $fieldnames);
422 if (isset($structure["indexes"][$indexname])) {
423 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
425 $new_index_definition = "__NOT_SET__";
427 if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
428 $sql2 = self::dropIndex($indexname);
430 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
432 $sql3 .= ", " . $sql2;
436 // Compare the field structure field by field
437 foreach ($structure["fields"] AS $fieldname => $parameters) {
438 if (!isset($database[$name]["fields"][$fieldname])) {
439 $sql2 = self::addTableField($fieldname, $parameters);
441 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
443 $sql3 .= ", " . $sql2;
446 // Compare the field definition
447 $field_definition = $database[$name]["fields"][$fieldname];
449 // Remove the relation data that is used for the referential integrity
450 unset($parameters['relation']);
451 unset($parameters['foreign']);
453 // We change the collation after the indexes had been changed.
454 // This is done to avoid index length problems.
455 // So here we always ensure that there is no need to change it.
456 unset($parameters['Collation']);
457 unset($field_definition['Collation']);
459 // Only update the comment when it is defined
460 if (!isset($parameters['comment'])) {
461 $parameters['comment'] = "";
464 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
465 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
466 if ($current_field_definition != $new_field_definition) {
467 $sql2 = self::modifyTableField($fieldname, $parameters);
469 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
471 $sql3 .= ", " . $sql2;
479 * Create the index if the index don't exists in database
480 * or the definition differ from the current status.
481 * Don't create keys if table is new
483 if (!$is_new_table) {
484 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
485 if (isset($database[$name]["indexes"][$indexname])) {
486 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
488 $current_index_definition = "__NOT_SET__";
490 $new_index_definition = implode(",", $fieldnames);
491 if ($current_index_definition != $new_index_definition) {
492 $sql2 = self::createIndex($indexname, $fieldnames);
494 // Fetch the "group by" fields for unique indexes
495 $group_by = self::groupBy($fieldnames);
498 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
500 $sql3 .= ", " . $sql2;
506 $existing_foreign_keys = $database[$name]['foreign_keys'];
509 // Compare the field structure field by field
510 foreach ($structure["fields"] AS $fieldname => $parameters) {
511 if (empty($parameters['foreign'])) {
515 $constraint = self::getConstraintName($name, $fieldname, $parameters);
517 unset($existing_foreign_keys[$constraint]);
519 if (empty($database[$name]['foreign_keys'][$constraint])) {
520 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
523 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
525 $sql3 .= ", " . $sql2;
530 foreach ($existing_foreign_keys as $param) {
531 $sql2 = self::dropForeignKey($param['CONSTRAINT_NAME']);
534 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
536 $sql3 .= ", " . $sql2;
540 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
541 $structurecomment = $structure["comment"] ?? '';
542 if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
543 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
546 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
548 $sql3 .= ", " . $sql2;
553 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
554 if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
555 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
558 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
560 $sql3 .= ", " . $sql2;
565 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
566 if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
567 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
570 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
572 $sql3 .= ", " . $sql2;
581 // Now have a look at the field collations
582 // Compare the field structure field by field
583 foreach ($structure["fields"] AS $fieldname => $parameters) {
584 // Compare the field definition
585 $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
587 // Define the default collation if not given
588 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
589 $parameters['Collation'] = 'utf8mb4_general_ci';
591 $parameters['Collation'] = null;
594 if ($field_definition['Collation'] != $parameters['Collation']) {
595 $sql2 = self::modifyTableField($fieldname, $parameters);
596 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
597 $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
599 $sql3 .= ", " . $sql2;
606 if (substr($sql3, -2, 2) != "; ") {
611 if ($is_unique && $ignore == '') {
612 foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
613 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
615 $field_list = rtrim($field_list, ',');
619 // Ensure index conversion to unique removes duplicates
620 if ($is_unique && ($temp_name != $name)) {
622 echo "SET session old_alter_table=1;\n";
624 echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
625 echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
631 if ($is_unique && ($temp_name != $name)) {
633 echo "SET session old_alter_table=0;\n";
635 echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
636 echo "DROP TABLE `" . $name . "`;\n";
637 echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
644 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
647 // Ensure index conversion to unique removes duplicates
648 if ($is_unique && ($temp_name != $name)) {
650 DBA::e("SET session old_alter_table=1;");
652 $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
653 if (!DBA::isResult($r)) {
654 $errors .= self::printUpdateError($sql3);
658 $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
659 if (!DBA::isResult($r)) {
660 $errors .= self::printUpdateError($sql3);
667 if (!DBA::isResult($r)) {
668 $errors .= self::printUpdateError($sql3);
670 if ($is_unique && ($temp_name != $name)) {
672 DBA::e("SET session old_alter_table=0;");
674 $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
675 if (!DBA::isResult($r)) {
676 $errors .= self::printUpdateError($sql3);
679 $r = DBA::e("DROP TABLE `" . $name . "`;");
680 if (!DBA::isResult($r)) {
681 $errors .= self::printUpdateError($sql3);
684 $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
685 if (!DBA::isResult($r)) {
686 $errors .= self::printUpdateError($sql3);
695 View::create(false, $action);
697 self::checkInitialValues();
699 if ($action && !$install) {
700 DI::config()->set('system', 'maintenance', 0);
701 DI::config()->set('system', 'maintenance_reason', '');
704 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
706 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
713 private static function tableStructure($table)
715 // This query doesn't seem to be executable as a prepared statement
716 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
718 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
719 ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
720 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
721 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
722 DBA::databaseName(), $table]);
724 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
725 ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
726 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
727 DBA::databaseName(), $table]);
729 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
730 ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
731 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
732 DBA::databaseName(), $table]);
738 if (DBA::isResult($foreign_keys)) {
739 foreach ($foreign_keys as $foreign_key) {
740 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
741 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
742 $foreigndata[$constraint] = $foreign_key;
746 if (DBA::isResult($indexes)) {
747 foreach ($indexes AS $index) {
748 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
749 $indexdata[$index["Key_name"]] = ["UNIQUE"];
752 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
753 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
756 $column = $index["Column_name"];
758 if ($index["Sub_part"] != "") {
759 $column .= "(" . $index["Sub_part"] . ")";
762 $indexdata[$index["Key_name"]][] = $column;
767 if (DBA::isResult($fields)) {
768 foreach ($fields AS $field) {
769 $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)'];
770 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
771 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
773 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
775 if ($field['IS_NULLABLE'] == 'NO') {
776 $fielddata[$field['COLUMN_NAME']]['not null'] = true;
779 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
780 $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
783 if (!empty($field['EXTRA'])) {
784 $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
787 if ($field['COLUMN_KEY'] == 'PRI') {
788 $fielddata[$field['COLUMN_NAME']]['primary'] = true;
791 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
792 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
796 return ["fields" => $fielddata, "indexes" => $indexdata,
797 "foreign_keys" => $foreigndata, "table_status" => $table_status];
800 private static function dropIndex($indexname)
802 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
806 private static function addTableField($fieldname, $parameters)
808 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
812 private static function modifyTableField($fieldname, $parameters)
814 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
818 private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
820 $foreign_table = array_keys($parameters['foreign'])[0];
821 $foreign_field = array_values($parameters['foreign'])[0];
823 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
826 private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
827 $foreign_table = array_keys($parameters['foreign'])[0];
828 $foreign_field = array_values($parameters['foreign'])[0];
830 $sql = "FOREIGN KEY (`" . $fieldname . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
832 if (!empty($parameters['foreign']['on update'])) {
833 $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
835 $sql .= " ON UPDATE RESTRICT";
838 if (!empty($parameters['foreign']['on delete'])) {
839 $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
841 $sql .= " ON DELETE CASCADE";
847 private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
849 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
852 private static function dropForeignKey(string $constraint)
854 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
858 * Constructs a GROUP BY clause from a UNIQUE index definition.
860 * @param array $fieldnames
863 private static function groupBy(array $fieldnames)
865 if ($fieldnames[0] != "UNIQUE") {
869 array_shift($fieldnames);
872 foreach ($fieldnames AS $fieldname) {
877 if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
878 $names .= "`" . DBA::escape($matches[1]) . "`";
880 $names .= "`" . DBA::escape($fieldname) . "`";
884 $sql = sprintf(" GROUP BY %s", $names);
889 * Renames columns or the primary key of a table
891 * @todo You cannot rename a primary key if "auto increment" is set
893 * @param string $table Table name
894 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
895 * Syntax for Primary Key: [ $col1, $col2, ...]
896 * @param int $type The type of renaming (Default is Column)
898 * @return boolean Was the renaming successful?
901 public static function rename($table, $columns, $type = self::RENAME_COLUMN)
903 if (empty($table) || empty($columns)) {
907 if (!is_array($columns)) {
911 $table = DBA::escape($table);
913 $sql = "ALTER TABLE `" . $table . "`";
915 case self::RENAME_COLUMN:
916 if (!self::existsColumn($table, array_keys($columns))) {
919 $sql .= implode(',', array_map(
920 function ($to, $from) {
921 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
927 case self::RENAME_PRIMARY_KEY:
928 if (!self::existsColumn($table, $columns)) {
931 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
939 $stmt = DBA::p($sql);
941 if (is_bool($stmt)) {
953 * Check if the columns of the table exists
955 * @param string $table Table name
956 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
958 * @return boolean Does the table exist?
961 public static function existsColumn($table, $columns = [])
967 if (is_null($columns) || empty($columns)) {
968 return self::existsTable($table);
971 $table = DBA::escape($table);
973 foreach ($columns AS $column) {
974 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
976 $stmt = DBA::p($sql);
978 if (is_bool($stmt)) {
981 $retval = (DBA::numRows($stmt) > 0);
995 * Check if a foreign key exists for the given table field
997 * @param string $table
998 * @param string $field
1001 public static function existsForeignKeyForField(string $table, string $field)
1003 return DBA::exists(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
1004 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
1005 DBA::databaseName(), $table, $field]);
1008 * Check if a table exists
1010 * @param string|array $table Table name
1012 * @return boolean Does the table exist?
1015 public static function existsTable($table)
1017 if (empty($table)) {
1021 if (is_array($table)) {
1022 $condition = ['table_schema' => key($table), 'table_name' => current($table)];
1024 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
1027 $result = DBA::exists(['information_schema' => 'tables'], $condition);
1033 * Returns the columns of a table
1035 * @param string $table Table name
1037 * @return array An array of the table columns
1040 public static function getColumns($table)
1042 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
1043 return DBA::toArray($stmtColumns);
1047 * Check if initial database values do exist - or create them
1049 public static function checkInitialValues()
1051 if (self::existsTable('verb') && !DBA::exists('verb', ['id' => 1])) {
1052 foreach (Item::ACTIVITIES as $index => $activity) {
1053 DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], true);
1057 if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) {
1058 DBA::insert('user', ['uid' => 0]);
1059 $lastid = DBA::lastInsertId();
1063 "page-flags" => User::PAGE_FLAGS_SOAPBOX,
1064 "account-type" => User::ACCOUNT_TYPE_RELAY,
1066 DBA::update('user', $user, ['uid' => $lastid]);
1070 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
1071 DBA::insert('contact', ['nurl' => '']);
1072 $lastid = DBA::lastInsertId();
1074 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
1078 /* if (self::existsTable('user') && DBA::exists('user', ['uid' => 0])) {
1079 $system = User::getSystemAccount();
1081 "username" => $system['name'],
1082 "nickname" => $system['nick'],
1083 "register_date" => $system['created'],
1084 "pubkey" => $system['pubkey'],
1085 "prvkey" => $system['prvkey'],
1086 "spubkey" => $system['spubkey'],
1087 "sprvkey" => $system['sprvkey'],
1089 "page-flags" => User::PAGE_FLAGS_SOAPBOX,
1090 "account-type" => User::ACCOUNT_TYPE_RELAY,
1093 DBA::update('user', $user, ['uid' => 0]);
1096 if (self::existsTable('permissionset')) {
1097 if (!DBA::exists('permissionset', ['id' => 0])) {
1098 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
1099 $lastid = DBA::lastInsertId();
1101 DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
1104 if (!self::existsForeignKeyForField('item', 'psid')) {
1105 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
1106 LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
1107 WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
1108 while ($set = DBA::fetch($sets)) {
1109 if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
1110 $owner = User::getOwnerDataById($set['uid']);
1112 $permission = '<' . $owner['id'] . '>';
1119 $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
1120 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
1121 DBA::insert('permissionset', $fields);
1127 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
1128 DBA::insert('tag', ['name' => '']);
1129 $lastid = DBA::lastInsertId();
1131 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
1135 if (!self::existsForeignKeyForField('tokens', 'client_id')) {
1136 $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
1137 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
1138 WHERE `clients`.`client_id` IS NULL");
1139 while ($token = DBA::fetch($tokens)) {
1140 DBA::delete('tokens', ['id' => $token['id']]);
1142 DBA::close($tokens);
1147 * Checks if a database update is currently running
1151 private static function isUpdating()
1155 $processes = DBA::select(['information_schema' => 'processlist'], ['info'],
1156 ['db' => DBA::databaseName(), 'command' => ['Query', 'Execute']]);
1158 while ($process = DBA::fetch($processes)) {
1159 $parts = explode(' ', $process['info']);
1160 if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
1165 DBA::close($processes);