3 * @copyright Copyright (C) 2010-2023, the Friendica project
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\Logger;
27 use Friendica\Model\Item;
28 use Friendica\Model\User;
29 use Friendica\Util\DateTimeFormat;
30 use Friendica\Util\Writer\DbaDefinitionSqlWriter;
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 * Set a database version to trigger update functions
47 * @param string $version
50 public static function setDatabaseVersion(string $version)
52 if (!is_numeric($version)) {
53 throw new \Asika\SimpleConsole\CommandArgsException('The version number must be numeric');
56 DI::keyValue()->set('build', $version);
57 echo DI::l10n()->t('The database version had been set to %s.', $version);
63 * @param boolean $execute
66 public static function dropTables(bool $execute)
68 $postupdate = DI::keyValue()->get('post_update_version') ?? PostUpdate::VERSION;
69 if ($postupdate < PostUpdate::VERSION) {
70 echo DI::l10n()->t('The post update is at version %d, it has to be at %d to safely drop the tables.', $postupdate, PostUpdate::VERSION);
74 $old_tables = ['fserver', 'gcign', 'gcontact', 'gcontact-relation', 'gfollower' ,'glink', 'item-delivery-data',
75 'item-activity', 'item-content', 'item_id', 'participation', 'poll', 'poll_result', 'queue', 'retriever_rule',
76 'deliverq', 'dsprphotoq', 'ffinder', 'sign', 'spam', 'term', 'user-item', 'thread', 'item', 'challenge',
77 'auth_codes', 'tokens', 'clients', 'profile_check', 'host', 'conversation', 'fcontact', 'config'];
79 $tables = DBA::selectToArray('INFORMATION_SCHEMA.TABLES', ['TABLE_NAME'],
80 ['TABLE_SCHEMA' => DBA::databaseName(), 'TABLE_TYPE' => 'BASE TABLE']);
83 echo DI::l10n()->t('No unused tables found.');
88 echo DI::l10n()->t('These tables are not used for friendica and will be deleted when you execute "dbstructure drop -e":') . "\n\n";
91 foreach ($old_tables as $table) {
92 if (in_array($table, array_column($tables, 'TABLE_NAME'))) {
94 $sql = 'DROP TABLE ' . DBA::quoteIdentifier($table) . ';';
97 $result = DBA::e($sql);
98 if (!DBA::isResult($result)) {
99 self::printUpdateError($sql);
109 * Converts all tables from MyISAM/InnoDB Antelope to InnoDB Barracuda
111 public static function convertToInnoDB()
113 $tables = DBA::selectToArray(
114 'information_schema.tables',
116 ['engine' => 'MyISAM', 'table_schema' => DBA::databaseName()]
119 $tables = array_merge($tables, DBA::selectToArray(
120 'information_schema.tables',
122 ['engine' => 'InnoDB', 'ROW_FORMAT' => ['COMPACT', 'REDUNDANT'], 'table_schema' => DBA::databaseName()]
125 if (!DBA::isResult($tables)) {
126 echo DI::l10n()->t('There are no tables on MyISAM or InnoDB with the Antelope file format.') . "\n";
130 foreach ($tables as $table) {
131 $sql = "ALTER TABLE " . DBA::quoteIdentifier($table['table_name']) . " ENGINE=InnoDB ROW_FORMAT=DYNAMIC;";
134 $result = DBA::e($sql);
135 if (!DBA::isResult($result)) {
136 self::printUpdateError($sql);
142 * Print out database error messages
144 * @param string $message Message to be added to the error message
146 * @return string Error message
148 private static function printUpdateError(string $message): string
150 echo DI::l10n()->t("\nError %d occurred during database update:\n%s\n",
151 DBA::errorNo(), DBA::errorMessage());
153 return DI::l10n()->t('Errors encountered performing database changes: ') . $message . '<br />';
157 * Perform a database structure dryrun (means: just simulating)
159 * @return string Empty string if the update is successful, error messages otherwise
162 public static function dryRun(): string
164 return self::update(true, false);
168 * Updates DB structure and returns eventual errors messages
170 * @param bool $enable_maintenance_mode Set the maintenance mode
171 * @param bool $verbose Display the SQL commands
173 * @return string Empty string if the update is successful, error messages otherwise
176 public static function performUpdate(bool $enable_maintenance_mode = true, bool $verbose = false): string
178 if ($enable_maintenance_mode) {
179 DI::config()->set('system', 'maintenance', true);
182 $status = self::update($verbose, true);
184 if ($enable_maintenance_mode) {
185 DI::config()->set('system', 'maintenance', false, false);
186 DI::config()->delete('system', 'maintenance_reason', false);
187 DI::config()->save();
194 * Updates DB structure from the installation and returns eventual errors messages
196 * @return string Empty string if the update is successful, error messages otherwise
199 public static function install(): string
201 return self::update(false, true, true);
205 * Updates DB structure and returns eventual errors messages
207 * @param bool $verbose
208 * @param bool $action Whether to actually apply the update
209 * @param bool $install Is this the initial update during the installation?
210 * @param array $tables An array of the database tables
211 * @param array $definition An array of the definition tables
212 * @return string Empty string if the update is successful, error messages otherwise
215 private static function update(bool $verbose, bool $action, bool $install = false, array $tables = null, array $definition = null): string
217 $in_maintenance_mode = DI::config()->get('system', 'maintenance');
219 if ($action && !$install && self::isUpdating()) {
220 return DI::l10n()->t('Another database update is currently running.');
223 if ($in_maintenance_mode) {
224 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
227 // ensure that all initial values exist. This test has to be done prior and after the structure check.
228 // Prior is needed if the specific tables already exists - after is needed when they had been created.
229 self::checkInitialValues();
233 Logger::info('updating structure');
235 // Get the current structure
238 if (is_null($tables)) {
239 $tables = DBA::toArray(DBA::p("SHOW TABLES"));
242 if (DBA::isResult($tables)) {
243 foreach ($tables as $table) {
244 $table = current($table);
246 Logger::info('updating structure', ['table' => $table]);
247 $database[$table] = self::tableStructure($table);
251 // Get the definition
252 if (is_null($definition)) {
253 // just for Update purpose, reload the DBA definition with addons to explicit get the whole definition
254 $definition = DI::dbaDefinition()->load(true)->getAll();
257 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
258 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
259 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
266 foreach ($definition as $name => $structure) {
267 $is_new_table = false;
269 if (!isset($database[$name])) {
270 $sql = DbaDefinitionSqlWriter::createTable($name, $structure, $verbose, $action);
276 if (!DBA::isResult($r)) {
277 $errors .= self::printUpdateError($name);
280 $is_new_table = true;
283 * Drop the index if it isn't present in the definition
284 * or the definition differ from current status
285 * and index name doesn't start with "local_"
287 foreach ($database[$name]["indexes"] as $indexName => $fieldNames) {
288 $current_index_definition = implode(",", $fieldNames);
289 if (isset($structure["indexes"][$indexName])) {
290 $new_index_definition = implode(",", $structure["indexes"][$indexName]);
292 $new_index_definition = "__NOT_SET__";
294 if ($current_index_definition != $new_index_definition && substr($indexName, 0, 6) != 'local_') {
295 $sql2 = DbaDefinitionSqlWriter::dropIndex($indexName);
297 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
299 $sql3 .= ", " . $sql2;
303 // Compare the field structure field by field
304 foreach ($structure["fields"] as $fieldName => $parameters) {
305 if (!isset($database[$name]["fields"][$fieldName])) {
306 $sql2 = DbaDefinitionSqlWriter::addTableField($fieldName, $parameters);
308 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
310 $sql3 .= ", " . $sql2;
313 // Compare the field definition
314 $field_definition = $database[$name]["fields"][$fieldName];
316 // Remove the relation data that is used for the referential integrity
317 unset($parameters['relation']);
318 unset($parameters['foreign']);
320 // We change the collation after the indexes had been changed.
321 // This is done to avoid index length problems.
322 // So here we always ensure that there is no need to change it.
323 unset($parameters['Collation']);
324 unset($field_definition['Collation']);
326 // Only update the comment when it is defined
327 if (!isset($parameters['comment'])) {
328 $parameters['comment'] = "";
331 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
332 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
333 if ($current_field_definition != $new_field_definition) {
334 $sql2 = DbaDefinitionSqlWriter::modifyTableField($fieldName, $parameters);
336 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
338 $sql3 .= ", " . $sql2;
346 * Create the index if the index don't exists in database
347 * or the definition differ from the current status.
348 * Don't create keys if table is new
350 if (!$is_new_table) {
351 foreach ($structure["indexes"] as $indexName => $fieldNames) {
352 if (isset($database[$name]["indexes"][$indexName])) {
353 $current_index_definition = implode(",", $database[$name]["indexes"][$indexName]);
355 $current_index_definition = "__NOT_SET__";
357 $new_index_definition = implode(",", $fieldNames);
358 if ($current_index_definition != $new_index_definition) {
359 $sql2 = DbaDefinitionSqlWriter::createIndex($indexName, $fieldNames);
363 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
365 $sql3 .= ", " . $sql2;
371 $existing_foreign_keys = $database[$name]['foreign_keys'];
374 // Compare the field structure field by field
375 foreach ($structure["fields"] as $fieldName => $parameters) {
376 if (empty($parameters['foreign'])) {
380 $constraint = self::getConstraintName($name, $fieldName, $parameters);
382 unset($existing_foreign_keys[$constraint]);
384 if (empty($database[$name]['foreign_keys'][$constraint])) {
385 $sql2 = DbaDefinitionSqlWriter::addForeignKey($fieldName, $parameters);
388 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
390 $sql3 .= ", " . $sql2;
395 foreach ($existing_foreign_keys as $param) {
396 $sql2 = DbaDefinitionSqlWriter::dropForeignKey($param['CONSTRAINT_NAME']);
399 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
401 $sql3 .= ", " . $sql2;
405 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
406 $structurecomment = $structure["comment"] ?? '';
407 if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
408 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
411 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
413 $sql3 .= ", " . $sql2;
418 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
419 if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
420 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
423 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
425 $sql3 .= ", " . $sql2;
430 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
431 if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
432 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
435 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
437 $sql3 .= ", " . $sql2;
446 // Now have a look at the field collations
447 // Compare the field structure field by field
448 foreach ($structure["fields"] as $fieldName => $parameters) {
449 // Compare the field definition
450 $field_definition = ($database[$name]["fields"][$fieldName] ?? '') ?: ['Collation' => ''];
452 // Define the default collation if not given
453 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
454 $parameters['Collation'] = 'utf8mb4_general_ci';
456 $parameters['Collation'] = null;
459 if ($field_definition['Collation'] != $parameters['Collation']) {
460 $sql2 = DbaDefinitionSqlWriter::modifyTableField($fieldName, $parameters);
461 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
462 $sql3 .= "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
464 $sql3 .= ", " . $sql2;
471 if (substr($sql3, -2, 2) != "; ") {
480 if ($in_maintenance_mode) {
481 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
485 if (!DBA::isResult($r)) {
486 $errors .= self::printUpdateError($sql3);
492 View::create(false, $action);
494 self::checkInitialValues();
496 if ($action && !$install) {
498 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
500 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
508 * Returns an array with table structure information
510 * @param string $table Name of table
511 * @return array Table structure information
513 private static function tableStructure(string $table): array
515 // This query doesn't seem to be executable as a prepared statement
516 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
518 $fields = DBA::selectToArray('INFORMATION_SCHEMA.COLUMNS',
519 ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
520 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
521 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
522 DBA::databaseName(), $table]);
524 $foreign_keys = DBA::selectToArray('INFORMATION_SCHEMA.KEY_COLUMN_USAGE',
525 ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
526 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
527 DBA::databaseName(), $table]);
529 $table_status = DBA::selectFirst('INFORMATION_SCHEMA.TABLES',
530 ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
531 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
532 DBA::databaseName(), $table]);
538 if (DBA::isResult($foreign_keys)) {
539 foreach ($foreign_keys as $foreign_key) {
540 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
541 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
542 $foreigndata[$constraint] = $foreign_key;
546 if (DBA::isResult($indexes)) {
547 foreach ($indexes as $index) {
548 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
549 $indexdata[$index["Key_name"]] = ["UNIQUE"];
552 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
553 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
556 $column = $index["Column_name"];
558 if ($index["Sub_part"] != "") {
559 $column .= "(" . $index["Sub_part"] . ")";
562 $indexdata[$index["Key_name"]][] = $column;
567 if (DBA::isResult($fields)) {
568 foreach ($fields as $field) {
569 $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)'];
570 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
571 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
573 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
575 if ($field['IS_NULLABLE'] == 'NO') {
576 $fielddata[$field['COLUMN_NAME']]['not null'] = true;
579 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
580 $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
583 if (!empty($field['EXTRA'])) {
584 $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
587 if ($field['COLUMN_KEY'] == 'PRI') {
588 $fielddata[$field['COLUMN_NAME']]['primary'] = true;
591 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
592 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
597 'fields' => $fielddata,
598 'indexes' => $indexdata,
599 'foreign_keys' => $foreigndata,
600 'table_status' => $table_status
604 private static function getConstraintName(string $tableName, string $fieldName, array $parameters): string
606 $foreign_table = array_keys($parameters['foreign'])[0];
607 $foreign_field = array_values($parameters['foreign'])[0];
609 return $tableName . '-' . $fieldName. '-' . $foreign_table. '-' . $foreign_field;
613 * Renames columns or the primary key of a table
615 * @todo You cannot rename a primary key if "auto increment" is set
617 * @param string $table Table name
618 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
619 * Syntax for Primary Key: [ $col1, $col2, ...]
620 * @param int $type The type of renaming (Default is Column)
622 * @return boolean Was the renaming successful?
625 public static function rename(string $table, array $columns, int $type = self::RENAME_COLUMN): bool
627 if (empty($table) || empty($columns)) {
631 if (!is_array($columns)) {
635 $table = DBA::escape($table);
637 $sql = "ALTER TABLE `" . $table . "`";
639 case self::RENAME_COLUMN:
640 if (!self::existsColumn($table, array_keys($columns))) {
643 $sql .= implode(',', array_map(
644 function ($to, $from) {
645 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
651 case self::RENAME_PRIMARY_KEY:
652 if (!self::existsColumn($table, $columns)) {
655 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
663 $stmt = DBA::p($sql);
665 if (is_bool($stmt)) {
677 * Check if the columns of the table exists
679 * @param string $table Table name
680 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
682 * @return boolean Does the table exist?
685 public static function existsColumn(string $table, array $columns = []): bool
691 if (is_null($columns) || empty($columns)) {
692 return self::existsTable($table);
695 $table = DBA::escape($table);
697 foreach ($columns as $column) {
698 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
700 $stmt = DBA::p($sql);
702 if (is_bool($stmt)) {
705 $retval = (DBA::numRows($stmt) > 0);
719 * Check if a foreign key exists for the given table field
721 * @param string $table Table name
722 * @param string $field Field name
723 * @return boolean Wether a foreign key exists
725 public static function existsForeignKeyForField(string $table, string $field): bool
727 return DBA::exists('INFORMATION_SCHEMA.KEY_COLUMN_USAGE',
728 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
729 DBA::databaseName(), $table, $field]);
733 * Check if a table exists
735 * @param string $table Single table name (please loop yourself)
736 * @return boolean Does the table exist?
739 public static function existsTable(string $table): bool
745 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
747 return DBA::exists('information_schema.tables', $condition);
751 * Returns the columns of a table
753 * @param string $table Table name
755 * @return array An array of the table columns
758 public static function getColumns(string $table): array
760 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
761 return DBA::toArray($stmtColumns);
765 * Check if initial database values do exist - or create them
767 * @param bool $verbose Whether to output messages
770 public static function checkInitialValues(bool $verbose = false)
772 if (self::existsTable('verb')) {
773 if (!DBA::exists('verb', ['id' => 1])) {
774 foreach (Item::ACTIVITIES as $index => $activity) {
775 DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], Database::INSERT_IGNORE);
778 echo "verb: activities added\n";
780 } elseif ($verbose) {
781 echo "verb: activities already added\n";
784 if (!DBA::exists('verb', ['id' => 0])) {
785 DBA::insert('verb', ['name' => '']);
786 $lastid = DBA::lastInsertId();
788 DBA::update('verb', ['id' => 0], ['id' => $lastid]);
790 echo "Zero verb added\n";
793 } elseif ($verbose) {
794 echo "Zero verb already added\n";
796 } elseif ($verbose) {
797 echo "verb: Table not found\n";
800 if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) {
803 'page-flags' => User::PAGE_FLAGS_SOAPBOX,
804 'account-type' => User::ACCOUNT_TYPE_RELAY,
806 DBA::insert('user', $user);
807 $lastid = DBA::lastInsertId();
809 DBA::update('user', ['uid' => 0], ['uid' => $lastid]);
811 echo "Zero user added\n";
814 } elseif (self::existsTable('user') && $verbose) {
815 echo "Zero user already added\n";
816 } elseif ($verbose) {
817 echo "user: Table not found\n";
820 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
821 DBA::insert('contact', ['nurl' => '']);
822 $lastid = DBA::lastInsertId();
824 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
826 echo "Zero contact added\n";
829 } elseif (self::existsTable('contact') && $verbose) {
830 echo "Zero contact already added\n";
831 } elseif ($verbose) {
832 echo "contact: Table not found\n";
835 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
836 DBA::insert('tag', ['name' => '']);
837 $lastid = DBA::lastInsertId();
839 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
841 echo "Zero tag added\n";
844 } elseif (self::existsTable('tag') && $verbose) {
845 echo "Zero tag already added\n";
846 } elseif ($verbose) {
847 echo "tag: Table not found\n";
850 if (self::existsTable('permissionset')) {
851 if (!DBA::exists('permissionset', ['id' => 0])) {
852 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
853 $lastid = DBA::lastInsertId();
855 DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
857 echo "Zero permissionset added\n";
860 } elseif ($verbose) {
861 echo "Zero permissionset already added\n";
863 if (self::existsTable('item') && !self::existsForeignKeyForField('item', 'psid')) {
864 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
865 LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
866 WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
867 while ($set = DBA::fetch($sets)) {
868 if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
869 $owner = User::getOwnerDataById($set['uid']);
871 $permission = '<' . $owner['id'] . '>';
878 $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
879 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
880 DBA::insert('permissionset', $fields);
884 } elseif ($verbose) {
885 echo "permissionset: Table not found\n";
888 if (self::existsTable('tokens') && self::existsTable('clients') && !self::existsForeignKeyForField('tokens', 'client_id')) {
889 $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
890 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
891 WHERE `clients`.`client_id` IS NULL");
892 while ($token = DBA::fetch($tokens)) {
893 DBA::delete('tokens', ['id' => $token['id']]);
900 * Checks if a database update is currently running
904 private static function isUpdating(): bool
908 $processes = DBA::select('information_schema.processlist', ['info'], [
909 'db' => DBA::databaseName(),
910 'command' => ['Query', 'Execute']
913 while ($process = DBA::fetch($processes)) {
914 $parts = explode(' ', $process['info']);
915 if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
920 DBA::close($processes);