MediaWiki master
renameDbPrefix.php
Go to the documentation of this file.
1<?php
27
28// @codeCoverageIgnoreStart
29require_once __DIR__ . '/Maintenance.php';
30// @codeCoverageIgnoreEnd
31
37class RenameDbPrefix extends Maintenance {
38 public function __construct() {
39 parent::__construct();
40 $this->addOption( "old", "Old db prefix [0 for none]", true, true );
41 $this->addOption( "new", "New db prefix [0 for none]", true, true );
42 }
43
44 public function getDbType() {
45 return Maintenance::DB_ADMIN;
46 }
47
48 public function execute() {
49 $dbName = $this->getConfig()->get( MainConfigNames::DBname );
50
51 // Allow for no old prefix
52 if ( $this->getOption( 'old', 0 ) === '0' ) {
53 $old = '';
54 } else {
55 // Use nice safe, sensible, prefixes
56 preg_match( '/^[a-zA-Z]+_$/', $this->getOption( 'old' ), $m );
57 $old = $m[0] ?? false;
58 }
59 // Allow for no new prefix
60 if ( $this->getOption( 'new', 0 ) === '0' ) {
61 $new = '';
62 } else {
63 // Use nice safe, sensible, prefixes
64 preg_match( '/^[a-zA-Z]+_$/', $this->getOption( 'new' ), $m );
65 $new = $m[0] ?? false;
66 }
67
68 if ( $old === false || $new === false ) {
69 $this->fatalError( "Invalid prefix!" );
70 }
71 if ( $old === $new ) {
72 $this->output( "Same prefix. Nothing to rename!\n", true );
73 }
74
75 $this->output( "Renaming DB prefix for tables of $dbName from '$old' to '$new'\n" );
76 $count = 0;
77
78 $dbw = $this->getPrimaryDB();
79 $res = $dbw->query( "SHOW TABLES " . $dbw->buildLike( $old, $dbw->anyString() ), __METHOD__ );
80 foreach ( $res as $row ) {
81 // XXX: odd syntax. MySQL outputs an oddly cased "Tables of X"
82 // sort of message. Best not to try $row->x stuff...
83 $fields = get_object_vars( $row );
84 // Silly for loop over one field...
85 foreach ( $fields as $table ) {
86 // $old should be regexp safe ([a-zA-Z_])
87 $newTable = preg_replace( '/^' . $old . '/', $new, $table );
88 $this->output( "Renaming table $table to $newTable\n" );
89 $oldTableEnc = $dbw->addIdentifierQuotes( $table );
90 $newTableEnc = $dbw->addIdentifierQuotes( $newTable );
91 $dbw->query( "RENAME TABLE $oldTableEnc TO $newTableEnc", __METHOD__ );
92 }
93 $count++;
94 }
95 $this->output( "Done! [$count tables]\n" );
96 }
97}
98
99// @codeCoverageIgnoreStart
100$maintClass = RenameDbPrefix::class;
101require_once RUN_MAINTENANCE_IF_MAIN;
102// @codeCoverageIgnoreEnd
A class containing constants representing the names of configuration variables.
Maintenance script that changes the prefix of database tables.
$maintClass