Friday, May 04, 2007

Comparing mysql databases

I was recently working on a project between two servers (dev and live). The goal was to compare the structures of the two databases so I could merge the changes I made on dev and import them to live. I had a problem though...the mysql versions between the two were slightly different and so were the phpmyadmin versions and the mysqldump versions. I tried dumps using all three tools. However because of version differences, I could not get a good comparison between the two databases. I had no way to easily compare the two! So, I decided to use my programming legs and write a php script. It's a really simple script, but got the job done. I was then able to use winmerge (http://winmerge.org/) and easily tell what the differences between the two were. I called the php script database_describe.php. Keep in mind that you need command-line privileges on your system for this script to work:


$db_host = "127.0.0.1";
$db_name = "db_name";
$db_user = "mysql_username";
$db_pass = "mysql_password";

$link = mysql_connect ($db_host, $db_user, $db_pass) or die ('Cannot Connect to mysql db!');
mysql_select_db ($db_name);


$query = "SHOW TABLES";
$table_result = mysql_query($query);
while ($table_row = mysql_fetch_assoc($table_result))
{
$table_name = $table_row['Tables_in_'.$db_name];

$query = "DESCRIBE ".$table_name;

echo $table_name."\n";
echo "----------------------\n";

$describe_result = mysql_query($query);
while ($describe_row = mysql_fetch_assoc($describe_result))
{
echo $describe_row['Field']."\t".$describe_row['Type']."\n";
}

echo "\n\n";
}
?>


To run this program, I simply typed the following on the command line:
php database_describe.php > outputfile.txt

outputfileand then used my favorite sftp transfer program (filezilla or winscp) to download the dump that was made into outputfile.txt and repeated the step on the other system.

I know this is an absolute kludge that has to be done from the command line. Perhaps I'll write a web interface to do the same thing someday.

No comments: