Skip to content

Instantly share code, notes, and snippets.

@zetta
Last active August 29, 2015 14:01
Show Gist options
  • Save zetta/6bc7c4572eb461ec9bef to your computer and use it in GitHub Desktop.
Save zetta/6bc7c4572eb461ec9bef to your computer and use it in GitHub Desktop.
<?php
$oldName = get_argument(1, 'You must specify the current database name', true);
$newName = get_argument(2, 'You must specify the new database name', true);
try
{
echo 'Database renamer 1.0', "\n\n";
echo "Renaming database ${oldName} to ${newName}\n";
echo 'Connecting to mysql...', "\n";
$pdo = new PDO('mysql:host=localhost;charset=UTF8', 'root');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Creating target database', "\n";
$pdo->exec('CREATE DATABASE IF NOT EXISTS '.$newName);
echo 'Retrieving table information', "\n";
$statement = $pdo->query('SHOW FULL TABLES IN '. $oldName .' WHERE Table_Type = \'BASE TABLE\'');
$tables = array();
foreach ($statement->fetchAll() as $table) {
$tables[] = $table[0];
}
$totalTables = count($tables);
echo 'Moving tables to new database', "\n";
foreach ($tables as $idx => $table) {
$i = $idx+1;
for ($a = 0; $a < 100; $a++) echo "\x08";
$name = table_name($table);
echo 'Moving table ', $name , ' ', round($i/$totalTables*100, 2), '% ';
$query = sprintf('RENAME TABLE %1$s.%3$s to %2$s.%3$s', $oldName, $newName, $table);
$pdo->exec($query);
}
echo "\n", 'Droping old database', "\n";
$pdo->exec('DROP DATABASE IF EXISTS '.$oldName);
echo 'Job finished!!', "\n";
} catch(Exception $e)
{
die($e->getMessage()."\n");
}
/**
* format the table name
* @param string $name
* @param int $max
* @return string
*/
function table_name($name, $max = 50)
{
if (strlen($name) > $max){
$name = substr($name, 0, floor($max/2)).'...'.substr($name, (floor($max/2)-3)*-1);
}
return str_pad($name, $max);
}
/**
* get the cli argument
*/
function get_argument($index, $errorMessage = 'Argument %s is required', $exitOnFail = false)
{
global $argv;
if (isset($argv[$index]))
return $argv[$index];
else
{
echo sprintf($errorMessage, $index), "\n";
if ($exitOnFail)
exit(1);
}
}
@zetta
Copy link
Author

zetta commented Oct 9, 2014

Usage:

$ php renamer.php old_database_name new_database_name

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment