Replace `global` keyword with `$GLOBALS`
[phpmyadmin.git] / libraries / classes / Operations.php
bloba314c4071ecc61d61c431e61d20b8caa03c5ea0d
1 <?php
3 declare(strict_types=1);
5 namespace PhpMyAdmin;
7 use PhpMyAdmin\ConfigStorage\Relation;
8 use PhpMyAdmin\Engines\Innodb;
9 use PhpMyAdmin\Partitioning\Partition;
10 use PhpMyAdmin\Plugins\Export\ExportSql;
12 use function __;
13 use function array_keys;
14 use function array_merge;
15 use function count;
16 use function explode;
17 use function is_scalar;
18 use function is_string;
19 use function mb_strtolower;
20 use function str_replace;
21 use function strlen;
22 use function strtolower;
23 use function urldecode;
25 /**
26 * Set of functions with the operations section in phpMyAdmin
28 class Operations
30 /** @var Relation */
31 private $relation;
33 /** @var DatabaseInterface */
34 private $dbi;
36 /**
37 * @param DatabaseInterface $dbi DatabaseInterface object
38 * @param Relation $relation Relation object
40 public function __construct(DatabaseInterface $dbi, Relation $relation)
42 $this->dbi = $dbi;
43 $this->relation = $relation;
46 /**
47 * Run the Procedure definitions and function definitions
49 * to avoid selecting alternatively the current and new db
50 * we would need to modify the CREATE definitions to qualify
51 * the db name
53 * @param string $db database name
55 public function runProcedureAndFunctionDefinitions($db): void
57 $procedure_names = $this->dbi->getProceduresOrFunctions($db, 'PROCEDURE');
58 if ($procedure_names) {
59 foreach ($procedure_names as $procedure_name) {
60 $this->dbi->selectDb($db);
61 $tmp_query = $this->dbi->getDefinition($db, 'PROCEDURE', $procedure_name);
62 if ($tmp_query === null) {
63 continue;
66 // collect for later display
67 $GLOBALS['sql_query'] .= "\n" . $tmp_query;
68 $this->dbi->selectDb($_POST['newname']);
69 $this->dbi->query($tmp_query);
73 $function_names = $this->dbi->getProceduresOrFunctions($db, 'FUNCTION');
74 if (! $function_names) {
75 return;
78 foreach ($function_names as $function_name) {
79 $this->dbi->selectDb($db);
80 $tmp_query = $this->dbi->getDefinition($db, 'FUNCTION', $function_name);
81 if ($tmp_query === null) {
82 continue;
85 // collect for later display
86 $GLOBALS['sql_query'] .= "\n" . $tmp_query;
87 $this->dbi->selectDb($_POST['newname']);
88 $this->dbi->query($tmp_query);
92 /**
93 * Create database before copy
95 public function createDbBeforeCopy(): void
97 $local_query = 'CREATE DATABASE IF NOT EXISTS '
98 . Util::backquote($_POST['newname']);
99 if (isset($_POST['db_collation'])) {
100 $local_query .= ' DEFAULT'
101 . Util::getCharsetQueryPart($_POST['db_collation'] ?? '');
104 $local_query .= ';';
105 $GLOBALS['sql_query'] .= $local_query;
107 // save the original db name because Tracker.php which
108 // may be called under $this->dbi->query() changes $GLOBALS['db']
109 // for some statements, one of which being CREATE DATABASE
110 $original_db = $GLOBALS['db'];
111 $this->dbi->query($local_query);
112 $GLOBALS['db'] = $original_db;
114 // Set the SQL mode to NO_AUTO_VALUE_ON_ZERO to prevent MySQL from creating
115 // export statements it cannot import
116 $sql_set_mode = "SET SQL_MODE='NO_AUTO_VALUE_ON_ZERO'";
117 $this->dbi->query($sql_set_mode);
119 // rebuild the database list because Table::moveCopy
120 // checks in this list if the target db exists
121 $GLOBALS['dblist']->databases->build();
125 * Get views as an array and create SQL view stand-in
127 * @param array $tables_full array of all tables in given db or dbs
128 * @param ExportSql $export_sql_plugin export plugin instance
129 * @param string $db database name
131 * @return array
133 public function getViewsAndCreateSqlViewStandIn(
134 array $tables_full,
135 $export_sql_plugin,
138 $views = [];
139 foreach (array_keys($tables_full) as $each_table) {
140 // to be able to rename a db containing views,
141 // first all the views are collected and a stand-in is created
142 // the real views are created after the tables
143 if (! $this->dbi->getTable($db, (string) $each_table)->isView()) {
144 continue;
147 // If view exists, and 'add drop view' is selected: Drop it!
148 if ($_POST['what'] !== 'nocopy' && isset($_POST['drop_if_exists']) && $_POST['drop_if_exists'] === 'true') {
149 $drop_query = 'DROP VIEW IF EXISTS '
150 . Util::backquote($_POST['newname']) . '.'
151 . Util::backquote($each_table);
152 $this->dbi->query($drop_query);
154 $GLOBALS['sql_query'] .= "\n" . $drop_query . ';';
157 $views[] = $each_table;
158 // Create stand-in definition to resolve view dependencies
159 $sql_view_standin = $export_sql_plugin->getTableDefStandIn($db, $each_table, "\n");
160 $this->dbi->selectDb($_POST['newname']);
161 $this->dbi->query($sql_view_standin);
162 $GLOBALS['sql_query'] .= "\n" . $sql_view_standin;
165 return $views;
169 * Get sql query for copy/rename table and boolean for whether copy/rename or not
171 * @param array $tables_full array of all tables in given db or dbs
172 * @param bool $move whether database name is empty or not
173 * @param string $db database name
175 * @return array SQL queries for the constraints
177 public function copyTables(array $tables_full, $move, $db)
179 $sqlContraints = [];
180 foreach (array_keys($tables_full) as $each_table) {
181 // skip the views; we have created stand-in definitions
182 if ($this->dbi->getTable($db, (string) $each_table)->isView()) {
183 continue;
186 // value of $what for this table only
187 $this_what = $_POST['what'];
189 // do not copy the data from a Merge table
190 // note: on the calling FORM, 'data' means 'structure and data'
191 if ($this->dbi->getTable($db, (string) $each_table)->isMerge()) {
192 if ($this_what === 'data') {
193 $this_what = 'structure';
196 if ($this_what === 'dataonly') {
197 $this_what = 'nocopy';
201 if ($this_what === 'nocopy') {
202 continue;
205 // keep the triggers from the original db+table
206 // (third param is empty because delimiters are only intended
207 // for importing via the mysql client or our Import feature)
208 $triggers = $this->dbi->getTriggers($db, (string) $each_table, '');
210 if (
211 ! Table::moveCopy(
212 $db,
213 $each_table,
214 $_POST['newname'],
215 $each_table,
216 ($this_what ?? 'data'),
217 $move,
218 'db_copy',
219 isset($_POST['drop_if_exists']) && $_POST['drop_if_exists'] === 'true'
222 $GLOBALS['_error'] = true;
223 break;
226 // apply the triggers to the destination db+table
227 if ($triggers) {
228 $this->dbi->selectDb($_POST['newname']);
229 foreach ($triggers as $trigger) {
230 $this->dbi->query($trigger['create']);
231 $GLOBALS['sql_query'] .= "\n" . $trigger['create'] . ';';
235 // this does not apply to a rename operation
236 if (! isset($_POST['add_constraints']) || empty($GLOBALS['sql_constraints_query'])) {
237 continue;
240 $sqlContraints[] = $GLOBALS['sql_constraints_query'];
241 unset($GLOBALS['sql_constraints_query']);
244 return $sqlContraints;
248 * Run the EVENT definition for selected database
250 * to avoid selecting alternatively the current and new db
251 * we would need to modify the CREATE definitions to qualify
252 * the db name
254 * @param string $db database name
256 public function runEventDefinitionsForDb($db): void
258 $event_names = $this->dbi->fetchResult(
259 'SELECT EVENT_NAME FROM information_schema.EVENTS WHERE EVENT_SCHEMA= \''
260 . $this->dbi->escapeString($db) . '\';'
262 if (! $event_names) {
263 return;
266 foreach ($event_names as $event_name) {
267 $this->dbi->selectDb($db);
268 $tmp_query = $this->dbi->getDefinition($db, 'EVENT', $event_name);
269 // collect for later display
270 $GLOBALS['sql_query'] .= "\n" . $tmp_query;
271 $this->dbi->selectDb($_POST['newname']);
272 $this->dbi->query($tmp_query);
277 * Handle the views, return the boolean value whether table rename/copy or not
279 * @param array $views views as an array
280 * @param bool $move whether database name is empty or not
281 * @param string $db database name
283 public function handleTheViews(array $views, $move, $db): void
285 // Add DROP IF EXIST to CREATE VIEW query, to remove stand-in VIEW that was created earlier.
286 foreach ($views as $view) {
287 $copying_succeeded = Table::moveCopy(
288 $db,
289 $view,
290 $_POST['newname'],
291 $view,
292 'structure',
293 $move,
294 'db_copy',
295 true
297 if (! $copying_succeeded) {
298 $GLOBALS['_error'] = true;
299 break;
305 * Adjust the privileges after Renaming the db
307 * @param string $oldDb Database name before renaming
308 * @param string $newname New Database name requested
310 public function adjustPrivilegesMoveDb($oldDb, $newname): void
312 if (
313 ! $GLOBALS['db_priv'] || ! $GLOBALS['table_priv']
314 || ! $GLOBALS['col_priv'] || ! $GLOBALS['proc_priv']
315 || ! $GLOBALS['is_reload_priv']
317 return;
320 $this->dbi->selectDb('mysql');
321 $newname = str_replace('_', '\_', $newname);
322 $oldDb = str_replace('_', '\_', $oldDb);
324 // For Db specific privileges
325 $query_db_specific = 'UPDATE ' . Util::backquote('db')
326 . 'SET Db = \'' . $this->dbi->escapeString($newname)
327 . '\' where Db = \'' . $this->dbi->escapeString($oldDb) . '\';';
328 $this->dbi->query($query_db_specific);
330 // For table specific privileges
331 $query_table_specific = 'UPDATE ' . Util::backquote('tables_priv')
332 . 'SET Db = \'' . $this->dbi->escapeString($newname)
333 . '\' where Db = \'' . $this->dbi->escapeString($oldDb) . '\';';
334 $this->dbi->query($query_table_specific);
336 // For column specific privileges
337 $query_col_specific = 'UPDATE ' . Util::backquote('columns_priv')
338 . 'SET Db = \'' . $this->dbi->escapeString($newname)
339 . '\' where Db = \'' . $this->dbi->escapeString($oldDb) . '\';';
340 $this->dbi->query($query_col_specific);
342 // For procedures specific privileges
343 $query_proc_specific = 'UPDATE ' . Util::backquote('procs_priv')
344 . 'SET Db = \'' . $this->dbi->escapeString($newname)
345 . '\' where Db = \'' . $this->dbi->escapeString($oldDb) . '\';';
346 $this->dbi->query($query_proc_specific);
348 // Finally FLUSH the new privileges
349 $flush_query = 'FLUSH PRIVILEGES;';
350 $this->dbi->query($flush_query);
354 * Adjust the privileges after Copying the db
356 * @param string $oldDb Database name before copying
357 * @param string $newname New Database name requested
359 public function adjustPrivilegesCopyDb($oldDb, $newname): void
361 if (
362 ! $GLOBALS['db_priv'] || ! $GLOBALS['table_priv']
363 || ! $GLOBALS['col_priv'] || ! $GLOBALS['proc_priv']
364 || ! $GLOBALS['is_reload_priv']
366 return;
369 $this->dbi->selectDb('mysql');
370 $newname = str_replace('_', '\_', $newname);
371 $oldDb = str_replace('_', '\_', $oldDb);
373 $query_db_specific_old = 'SELECT * FROM '
374 . Util::backquote('db') . ' WHERE '
375 . 'Db = "' . $oldDb . '";';
377 $old_privs_db = $this->dbi->fetchResult($query_db_specific_old, 0);
379 foreach ($old_privs_db as $old_priv) {
380 $newDb_db_privs_query = 'INSERT INTO ' . Util::backquote('db')
381 . ' VALUES("' . $old_priv[0] . '", "' . $newname . '"';
382 $privCount = count($old_priv);
383 for ($i = 2; $i < $privCount; $i++) {
384 $newDb_db_privs_query .= ', "' . $old_priv[$i] . '"';
387 $newDb_db_privs_query .= ')';
389 $this->dbi->query($newDb_db_privs_query);
392 // For Table Specific privileges
393 $query_table_specific_old = 'SELECT * FROM '
394 . Util::backquote('tables_priv') . ' WHERE '
395 . 'Db = "' . $oldDb . '";';
397 $old_privs_table = $this->dbi->fetchResult($query_table_specific_old, 0);
399 foreach ($old_privs_table as $old_priv) {
400 $newDb_table_privs_query = 'INSERT INTO ' . Util::backquote(
401 'tables_priv'
402 ) . ' VALUES("' . $old_priv[0] . '", "' . $newname . '", "'
403 . $old_priv[2] . '", "' . $old_priv[3] . '", "' . $old_priv[4]
404 . '", "' . $old_priv[5] . '", "' . $old_priv[6] . '", "'
405 . $old_priv[7] . '");';
407 $this->dbi->query($newDb_table_privs_query);
410 // For Column Specific privileges
411 $query_col_specific_old = 'SELECT * FROM '
412 . Util::backquote('columns_priv') . ' WHERE '
413 . 'Db = "' . $oldDb . '";';
415 $old_privs_col = $this->dbi->fetchResult($query_col_specific_old, 0);
417 foreach ($old_privs_col as $old_priv) {
418 $newDb_col_privs_query = 'INSERT INTO ' . Util::backquote(
419 'columns_priv'
420 ) . ' VALUES("' . $old_priv[0] . '", "' . $newname . '", "'
421 . $old_priv[2] . '", "' . $old_priv[3] . '", "' . $old_priv[4]
422 . '", "' . $old_priv[5] . '", "' . $old_priv[6] . '");';
424 $this->dbi->query($newDb_col_privs_query);
427 // For Procedure Specific privileges
428 $query_proc_specific_old = 'SELECT * FROM '
429 . Util::backquote('procs_priv') . ' WHERE '
430 . 'Db = "' . $oldDb . '";';
432 $old_privs_proc = $this->dbi->fetchResult($query_proc_specific_old, 0);
434 foreach ($old_privs_proc as $old_priv) {
435 $newDb_proc_privs_query = 'INSERT INTO ' . Util::backquote(
436 'procs_priv'
437 ) . ' VALUES("' . $old_priv[0] . '", "' . $newname . '", "'
438 . $old_priv[2] . '", "' . $old_priv[3] . '", "' . $old_priv[4]
439 . '", "' . $old_priv[5] . '", "' . $old_priv[6] . '", "'
440 . $old_priv[7] . '");';
442 $this->dbi->query($newDb_proc_privs_query);
445 // Finally FLUSH the new privileges
446 $flush_query = 'FLUSH PRIVILEGES;';
447 $this->dbi->query($flush_query);
451 * Create all accumulated constraints
453 * @param array $sqlConstratints array of sql constraints for the database
455 public function createAllAccumulatedConstraints(array $sqlConstratints): void
457 $this->dbi->selectDb($_POST['newname']);
458 foreach ($sqlConstratints as $one_query) {
459 $this->dbi->query($one_query);
460 // and prepare to display them
461 $GLOBALS['sql_query'] .= "\n" . $one_query;
466 * Duplicate the bookmarks for the db (done once for each db)
468 * @param bool $_error whether table rename/copy or not
469 * @param string $db database name
471 public function duplicateBookmarks($_error, $db): void
473 if ($_error || $db == $_POST['newname']) {
474 return;
477 $get_fields = [
478 'user',
479 'label',
480 'query',
482 $where_fields = ['dbase' => $db];
483 $new_fields = ['dbase' => $_POST['newname']];
484 Table::duplicateInfo('bookmarkwork', 'bookmark', $get_fields, $where_fields, $new_fields);
488 * Get array of possible row formats
490 * @return array
492 public function getPossibleRowFormat()
494 // the outer array is for engines, the inner array contains the dropdown
495 // option values as keys then the dropdown option labels
497 $possible_row_formats = [
498 'ARCHIVE' => ['COMPRESSED' => 'COMPRESSED'],
499 'ARIA' => [
500 'FIXED' => 'FIXED',
501 'DYNAMIC' => 'DYNAMIC',
502 'PAGE' => 'PAGE',
504 'MARIA' => [
505 'FIXED' => 'FIXED',
506 'DYNAMIC' => 'DYNAMIC',
507 'PAGE' => 'PAGE',
509 'MYISAM' => [
510 'FIXED' => 'FIXED',
511 'DYNAMIC' => 'DYNAMIC',
513 'PBXT' => [
514 'FIXED' => 'FIXED',
515 'DYNAMIC' => 'DYNAMIC',
517 'INNODB' => [
518 'COMPACT' => 'COMPACT',
519 'REDUNDANT' => 'REDUNDANT',
523 /** @var Innodb $innodbEnginePlugin */
524 $innodbEnginePlugin = StorageEngine::getEngine('Innodb');
525 $innodbPluginVersion = $innodbEnginePlugin->getInnodbPluginVersion();
526 $innodb_file_format = '';
527 if (! empty($innodbPluginVersion)) {
528 $innodb_file_format = $innodbEnginePlugin->getInnodbFileFormat() ?? '';
532 * Newer MySQL/MariaDB always return empty a.k.a '' on $innodb_file_format otherwise
533 * old versions of MySQL/MariaDB must be returning something or not empty.
534 * This patch is to support newer MySQL/MariaDB while also for backward compatibilities.
536 if (
537 (strtolower($innodb_file_format) === 'barracuda') || ($innodb_file_format == '')
538 && $innodbEnginePlugin->supportsFilePerTable()
540 $possible_row_formats['INNODB']['DYNAMIC'] = 'DYNAMIC';
541 $possible_row_formats['INNODB']['COMPRESSED'] = 'COMPRESSED';
544 return $possible_row_formats;
548 * @return array<string, string>
550 public function getPartitionMaintenanceChoices(): array
552 $choices = [
553 'ANALYZE' => __('Analyze'),
554 'CHECK' => __('Check'),
555 'OPTIMIZE' => __('Optimize'),
556 'REBUILD' => __('Rebuild'),
557 'REPAIR' => __('Repair'),
558 'TRUNCATE' => __('Truncate'),
561 $partitionMethod = Partition::getPartitionMethod($GLOBALS['db'], $GLOBALS['table']);
563 // add COALESCE or DROP option to choices array depending on Partition method
564 if (
565 $partitionMethod === 'RANGE'
566 || $partitionMethod === 'RANGE COLUMNS'
567 || $partitionMethod === 'LIST'
568 || $partitionMethod === 'LIST COLUMNS'
570 $choices['DROP'] = __('Drop');
571 } else {
572 $choices['COALESCE'] = __('Coalesce');
575 return $choices;
579 * @param array $urlParams Array of url parameters.
580 * @param bool $hasRelationFeature If relation feature is enabled.
582 * @return array
584 public function getForeignersForReferentialIntegrityCheck(
585 array $urlParams,
586 $hasRelationFeature
587 ): array {
588 if (! $hasRelationFeature) {
589 return [];
592 $foreigners = [];
593 $this->dbi->selectDb($GLOBALS['db']);
594 $foreign = $this->relation->getForeigners($GLOBALS['db'], $GLOBALS['table'], '', 'internal');
596 foreach ($foreign as $master => $arr) {
597 $joinQuery = 'SELECT '
598 . Util::backquote($GLOBALS['table']) . '.*'
599 . ' FROM ' . Util::backquote($GLOBALS['table'])
600 . ' LEFT JOIN '
601 . Util::backquote($arr['foreign_db'])
602 . '.'
603 . Util::backquote($arr['foreign_table']);
605 if ($arr['foreign_table'] == $GLOBALS['table']) {
606 $foreignTable = $GLOBALS['table'] . '1';
607 $joinQuery .= ' AS ' . Util::backquote($foreignTable);
608 } else {
609 $foreignTable = $arr['foreign_table'];
612 $joinQuery .= ' ON '
613 . Util::backquote($GLOBALS['table']) . '.'
614 . Util::backquote($master)
615 . ' = '
616 . Util::backquote($arr['foreign_db'])
617 . '.'
618 . Util::backquote($foreignTable) . '.'
619 . Util::backquote($arr['foreign_field'])
620 . ' WHERE '
621 . Util::backquote($arr['foreign_db'])
622 . '.'
623 . Util::backquote($foreignTable) . '.'
624 . Util::backquote($arr['foreign_field'])
625 . ' IS NULL AND '
626 . Util::backquote($GLOBALS['table']) . '.'
627 . Util::backquote($master)
628 . ' IS NOT NULL';
629 $thisUrlParams = array_merge(
630 $urlParams,
632 'sql_query' => $joinQuery,
633 'sql_signature' => Core::signSqlQuery($joinQuery),
637 $foreigners[] = [
638 'params' => $thisUrlParams,
639 'master' => $master,
640 'db' => $arr['foreign_db'],
641 'table' => $arr['foreign_table'],
642 'field' => $arr['foreign_field'],
646 return $foreigners;
650 * Get table alters array
652 * @param Table $pma_table The Table object
653 * @param string $pack_keys pack keys
654 * @param string $checksum value of checksum
655 * @param string $page_checksum value of page checksum
656 * @param string $delay_key_write delay key write
657 * @param string $row_format row format
658 * @param string $newTblStorageEngine table storage engine
659 * @param string $transactional value of transactional
660 * @param string $tbl_collation collation of the table
662 * @return array
664 public function getTableAltersArray(
665 $pma_table,
666 $pack_keys,
667 $checksum,
668 $page_checksum,
669 $delay_key_write,
670 $row_format,
671 $newTblStorageEngine,
672 $transactional,
673 $tbl_collation
675 $table_alters = [];
677 if (isset($_POST['comment']) && urldecode($_POST['prev_comment']) !== $_POST['comment']) {
678 $table_alters[] = 'COMMENT = \''
679 . $this->dbi->escapeString($_POST['comment']) . '\'';
682 if (
683 ! empty($newTblStorageEngine)
684 && mb_strtolower($newTblStorageEngine) !== mb_strtolower($GLOBALS['tbl_storage_engine'])
686 $table_alters[] = 'ENGINE = ' . $newTblStorageEngine;
689 if (! empty($_POST['tbl_collation']) && $_POST['tbl_collation'] !== $tbl_collation) {
690 $table_alters[] = 'DEFAULT '
691 . Util::getCharsetQueryPart($_POST['tbl_collation'] ?? '');
694 if (
695 $pma_table->isEngine(['MYISAM', 'ARIA', 'ISAM'])
696 && isset($_POST['new_pack_keys'])
697 && $_POST['new_pack_keys'] != (string) $pack_keys
699 $table_alters[] = 'pack_keys = ' . $_POST['new_pack_keys'];
702 $newChecksum = empty($_POST['new_checksum']) ? '0' : '1';
703 if ($pma_table->isEngine(['MYISAM', 'ARIA']) && $newChecksum !== $checksum) {
704 $table_alters[] = 'checksum = ' . $newChecksum;
707 $newTransactional = empty($_POST['new_transactional']) ? '0' : '1';
708 if ($pma_table->isEngine('ARIA') && $newTransactional !== $transactional) {
709 $table_alters[] = 'TRANSACTIONAL = ' . $newTransactional;
712 $newPageChecksum = empty($_POST['new_page_checksum']) ? '0' : '1';
713 if ($pma_table->isEngine('ARIA') && $newPageChecksum !== $page_checksum) {
714 $table_alters[] = 'PAGE_CHECKSUM = ' . $newPageChecksum;
717 $newDelayKeyWrite = empty($_POST['new_delay_key_write']) ? '0' : '1';
718 if ($pma_table->isEngine(['MYISAM', 'ARIA']) && $newDelayKeyWrite !== $delay_key_write) {
719 $table_alters[] = 'delay_key_write = ' . $newDelayKeyWrite;
722 if (
723 $pma_table->isEngine(['MYISAM', 'ARIA', 'INNODB', 'PBXT', 'ROCKSDB'])
724 && ! empty($_POST['new_auto_increment'])
725 && (! isset($GLOBALS['auto_increment'])
726 || $_POST['new_auto_increment'] !== $GLOBALS['auto_increment'])
727 && $_POST['new_auto_increment'] !== $_POST['hidden_auto_increment']
729 $table_alters[] = 'auto_increment = '
730 . $this->dbi->escapeString($_POST['new_auto_increment']);
733 if (! empty($_POST['new_row_format'])) {
734 $newRowFormat = $_POST['new_row_format'];
735 $newRowFormatLower = mb_strtolower($newRowFormat);
736 if (
737 $pma_table->isEngine(['MYISAM', 'ARIA', 'INNODB', 'PBXT'])
738 && (strlen($row_format) === 0
739 || $newRowFormatLower !== mb_strtolower($row_format))
741 $table_alters[] = 'ROW_FORMAT = '
742 . $this->dbi->escapeString($newRowFormat);
746 return $table_alters;
750 * Get warning messages array
752 * @return string[]
754 public function getWarningMessagesArray(): array
756 $warning_messages = [];
757 foreach ($this->dbi->getWarnings() as $warning) {
758 // In MariaDB 5.1.44, when altering a table from Maria to MyISAM
759 // and if TRANSACTIONAL was set, the system reports an error;
760 // I discussed with a Maria developer and he agrees that this
761 // should not be reported with a Level of Error, so here
762 // I just ignore it. But there are other 1478 messages
763 // that it's better to show.
764 if (
765 isset($_POST['new_tbl_storage_engine'])
766 && $_POST['new_tbl_storage_engine'] === 'MyISAM'
767 && $warning->code === 1478
768 && $warning->level === 'Error'
770 continue;
773 $warning_messages[] = (string) $warning;
776 return $warning_messages;
780 * Adjust the privileges after renaming/moving a table
782 * @param string $oldDb Database name before table renaming/moving table
783 * @param string $oldTable Table name before table renaming/moving table
784 * @param string $newDb Database name after table renaming/ moving table
785 * @param string $newTable Table name after table renaming/moving table
787 public function adjustPrivilegesRenameOrMoveTable($oldDb, $oldTable, $newDb, $newTable): void
789 if (! $GLOBALS['table_priv'] || ! $GLOBALS['col_priv'] || ! $GLOBALS['is_reload_priv']) {
790 return;
793 $this->dbi->selectDb('mysql');
795 // For table specific privileges
796 $query_table_specific = 'UPDATE ' . Util::backquote('tables_priv')
797 . 'SET Db = \'' . $this->dbi->escapeString($newDb)
798 . '\', Table_name = \'' . $this->dbi->escapeString($newTable)
799 . '\' where Db = \'' . $this->dbi->escapeString($oldDb)
800 . '\' AND Table_name = \'' . $this->dbi->escapeString($oldTable)
801 . '\';';
802 $this->dbi->query($query_table_specific);
804 // For column specific privileges
805 $query_col_specific = 'UPDATE ' . Util::backquote('columns_priv')
806 . 'SET Db = \'' . $this->dbi->escapeString($newDb)
807 . '\', Table_name = \'' . $this->dbi->escapeString($newTable)
808 . '\' where Db = \'' . $this->dbi->escapeString($oldDb)
809 . '\' AND Table_name = \'' . $this->dbi->escapeString($oldTable)
810 . '\';';
811 $this->dbi->query($query_col_specific);
813 // Finally FLUSH the new privileges
814 $flush_query = 'FLUSH PRIVILEGES;';
815 $this->dbi->query($flush_query);
819 * Adjust the privileges after copying a table
821 * @param string $oldDb Database name before table copying
822 * @param string $oldTable Table name before table copying
823 * @param string $newDb Database name after table copying
824 * @param string $newTable Table name after table copying
826 public function adjustPrivilegesCopyTable($oldDb, $oldTable, $newDb, $newTable): void
828 if (! $GLOBALS['table_priv'] || ! $GLOBALS['col_priv'] || ! $GLOBALS['is_reload_priv']) {
829 return;
832 $this->dbi->selectDb('mysql');
834 // For Table Specific privileges
835 $query_table_specific_old = 'SELECT * FROM '
836 . Util::backquote('tables_priv') . ' where '
837 . 'Db = "' . $oldDb . '" AND Table_name = "' . $oldTable . '";';
839 $old_privs_table = $this->dbi->fetchResult($query_table_specific_old, 0);
841 foreach ($old_privs_table as $old_priv) {
842 $newDb_table_privs_query = 'INSERT INTO '
843 . Util::backquote('tables_priv') . ' VALUES("'
844 . $old_priv[0] . '", "' . $newDb . '", "' . $old_priv[2] . '", "'
845 . $newTable . '", "' . $old_priv[4] . '", "' . $old_priv[5]
846 . '", "' . $old_priv[6] . '", "' . $old_priv[7] . '");';
848 $this->dbi->query($newDb_table_privs_query);
851 // For Column Specific privileges
852 $query_col_specific_old = 'SELECT * FROM '
853 . Util::backquote('columns_priv') . ' WHERE '
854 . 'Db = "' . $oldDb . '" AND Table_name = "' . $oldTable . '";';
856 $old_privs_col = $this->dbi->fetchResult($query_col_specific_old, 0);
858 foreach ($old_privs_col as $old_priv) {
859 $newDb_col_privs_query = 'INSERT INTO '
860 . Util::backquote('columns_priv') . ' VALUES("'
861 . $old_priv[0] . '", "' . $newDb . '", "' . $old_priv[2] . '", "'
862 . $newTable . '", "' . $old_priv[4] . '", "' . $old_priv[5]
863 . '", "' . $old_priv[6] . '");';
865 $this->dbi->query($newDb_col_privs_query);
868 // Finally FLUSH the new privileges
869 $flush_query = 'FLUSH PRIVILEGES;';
870 $this->dbi->query($flush_query);
874 * Change all collations and character sets of all columns in table
876 * @param string $db Database name
877 * @param string $table Table name
878 * @param string $tbl_collation Collation Name
880 public function changeAllColumnsCollation($db, $table, $tbl_collation): void
882 $this->dbi->selectDb($db);
884 $change_all_collations_query = 'ALTER TABLE '
885 . Util::backquote($table)
886 . ' CONVERT TO';
888 [$charset] = explode('_', $tbl_collation);
890 $change_all_collations_query .= ' CHARACTER SET ' . $charset
891 . ($charset == $tbl_collation ? '' : ' COLLATE ' . $tbl_collation);
893 $this->dbi->query($change_all_collations_query);
897 * Move or copy a table
899 * @param string $db current database name
900 * @param string $table current table name
902 public function moveOrCopyTable($db, $table): Message
905 * Selects the database to work with
907 $this->dbi->selectDb($db);
910 * $_POST['target_db'] could be empty in case we came from an input field
911 * (when there are many databases, no drop-down)
913 $targetDb = $db;
914 if (isset($_POST['target_db']) && is_string($_POST['target_db']) && strlen($_POST['target_db']) > 0) {
915 $targetDb = $_POST['target_db'];
919 * A target table name has been sent to this script -> do the work
921 if (isset($_POST['new_name']) && is_scalar($_POST['new_name']) && strlen((string) $_POST['new_name']) > 0) {
922 if ($db == $targetDb && $table == $_POST['new_name']) {
923 if (isset($_POST['submit_move'])) {
924 $message = Message::error(__('Can\'t move table to same one!'));
925 } else {
926 $message = Message::error(__('Can\'t copy table to same one!'));
928 } else {
929 Table::moveCopy(
930 $db,
931 $table,
932 $targetDb,
933 (string) $_POST['new_name'],
934 $_POST['what'],
935 isset($_POST['submit_move']),
936 'one_table',
937 isset($_POST['drop_if_exists']) && $_POST['drop_if_exists'] === 'true'
940 if (isset($_POST['adjust_privileges']) && ! empty($_POST['adjust_privileges'])) {
941 if (isset($_POST['submit_move'])) {
942 $this->adjustPrivilegesRenameOrMoveTable($db, $table, $targetDb, (string) $_POST['new_name']);
943 } else {
944 $this->adjustPrivilegesCopyTable($db, $table, $targetDb, (string) $_POST['new_name']);
947 if (isset($_POST['submit_move'])) {
948 $message = Message::success(
950 'Table %s has been moved to %s. Privileges have been adjusted.'
953 } else {
954 $message = Message::success(
956 'Table %s has been copied to %s. Privileges have been adjusted.'
960 } else {
961 if (isset($_POST['submit_move'])) {
962 $message = Message::success(
963 __('Table %s has been moved to %s.')
965 } else {
966 $message = Message::success(
967 __('Table %s has been copied to %s.')
972 $old = Util::backquote($db) . '.'
973 . Util::backquote($table);
974 $message->addParam($old);
976 $new_name = (string) $_POST['new_name'];
977 if ($this->dbi->getLowerCaseNames() === '1') {
978 $new_name = strtolower($new_name);
981 $GLOBALS['table'] = $new_name;
983 $new = Util::backquote($targetDb) . '.'
984 . Util::backquote($new_name);
985 $message->addParam($new);
987 } else {
989 * No new name for the table!
991 $message = Message::error(__('The table name is empty!'));
994 return $message;