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