]> git.mxchange.org Git - friendica.git/blob - src/Database/DBStructure.php
Coding standards
[friendica.git] / src / Database / DBStructure.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Database;
23
24 use Exception;
25 use Friendica\Core\Hook;
26 use Friendica\Core\Logger;
27 use Friendica\DI;
28 use Friendica\Model\Item;
29 use Friendica\Model\User;
30 use Friendica\Util\DateTimeFormat;
31
32 /**
33  * This class contains functions that doesn't need to know if pdo, mysqli or whatever is used.
34  */
35 class DBStructure
36 {
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
40
41         const RENAME_COLUMN      = 0;
42         const RENAME_PRIMARY_KEY = 1;
43
44         /**
45          * Database structure definition loaded from config/dbstructure.config.php
46          *
47          * @var array
48          */
49         private static $definition = [];
50
51         /**
52          * Set a database version to trigger update functions
53          *
54          * @param string $version
55          * @return void
56          */
57         public static function setDatabaseVersion(string $version)
58         {
59                 if (!is_numeric($version)) {
60                         throw new \Asika\SimpleConsole\CommandArgsException('The version number must be numeric');
61                 }
62
63                 DI::config()->set('system', 'build', $version);
64                 echo DI::l10n()->t('The database version had been set to %s.', $version);
65         }
66
67         /**
68          * Drop unused tables
69          *
70          * @param boolean $execute
71          * @return void
72          */
73         public static function dropTables(bool $execute)
74         {
75                 $postupdate = DI::config()->get("system", "post_update_version", PostUpdate::VERSION);
76                 if ($postupdate < PostUpdate::VERSION) {
77                         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);
78                         return;
79                 }
80
81                 $old_tables = ['fserver', 'gcign', 'gcontact', 'gcontact-relation', 'gfollower' ,'glink', 'item-delivery-data',
82                         'item-activity', 'item-content', 'item_id', 'participation', 'poll', 'poll_result', 'queue', 'retriever_rule',
83                         'deliverq', 'dsprphotoq', 'ffinder', 'sign', 'spam', 'term', 'user-item', 'thread', 'item'];
84
85                 $tables = DBA::selectToArray(['INFORMATION_SCHEMA' => 'TABLES'], ['TABLE_NAME'],
86                         ['TABLE_SCHEMA' => DBA::databaseName(), 'TABLE_TYPE' => 'BASE TABLE']);
87
88                 if (empty($tables)) {
89                         echo DI::l10n()->t('No unused tables found.');
90                         return;
91                 }
92
93                 if (!$execute) {
94                         echo DI::l10n()->t('These tables are not used for friendica and will be deleted when you execute "dbstructure drop -e":') . "\n\n";
95                 }
96
97                 foreach ($tables as $table) {
98                         if (in_array($table['TABLE_NAME'], $old_tables)) {
99                                 if ($execute) {
100                                         $sql = 'DROP TABLE ' . DBA::quoteIdentifier($table['TABLE_NAME']) . ';';
101                                         echo $sql . "\n";
102
103                                         $result = DBA::e($sql);
104                                         if (!DBA::isResult($result)) {
105                                                 self::printUpdateError($sql);
106                                         }
107                                 } else {
108                                         echo $table['TABLE_NAME'] . "\n";
109                                 }
110                         }
111                 }
112         }
113
114         /**
115          * Converts all tables from MyISAM/InnoDB Antelope to InnoDB Barracuda
116          */
117         public static function convertToInnoDB()
118         {
119                 $tables = DBA::selectToArray(
120                         ['information_schema' => 'tables'],
121                         ['table_name'],
122                         ['engine' => 'MyISAM', 'table_schema' => DBA::databaseName()]
123                 );
124
125                 $tables = array_merge($tables, DBA::selectToArray(
126                         ['information_schema' => 'tables'],
127                         ['table_name'],
128                         ['engine' => 'InnoDB', 'ROW_FORMAT' => ['COMPACT', 'REDUNDANT'], 'table_schema' => DBA::databaseName()]
129                 ));
130
131                 if (!DBA::isResult($tables)) {
132                         echo DI::l10n()->t('There are no tables on MyISAM or InnoDB with the Antelope file format.') . "\n";
133                         return;
134                 }
135
136                 foreach ($tables AS $table) {
137                         $sql = "ALTER TABLE " . DBA::quoteIdentifier($table['table_name']) . " ENGINE=InnoDB ROW_FORMAT=DYNAMIC;";
138                         echo $sql . "\n";
139
140                         $result = DBA::e($sql);
141                         if (!DBA::isResult($result)) {
142                                 self::printUpdateError($sql);
143                         }
144                 }
145         }
146
147         /**
148          * Print out database error messages
149          *
150          * @param string $message Message to be added to the error message
151          *
152          * @return string Error message
153          */
154         private static function printUpdateError($message)
155         {
156                 echo DI::l10n()->t("\nError %d occurred during database update:\n%s\n",
157                         DBA::errorNo(), DBA::errorMessage());
158
159                 return DI::l10n()->t('Errors encountered performing database changes: ') . $message . EOL;
160         }
161
162         public static function printStructure($basePath)
163         {
164                 $database = self::definition($basePath, false);
165
166                 echo "-- ------------------------------------------\n";
167                 echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n";
168                 echo "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
169                 echo "-- ------------------------------------------\n\n\n";
170                 foreach ($database AS $name => $structure) {
171                         echo "--\n";
172                         echo "-- TABLE $name\n";
173                         echo "--\n";
174                         self::createTable($name, $structure, true, false);
175
176                         echo "\n";
177                 }
178
179                 View::printStructure($basePath);
180         }
181
182         /**
183          * Loads the database structure definition from the static/dbstructure.config.php file.
184          * On first pass, defines DB_UPDATE_VERSION constant.
185          *
186          * @see static/dbstructure.config.php
187          * @param boolean $with_addons_structure Whether to tack on addons additional tables
188          * @param string  $basePath              The base path of this application
189          * @return array
190          * @throws Exception
191          */
192         public static function definition($basePath, $with_addons_structure = true)
193         {
194                 if (!self::$definition) {
195                         if (empty($basePath)) {
196                                 $basePath = DI::app()->getBasePath();
197                         }
198
199                         $filename = $basePath . '/static/dbstructure.config.php';
200
201                         if (!is_readable($filename)) {
202                                 throw new Exception('Missing database structure config file static/dbstructure.config.php');
203                         }
204
205                         $definition = require $filename;
206
207                         if (!$definition) {
208                                 throw new Exception('Corrupted database structure config file static/dbstructure.config.php');
209                         }
210
211                         self::$definition = $definition;
212                 } else {
213                         $definition = self::$definition;
214                 }
215
216                 if ($with_addons_structure) {
217                         Hook::callAll('dbstructure_definition', $definition);
218                 }
219
220                 return $definition;
221         }
222
223         /**
224          * Get field data for the given table
225          *
226          * @param string $table
227          * @param array $data data fields
228          * @return array fields for the given
229          */
230         public static function getFieldsForTable(string $table, array $data = [])
231         {
232                 $definition = DBStructure::definition('', false);
233                 if (empty($definition[$table])) {
234                         return [];
235                 }
236
237                 $fieldnames = array_keys($definition[$table]['fields']);
238
239                 $fields = [];
240
241                 // Assign all field that are present in the table
242                 foreach ($fieldnames as $field) {
243                         if (isset($data[$field])) {
244                                 $fields[$field] = $data[$field];
245                         }
246                 }
247
248                 return $fields;
249         }
250
251         private static function createTable($name, $structure, $verbose, $action)
252         {
253                 $r = true;
254
255                 $engine = "";
256                 $comment = "";
257                 $sql_rows = [];
258                 $primary_keys = [];
259                 $foreign_keys = [];
260
261                 foreach ($structure["fields"] AS $fieldname => $field) {
262                         $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
263                         if (!empty($field['primary'])) {
264                                 $primary_keys[] = $fieldname;
265                         }
266                         if (!empty($field['foreign'])) {
267                                 $foreign_keys[$fieldname] = $field;
268                         }
269                 }
270
271                 if (!empty($structure["indexes"])) {
272                         foreach ($structure["indexes"] AS $indexname => $fieldnames) {
273                                 $sql_index = self::createIndex($indexname, $fieldnames, "");
274                                 if (!is_null($sql_index)) {
275                                         $sql_rows[] = $sql_index;
276                                 }
277                         }
278                 }
279
280                 foreach ($foreign_keys AS $fieldname => $parameters) {
281                         $sql_rows[] = self::foreignCommand($name, $fieldname, $parameters);
282                 }
283
284                 if (isset($structure["engine"])) {
285                         $engine = " ENGINE=" . $structure["engine"];
286                 }
287
288                 if (isset($structure["comment"])) {
289                         $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
290                 }
291
292                 $sql = implode(",\n\t", $sql_rows);
293
294                 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
295                         "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
296                 if ($verbose) {
297                         echo $sql . ";\n";
298                 }
299
300                 if ($action) {
301                         $r = DBA::e($sql);
302                 }
303
304                 return $r;
305         }
306
307         private static function FieldCommand($parameters, $create = true)
308         {
309                 $fieldstruct = $parameters["type"];
310
311                 if (isset($parameters["Collation"])) {
312                         $fieldstruct .= " COLLATE " . $parameters["Collation"];
313                 }
314
315                 if (isset($parameters["not null"])) {
316                         $fieldstruct .= " NOT NULL";
317                 }
318
319                 if (isset($parameters["default"])) {
320                         if (strpos(strtolower($parameters["type"]), "int") !== false) {
321                                 $fieldstruct .= " DEFAULT " . $parameters["default"];
322                         } else {
323                                 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
324                         }
325                 }
326                 if (isset($parameters["extra"])) {
327                         $fieldstruct .= " " . $parameters["extra"];
328                 }
329
330                 if (isset($parameters["comment"])) {
331                         $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
332                 }
333
334                 /*if (($parameters["primary"] != "") && $create)
335                         $fieldstruct .= " PRIMARY KEY";*/
336
337                 return ($fieldstruct);
338         }
339
340         private static function createIndex($indexname, $fieldnames, $method = "ADD")
341         {
342                 $method = strtoupper(trim($method));
343                 if ($method != "" && $method != "ADD") {
344                         throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
345                 }
346
347                 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
348                         $index_type = array_shift($fieldnames);
349                         $method .= " " . $index_type;
350                 }
351
352                 $names = "";
353                 foreach ($fieldnames AS $fieldname) {
354                         if ($names != "") {
355                                 $names .= ",";
356                         }
357
358                         if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
359                                 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
360                         } else {
361                                 $names .= "`" . DBA::escape($fieldname) . "`";
362                         }
363                 }
364
365                 if ($indexname == "PRIMARY") {
366                         return sprintf("%s PRIMARY KEY(%s)", $method, $names);
367                 }
368
369
370                 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
371                 return ($sql);
372         }
373
374         /**
375          * Perform a database structure dryrun (means: just simulating)
376          *
377          * @throws Exception
378          */
379         public static function dryRun()
380         {
381                 self::update(DI::app()->getBasePath(), true, false);
382         }
383
384         /**
385          * Updates DB structure and returns eventual errors messages
386          *
387          * @param bool $enable_maintenance_mode Set the maintenance mode
388          * @param bool $verbose                 Display the SQL commands
389          *
390          * @return string Empty string if the update is successful, error messages otherwise
391          * @throws Exception
392          */
393         public static function performUpdate(bool $enable_maintenance_mode = true, bool $verbose = false)
394         {
395                 if ($enable_maintenance_mode) {
396                         DI::config()->set('system', 'maintenance', 1);
397                 }
398
399                 $status = self::update(DI::app()->getBasePath(), $verbose, true);
400
401                 if ($enable_maintenance_mode) {
402                         DI::config()->set('system', 'maintenance', 0);
403                         DI::config()->set('system', 'maintenance_reason', '');
404                 }
405
406                 return $status;
407         }
408
409         /**
410          * Updates DB structure from the installation and returns eventual errors messages
411          *
412          * @param string $basePath   The base path of this application
413          *
414          * @return string Empty string if the update is successful, error messages otherwise
415          * @throws Exception
416          */
417         public static function install(string $basePath)
418         {
419                 return self::update($basePath, false, true, true);
420         }
421
422         /**
423          * Updates DB structure and returns eventual errors messages
424          *
425          * @param string $basePath   The base path of this application
426          * @param bool   $verbose
427          * @param bool   $action     Whether to actually apply the update
428          * @param bool   $install    Is this the initial update during the installation?
429          * @param array  $tables     An array of the database tables
430          * @param array  $definition An array of the definition tables
431          * @return string Empty string if the update is successful, error messages otherwise
432          * @throws Exception
433          */
434         private static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
435         {
436                 $in_maintenance_mode = DI::config()->get('system', 'maintenance');
437
438                 if ($action && !$install && self::isUpdating()) {
439                         return DI::l10n()->t('Another database update is currently running.');
440                 }
441
442                 if ($in_maintenance_mode) {
443                         DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
444                 }
445
446                 // ensure that all initial values exist. This test has to be done prior and after the structure check.
447                 // Prior is needed if the specific tables already exists - after is needed when they had been created.
448                 self::checkInitialValues();
449
450                 $errors = '';
451
452                 Logger::info('updating structure');
453
454                 // Get the current structure
455                 $database = [];
456
457                 if (is_null($tables)) {
458                         $tables = DBA::toArray(DBA::p("SHOW TABLES"));
459                 }
460
461                 if (DBA::isResult($tables)) {
462                         foreach ($tables AS $table) {
463                                 $table = current($table);
464
465                                 Logger::info('updating structure', ['table' => $table]);
466                                 $database[$table] = self::tableStructure($table);
467                         }
468                 }
469
470                 // Get the definition
471                 if (is_null($definition)) {
472                         $definition = self::definition($basePath);
473                 }
474
475                 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
476                 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
477                         !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
478                         $ignore = '';
479                 } else {
480                         $ignore = ' IGNORE';
481                 }
482
483                 // Compare it
484                 foreach ($definition AS $name => $structure) {
485                         $is_new_table = false;
486                         $group_by = "";
487                         $sql3 = "";
488                         $is_unique = false;
489                         $temp_name = $name;
490                         if (!isset($database[$name])) {
491                                 $r = self::createTable($name, $structure, $verbose, $action);
492                                 if (!DBA::isResult($r)) {
493                                         $errors .= self::printUpdateError($name);
494                                 }
495                                 $is_new_table = true;
496                         } else {
497                                 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
498                                         if (isset($database[$name]["indexes"][$indexname])) {
499                                                 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
500                                         } else {
501                                                 $current_index_definition = "__NOT_SET__";
502                                         }
503                                         $new_index_definition = implode(",", $fieldnames);
504                                         if ($current_index_definition != $new_index_definition) {
505                                                 if ($fieldnames[0] == "UNIQUE") {
506                                                         $is_unique = true;
507                                                         if ($ignore == "") {
508                                                                 $temp_name = "temp-" . $name;
509                                                         }
510                                                 }
511                                         }
512                                 }
513
514                                 /*
515                                  * Drop the index if it isn't present in the definition
516                                  * or the definition differ from current status
517                                  * and index name doesn't start with "local_"
518                                  */
519                                 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
520                                         $current_index_definition = implode(",", $fieldnames);
521                                         if (isset($structure["indexes"][$indexname])) {
522                                                 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
523                                         } else {
524                                                 $new_index_definition = "__NOT_SET__";
525                                         }
526                                         if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
527                                                 $sql2 = self::dropIndex($indexname);
528                                                 if ($sql3 == "") {
529                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
530                                                 } else {
531                                                         $sql3 .= ", " . $sql2;
532                                                 }
533                                         }
534                                 }
535                                 // Compare the field structure field by field
536                                 foreach ($structure["fields"] AS $fieldname => $parameters) {
537                                         if (!isset($database[$name]["fields"][$fieldname])) {
538                                                 $sql2 = self::addTableField($fieldname, $parameters);
539                                                 if ($sql3 == "") {
540                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
541                                                 } else {
542                                                         $sql3 .= ", " . $sql2;
543                                                 }
544                                         } else {
545                                                 // Compare the field definition
546                                                 $field_definition = $database[$name]["fields"][$fieldname];
547
548                                                 // Remove the relation data that is used for the referential integrity
549                                                 unset($parameters['relation']);
550                                                 unset($parameters['foreign']);
551
552                                                 // We change the collation after the indexes had been changed.
553                                                 // This is done to avoid index length problems.
554                                                 // So here we always ensure that there is no need to change it.
555                                                 unset($parameters['Collation']);
556                                                 unset($field_definition['Collation']);
557
558                                                 // Only update the comment when it is defined
559                                                 if (!isset($parameters['comment'])) {
560                                                         $parameters['comment'] = "";
561                                                 }
562
563                                                 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
564                                                 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
565                                                 if ($current_field_definition != $new_field_definition) {
566                                                         $sql2 = self::modifyTableField($fieldname, $parameters);
567                                                         if ($sql3 == "") {
568                                                                 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
569                                                         } else {
570                                                                 $sql3 .= ", " . $sql2;
571                                                         }
572                                                 }
573                                         }
574                                 }
575                         }
576
577                         /*
578                          * Create the index if the index don't exists in database
579                          * or the definition differ from the current status.
580                          * Don't create keys if table is new
581                          */
582                         if (!$is_new_table) {
583                                 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
584                                         if (isset($database[$name]["indexes"][$indexname])) {
585                                                 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
586                                         } else {
587                                                 $current_index_definition = "__NOT_SET__";
588                                         }
589                                         $new_index_definition = implode(",", $fieldnames);
590                                         if ($current_index_definition != $new_index_definition) {
591                                                 $sql2 = self::createIndex($indexname, $fieldnames);
592
593                                                 // Fetch the "group by" fields for unique indexes
594                                                 $group_by = self::groupBy($fieldnames);
595                                                 if ($sql2 != "") {
596                                                         if ($sql3 == "") {
597                                                                 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
598                                                         } else {
599                                                                 $sql3 .= ", " . $sql2;
600                                                         }
601                                                 }
602                                         }
603                                 }
604
605                                 $existing_foreign_keys = $database[$name]['foreign_keys'];
606
607                                 // Foreign keys
608                                 // Compare the field structure field by field
609                                 foreach ($structure["fields"] AS $fieldname => $parameters) {
610                                         if (empty($parameters['foreign'])) {
611                                                 continue;
612                                         }
613
614                                         $constraint = self::getConstraintName($name, $fieldname, $parameters);
615
616                                         unset($existing_foreign_keys[$constraint]);
617
618                                         if (empty($database[$name]['foreign_keys'][$constraint])) {
619                                                 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
620
621                                                 if ($sql3 == "") {
622                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
623                                                 } else {
624                                                         $sql3 .= ", " . $sql2;
625                                                 }
626                                         }
627                                 }
628
629                                 foreach ($existing_foreign_keys as $param) {
630                                         $sql2 = self::dropForeignKey($param['CONSTRAINT_NAME']);
631
632                                         if ($sql3 == "") {
633                                                 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
634                                         } else {
635                                                 $sql3 .= ", " . $sql2;
636                                         }
637                                 }
638
639                                 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
640                                         $structurecomment = $structure["comment"] ?? '';
641                                         if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
642                                                 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
643
644                                                 if ($sql3 == "") {
645                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
646                                                 } else {
647                                                         $sql3 .= ", " . $sql2;
648                                                 }
649                                         }
650                                 }
651
652                                 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
653                                         if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
654                                                 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
655
656                                                 if ($sql3 == "") {
657                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
658                                                 } else {
659                                                         $sql3 .= ", " . $sql2;
660                                                 }
661                                         }
662                                 }
663
664                                 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
665                                         if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
666                                                 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
667
668                                                 if ($sql3 == "") {
669                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
670                                                 } else {
671                                                         $sql3 .= ", " . $sql2;
672                                                 }
673                                         }
674                                 }
675
676                                 if ($sql3 != "") {
677                                         $sql3 .= "; ";
678                                 }
679
680                                 // Now have a look at the field collations
681                                 // Compare the field structure field by field
682                                 foreach ($structure["fields"] AS $fieldname => $parameters) {
683                                         // Compare the field definition
684                                         $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
685
686                                         // Define the default collation if not given
687                                         if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
688                                                 $parameters['Collation'] = 'utf8mb4_general_ci';
689                                         } else {
690                                                 $parameters['Collation'] = null;
691                                         }
692
693                                         if ($field_definition['Collation'] != $parameters['Collation']) {
694                                                 $sql2 = self::modifyTableField($fieldname, $parameters);
695                                                 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
696                                                         $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
697                                                 } else {
698                                                         $sql3 .= ", " . $sql2;
699                                                 }
700                                         }
701                                 }
702                         }
703
704                         if ($sql3 != "") {
705                                 if (substr($sql3, -2, 2) != "; ") {
706                                         $sql3 .= ";";
707                                 }
708
709                                 $field_list = '';
710                                 if ($is_unique && $ignore == '') {
711                                         foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
712                                                 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
713                                         }
714                                         $field_list = rtrim($field_list, ',');
715                                 }
716
717                                 if ($verbose) {
718                                         // Ensure index conversion to unique removes duplicates
719                                         if ($is_unique && ($temp_name != $name)) {
720                                                 if ($ignore != "") {
721                                                         echo "SET session old_alter_table=1;\n";
722                                                 } else {
723                                                         echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
724                                                         echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
725                                                 }
726                                         }
727
728                                         echo $sql3 . "\n";
729
730                                         if ($is_unique && ($temp_name != $name)) {
731                                                 if ($ignore != "") {
732                                                         echo "SET session old_alter_table=0;\n";
733                                                 } else {
734                                                         echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
735                                                         echo "DROP TABLE `" . $name . "`;\n";
736                                                         echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
737                                                 }
738                                         }
739                                 }
740
741                                 if ($action) {
742                                         if ($in_maintenance_mode) {
743                                                 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
744                                         }
745
746                                         // Ensure index conversion to unique removes duplicates
747                                         if ($is_unique && ($temp_name != $name)) {
748                                                 if ($ignore != "") {
749                                                         DBA::e("SET session old_alter_table=1;");
750                                                 } else {
751                                                         $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
752                                                         if (!DBA::isResult($r)) {
753                                                                 $errors .= self::printUpdateError($sql3);
754                                                                 return $errors;
755                                                         }
756
757                                                         $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
758                                                         if (!DBA::isResult($r)) {
759                                                                 $errors .= self::printUpdateError($sql3);
760                                                                 return $errors;
761                                                         }
762                                                 }
763                                         }
764
765                                         $r = DBA::e($sql3);
766                                         if (!DBA::isResult($r)) {
767                                                 $errors .= self::printUpdateError($sql3);
768                                         }
769                                         if ($is_unique && ($temp_name != $name)) {
770                                                 if ($ignore != "") {
771                                                         DBA::e("SET session old_alter_table=0;");
772                                                 } else {
773                                                         $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
774                                                         if (!DBA::isResult($r)) {
775                                                                 $errors .= self::printUpdateError($sql3);
776                                                                 return $errors;
777                                                         }
778                                                         $r = DBA::e("DROP TABLE `" . $name . "`;");
779                                                         if (!DBA::isResult($r)) {
780                                                                 $errors .= self::printUpdateError($sql3);
781                                                                 return $errors;
782                                                         }
783                                                         $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
784                                                         if (!DBA::isResult($r)) {
785                                                                 $errors .= self::printUpdateError($sql3);
786                                                                 return $errors;
787                                                         }
788                                                 }
789                                         }
790                                 }
791                         }
792                 }
793
794                 View::create(false, $action);
795
796                 self::checkInitialValues();
797
798                 if ($action && !$install) {
799                         if ($errors) {
800                                 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
801                         } else {
802                                 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
803                         }
804                 }
805
806                 return $errors;
807         }
808
809         private static function tableStructure($table)
810         {
811                 // This query doesn't seem to be executable as a prepared statement
812                 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
813
814                 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
815                         ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
816                         'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
817                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
818                         DBA::databaseName(), $table]);
819
820                 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
821                         ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
822                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
823                         DBA::databaseName(), $table]);
824
825                 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
826                         ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
827                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
828                         DBA::databaseName(), $table]);
829
830                 $fielddata = [];
831                 $indexdata = [];
832                 $foreigndata = [];
833
834                 if (DBA::isResult($foreign_keys)) {
835                         foreach ($foreign_keys as $foreign_key) {
836                                 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
837                                 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
838                                 $foreigndata[$constraint] = $foreign_key;
839                         }
840                 }
841
842                 if (DBA::isResult($indexes)) {
843                         foreach ($indexes AS $index) {
844                                 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
845                                         $indexdata[$index["Key_name"]] = ["UNIQUE"];
846                                 }
847
848                                 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
849                                         $indexdata[$index["Key_name"]] = ["FULLTEXT"];
850                                 }
851
852                                 $column = $index["Column_name"];
853
854                                 if ($index["Sub_part"] != "") {
855                                         $column .= "(" . $index["Sub_part"] . ")";
856                                 }
857
858                                 $indexdata[$index["Key_name"]][] = $column;
859                         }
860                 }
861
862                 $fielddata = [];
863                 if (DBA::isResult($fields)) {
864                         foreach ($fields AS $field) {
865                                 $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)'];
866                                 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
867                                 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
868
869                                 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
870
871                                 if ($field['IS_NULLABLE'] == 'NO') {
872                                         $fielddata[$field['COLUMN_NAME']]['not null'] = true;
873                                 }
874
875                                 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
876                                         $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
877                                 }
878
879                                 if (!empty($field['EXTRA'])) {
880                                         $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
881                                 }
882
883                                 if ($field['COLUMN_KEY'] == 'PRI') {
884                                         $fielddata[$field['COLUMN_NAME']]['primary'] = true;
885                                 }
886
887                                 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
888                                 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
889                         }
890                 }
891
892                 return ["fields" => $fielddata, "indexes" => $indexdata,
893                         "foreign_keys" => $foreigndata, "table_status" => $table_status];
894         }
895
896         private static function dropIndex($indexname)
897         {
898                 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
899                 return ($sql);
900         }
901
902         private static function addTableField($fieldname, $parameters)
903         {
904                 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
905                 return ($sql);
906         }
907
908         private static function modifyTableField($fieldname, $parameters)
909         {
910                 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
911                 return ($sql);
912         }
913
914         private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
915         {
916                 $foreign_table = array_keys($parameters['foreign'])[0];
917                 $foreign_field = array_values($parameters['foreign'])[0];
918
919                 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
920         }
921
922         private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
923                 $foreign_table = array_keys($parameters['foreign'])[0];
924                 $foreign_field = array_values($parameters['foreign'])[0];
925
926                 $sql = "FOREIGN KEY (`" . $fieldname . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
927
928                 if (!empty($parameters['foreign']['on update'])) {
929                         $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
930                 } else {
931                         $sql .= " ON UPDATE RESTRICT";
932                 }
933
934                 if (!empty($parameters['foreign']['on delete'])) {
935                         $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
936                 } else {
937                         $sql .= " ON DELETE CASCADE";
938                 }
939
940                 return $sql;
941         }
942
943         private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
944         {
945                 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
946         }
947
948         private static function dropForeignKey(string $constraint)
949         {
950                 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
951         }
952
953         /**
954          * Constructs a GROUP BY clause from a UNIQUE index definition.
955          *
956          * @param array $fieldnames
957          * @return string
958          */
959         private static function groupBy(array $fieldnames)
960         {
961                 if ($fieldnames[0] != "UNIQUE") {
962                         return "";
963                 }
964
965                 array_shift($fieldnames);
966
967                 $names = "";
968                 foreach ($fieldnames AS $fieldname) {
969                         if ($names != "") {
970                                 $names .= ",";
971                         }
972
973                         if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
974                                 $names .= "`" . DBA::escape($matches[1]) . "`";
975                         } else {
976                                 $names .= "`" . DBA::escape($fieldname) . "`";
977                         }
978                 }
979
980                 $sql = sprintf(" GROUP BY %s", $names);
981                 return $sql;
982         }
983
984         /**
985          * Renames columns or the primary key of a table
986          *
987          * @todo You cannot rename a primary key if "auto increment" is set
988          *
989          * @param string $table            Table name
990          * @param array  $columns          Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
991          *                                 Syntax for Primary Key: [ $col1, $col2, ...]
992          * @param int    $type             The type of renaming (Default is Column)
993          *
994          * @return boolean Was the renaming successful?
995          * @throws Exception
996          */
997         public static function rename($table, $columns, $type = self::RENAME_COLUMN)
998         {
999                 if (empty($table) || empty($columns)) {
1000                         return false;
1001                 }
1002
1003                 if (!is_array($columns)) {
1004                         return false;
1005                 }
1006
1007                 $table = DBA::escape($table);
1008
1009                 $sql = "ALTER TABLE `" . $table . "`";
1010                 switch ($type) {
1011                         case self::RENAME_COLUMN:
1012                                 if (!self::existsColumn($table, array_keys($columns))) {
1013                                         return false;
1014                                 }
1015                                 $sql .= implode(',', array_map(
1016                                         function ($to, $from) {
1017                                                 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
1018                                         },
1019                                         $columns,
1020                                         array_keys($columns)
1021                                 ));
1022                                 break;
1023                         case self::RENAME_PRIMARY_KEY:
1024                                 if (!self::existsColumn($table, $columns)) {
1025                                         return false;
1026                                 }
1027                                 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
1028                                 break;
1029                         default:
1030                                 return false;
1031                 }
1032
1033                 $sql .= ";";
1034
1035                 $stmt = DBA::p($sql);
1036
1037                 if (is_bool($stmt)) {
1038                         $retval = $stmt;
1039                 } else {
1040                         $retval = true;
1041                 }
1042
1043                 DBA::close($stmt);
1044
1045                 return $retval;
1046         }
1047
1048         /**
1049          *    Check if the columns of the table exists
1050          *
1051          * @param string $table   Table name
1052          * @param array  $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
1053          *
1054          * @return boolean Does the table exist?
1055          * @throws Exception
1056          */
1057         public static function existsColumn($table, $columns = [])
1058         {
1059                 if (empty($table)) {
1060                         return false;
1061                 }
1062
1063                 if (is_null($columns) || empty($columns)) {
1064                         return self::existsTable($table);
1065                 }
1066
1067                 $table = DBA::escape($table);
1068
1069                 foreach ($columns AS $column) {
1070                         $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
1071
1072                         $stmt = DBA::p($sql);
1073
1074                         if (is_bool($stmt)) {
1075                                 $retval = $stmt;
1076                         } else {
1077                                 $retval = (DBA::numRows($stmt) > 0);
1078                         }
1079
1080                         DBA::close($stmt);
1081
1082                         if (!$retval) {
1083                                 return false;
1084                         }
1085                 }
1086
1087                 return true;
1088         }
1089
1090         /**
1091          * Check if a foreign key exists for the given table field
1092          *
1093          * @param string $table
1094          * @param string $field
1095          * @return boolean
1096          */
1097         public static function existsForeignKeyForField(string $table, string $field)
1098         {
1099                 return DBA::exists(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
1100                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
1101                         DBA::databaseName(), $table, $field]);
1102         }
1103         /**
1104          *    Check if a table exists
1105          *
1106          * @param string|array $table Table name
1107          *
1108          * @return boolean Does the table exist?
1109          * @throws Exception
1110          */
1111         public static function existsTable($table)
1112         {
1113                 if (empty($table)) {
1114                         return false;
1115                 }
1116
1117                 if (is_array($table)) {
1118                         $condition = ['table_schema' => key($table), 'table_name' => current($table)];
1119                 } else {
1120                         $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
1121                 }
1122
1123                 $result = DBA::exists(['information_schema' => 'tables'], $condition);
1124
1125                 return $result;
1126         }
1127
1128         /**
1129          * Returns the columns of a table
1130          *
1131          * @param string $table Table name
1132          *
1133          * @return array An array of the table columns
1134          * @throws Exception
1135          */
1136         public static function getColumns($table)
1137         {
1138                 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
1139                 return DBA::toArray($stmtColumns);
1140         }
1141
1142         /**
1143          * Check if initial database values do exist - or create them
1144          */
1145         public static function checkInitialValues(bool $verbose = false)
1146         {
1147                 if (self::existsTable('verb')) {
1148                         if (!DBA::exists('verb', ['id' => 1])) {
1149                                 foreach (Item::ACTIVITIES as $index => $activity) {
1150                                         DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], Database::INSERT_IGNORE);
1151                                 }
1152                                 if ($verbose) {
1153                                         echo "verb: activities added\n";
1154                                 }
1155                         } elseif ($verbose) {
1156                                 echo "verb: activities already added\n";
1157                         }
1158
1159                         if (!DBA::exists('verb', ['id' => 0])) {
1160                                 DBA::insert('verb', ['name' => '']);
1161                                 $lastid = DBA::lastInsertId();
1162                                 if ($lastid != 0) {
1163                                         DBA::update('verb', ['id' => 0], ['id' => $lastid]);
1164                                         if ($verbose) {
1165                                                 echo "Zero verb added\n";
1166                                         }
1167                                 }
1168                         } elseif ($verbose) {
1169                                 echo "Zero verb already added\n";
1170                         }
1171                 } elseif ($verbose) {
1172                         echo "verb: Table not found\n";
1173                 }
1174
1175                 if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) {
1176                         $user = [
1177                                 "verified" => true,
1178                                 "page-flags" => User::PAGE_FLAGS_SOAPBOX,
1179                                 "account-type" => User::ACCOUNT_TYPE_RELAY,
1180                         ];
1181                         DBA::insert('user', $user);
1182                         $lastid = DBA::lastInsertId();
1183                         if ($lastid != 0) {
1184                                 DBA::update('user', ['uid' => 0], ['uid' => $lastid]);
1185                                 if ($verbose) {
1186                                         echo "Zero user added\n";
1187                                 }
1188                         }
1189                 } elseif (self::existsTable('user') && $verbose) {
1190                         echo "Zero user already added\n";
1191                 } elseif ($verbose) {
1192                         echo "user: Table not found\n";
1193                 }
1194
1195                 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
1196                         DBA::insert('contact', ['nurl' => '']);
1197                         $lastid = DBA::lastInsertId();
1198                         if ($lastid != 0) {
1199                                 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
1200                                 if ($verbose) {
1201                                         echo "Zero contact added\n";
1202                                 }
1203                         }               
1204                 } elseif (self::existsTable('contact') && $verbose) {
1205                         echo "Zero contact already added\n";
1206                 } elseif ($verbose) {
1207                         echo "contact: Table not found\n";
1208                 }
1209
1210                 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
1211                         DBA::insert('tag', ['name' => '']);
1212                         $lastid = DBA::lastInsertId();
1213                         if ($lastid != 0) {
1214                                 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
1215                                 if ($verbose) {
1216                                         echo "Zero tag added\n";
1217                                 }
1218                         }
1219                 } elseif (self::existsTable('tag') && $verbose) {
1220                         echo "Zero tag already added\n";
1221                 } elseif ($verbose) {
1222                         echo "tag: Table not found\n";
1223                 }
1224
1225                 if (self::existsTable('permissionset')) {
1226                         if (!DBA::exists('permissionset', ['id' => 0])) {
1227                                 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);       
1228                                 $lastid = DBA::lastInsertId();
1229                                 if ($lastid != 0) {
1230                                         DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
1231                                         if ($verbose) {
1232                                                 echo "Zero permissionset added\n";
1233                                         }
1234                                 }
1235                         } elseif ($verbose) {
1236                                 echo "Zero permissionset already added\n";
1237                         }
1238                         if (self::existsTable('item') && !self::existsForeignKeyForField('item', 'psid')) {
1239                                 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
1240                                         LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
1241                                         WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
1242                                 while ($set = DBA::fetch($sets)) {
1243                                         if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
1244                                                 $owner = User::getOwnerDataById($set['uid']);
1245                                                 if ($owner) {
1246                                                         $permission = '<' . $owner['id'] . '>';
1247                                                 } else {
1248                                                         $permission = '<>';
1249                                                 }
1250                                         } else {
1251                                                 $permission = '';
1252                                         }
1253                                         $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
1254                                                 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
1255                                         DBA::insert('permissionset', $fields);
1256                                 }
1257                                 DBA::close($sets);
1258                         }
1259                 } elseif ($verbose) {
1260                         echo "permissionset: Table not found\n";
1261                 }
1262         
1263                 if (!self::existsForeignKeyForField('tokens', 'client_id')) {
1264                         $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
1265                                 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
1266                                 WHERE `clients`.`client_id` IS NULL");
1267                         while ($token = DBA::fetch($tokens)) {
1268                                 DBA::delete('tokens', ['id' => $token['id']]);
1269                         }
1270                         DBA::close($tokens);
1271                 }
1272         }
1273
1274         /**
1275          * Checks if a database update is currently running
1276          *
1277          * @return boolean
1278          */
1279         private static function isUpdating()
1280         {
1281                 $isUpdate = false;
1282
1283                 $processes = DBA::select(['information_schema' => 'processlist'], ['info'],
1284                         ['db' => DBA::databaseName(), 'command' => ['Query', 'Execute']]);
1285
1286                 while ($process = DBA::fetch($processes)) {
1287                         $parts = explode(' ', $process['info']);
1288                         if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
1289                                 $isUpdate = true;
1290                         }
1291                 }
1292
1293                 DBA::close($processes);
1294
1295                 return $isUpdate;
1296         }
1297 }