Merge maintenance-work branch:
[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 * @file
7 * @ingroup Maintenance
8 */
9
10 require_once( "Maintenance.php" );
11
12 class RenameDbPrefix extends Maintenance {
13 public function __construct() {
14 parent::__construct();
15 $this->addParam( "old", "Old db prefix [0 for none]", true, true );
16 $this->addParam( "new", "New db prefix [0 for none]", true, true );
17 }
18
19 public function execute() {
20 // Allow for no old prefix
21 if( $this->getOption( 'old', 0 ) === '0' ) {
22 $old = '';
23 } else {
24 // Use nice safe, sane, prefixes
25 preg_match( '/^[a-zA-Z]+_$/', $this->getOption('old'), $m );
26 $old = isset( $m[0] ) ? $m[0] : false;
27 }
28 // Allow for no new prefix
29 if( $this->getOption( 'new', 0 ) === '0' ) {
30 $new = '';
31 } else {
32 // Use nice safe, sane, prefixes
33 preg_match( '/^[a-zA-Z]+_$/', $this->getOption('new'), $m );
34 $new = isset( $m[0] ) ? $m[0] : false;
35 }
36
37 if( $old === false || $new === false ) {
38 $this->error( "Invalid prefix!\n", true );
39 }
40 if( $old === $new ) {
41 $this->( "Same prefix. Nothing to rename!\n", true );
42 }
43
44 $this->output( "Renaming DB prefix for tables of $wgDBname from '$old' to '$new'\n" );
45 $count = 0;
46
47 $dbw = wfGetDB( DB_MASTER );
48 $res = $dbw->query( "SHOW TABLES LIKE '".$dbw->escapeLike( $old )."%'" );
49 foreach( $res as $row ) {
50 // XXX: odd syntax. MySQL outputs an oddly cased "Tables of X"
51 // sort of message. Best not to try $row->x stuff...
52 $fields = get_object_vars( $row );
53 // Silly for loop over one field...
54 foreach( $fields as $resName => $table ) {
55 // $old should be regexp safe ([a-zA-Z_])
56 $newTable = preg_replace( '/^'.$old.'/', $new, $table );
57 $this->output( "Renaming table $table to $newTable\n" );
58 $dbw->query( "RENAME TABLE $table TO $newTable" );
59 }
60 $count++;
61 }
62 $this->output( "Done! [$count tables]\n" );
63 }
64 }