MediaWiki  REL1_22
renameDbPrefix.php
Go to the documentation of this file.
00001 <?php
00026 require_once __DIR__ . '/Maintenance.php';
00027 
00033 class RenameDbPrefix extends Maintenance {
00034     public function __construct() {
00035         parent::__construct();
00036         $this->addOption( "old", "Old db prefix [0 for none]", true, true );
00037         $this->addOption( "new", "New db prefix [0 for none]", true, true );
00038     }
00039 
00040     public function getDbType() {
00041         return Maintenance::DB_ADMIN;
00042     }
00043 
00044     public function execute() {
00045         global $wgDBname;
00046 
00047         // Allow for no old prefix
00048         if ( $this->getOption( 'old', 0 ) === '0' ) {
00049             $old = '';
00050         } else {
00051             // Use nice safe, sane, prefixes
00052             preg_match( '/^[a-zA-Z]+_$/', $this->getOption( 'old' ), $m );
00053             $old = isset( $m[0] ) ? $m[0] : false;
00054         }
00055         // Allow for no new prefix
00056         if ( $this->getOption( 'new', 0 ) === '0' ) {
00057             $new = '';
00058         } else {
00059             // Use nice safe, sane, prefixes
00060             preg_match( '/^[a-zA-Z]+_$/', $this->getOption( 'new' ), $m );
00061             $new = isset( $m[0] ) ? $m[0] : false;
00062         }
00063 
00064         if ( $old === false || $new === false ) {
00065             $this->error( "Invalid prefix!", true );
00066         }
00067         if ( $old === $new ) {
00068             $this->output( "Same prefix. Nothing to rename!\n", true );
00069         }
00070 
00071         $this->output( "Renaming DB prefix for tables of $wgDBname from '$old' to '$new'\n" );
00072         $count = 0;
00073 
00074         $dbw = wfGetDB( DB_MASTER );
00075         $res = $dbw->query( "SHOW TABLES " . $dbw->buildLike( $old, $dbw->anyString() ) );
00076         foreach ( $res as $row ) {
00077             // XXX: odd syntax. MySQL outputs an oddly cased "Tables of X"
00078             // sort of message. Best not to try $row->x stuff...
00079             $fields = get_object_vars( $row );
00080             // Silly for loop over one field...
00081             foreach ( $fields as $table ) {
00082                 // $old should be regexp safe ([a-zA-Z_])
00083                 $newTable = preg_replace( '/^' . $old . '/', $new, $table );
00084                 $this->output( "Renaming table $table to $newTable\n" );
00085                 $dbw->query( "RENAME TABLE $table TO $newTable" );
00086             }
00087             $count++;
00088         }
00089         $this->output( "Done! [$count tables]\n" );
00090     }
00091 }
00092 
00093 $maintClass = "RenameDbPrefix";
00094 require_once RUN_MAINTENANCE_IF_MAIN;