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