Merge maintenance-work branch (now with less errors!):
[lhc/web/wiklou.git] / maintenance / renameDbPrefix.php
1 <?php
2 /**
3 * Run this script to after changing $wgDBprefix on a wiki.
4 * The wiki will have to get downtime to do this correctly.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @ingroup Maintenance
22 */
23
24 require_once( "Maintenance.php" );
25
26 class RenameDbPrefix extends Maintenance {
27 public function __construct() {
28 parent::__construct();
29 $this->addOption( "old", "Old db prefix [0 for none]", true, true );
30 $this->addOption( "new", "New db prefix [0 for none]", true, true );
31 }
32
33 public function execute() {
34 // Allow for no old prefix
35 if( $this->getOption( 'old', 0 ) === '0' ) {
36 $old = '';
37 } else {
38 // Use nice safe, sane, prefixes
39 preg_match( '/^[a-zA-Z]+_$/', $this->getOption('old'), $m );
40 $old = isset( $m[0] ) ? $m[0] : false;
41 }
42 // Allow for no new prefix
43 if( $this->getOption( 'new', 0 ) === '0' ) {
44 $new = '';
45 } else {
46 // Use nice safe, sane, prefixes
47 preg_match( '/^[a-zA-Z]+_$/', $this->getOption('new'), $m );
48 $new = isset( $m[0] ) ? $m[0] : false;
49 }
50
51 if( $old === false || $new === false ) {
52 $this->error( "Invalid prefix!\n", true );
53 }
54 if( $old === $new ) {
55 $this->output( "Same prefix. Nothing to rename!\n", true );
56 }
57
58 $this->output( "Renaming DB prefix for tables of $wgDBname from '$old' to '$new'\n" );
59 $count = 0;
60
61 $dbw = wfGetDB( DB_MASTER );
62 $res = $dbw->query( "SHOW TABLES LIKE '".$dbw->escapeLike( $old )."%'" );
63 foreach( $res as $row ) {
64 // XXX: odd syntax. MySQL outputs an oddly cased "Tables of X"
65 // sort of message. Best not to try $row->x stuff...
66 $fields = get_object_vars( $row );
67 // Silly for loop over one field...
68 foreach( $fields as $resName => $table ) {
69 // $old should be regexp safe ([a-zA-Z_])
70 $newTable = preg_replace( '/^'.$old.'/', $new, $table );
71 $this->output( "Renaming table $table to $newTable\n" );
72 $dbw->query( "RENAME TABLE $table TO $newTable" );
73 }
74 $count++;
75 }
76 $this->output( "Done! [$count tables]\n" );
77 }
78 }
79
80 $maintClass = "RenameDbPrefix";
81 require_once( DO_MAINTENANCE );