Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added dbsum--simple database checksum program
- Loading branch information
Showing
1 changed file
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
#!/usr/bin/env ruby | ||
# | ||
# dbsum.rb - Checksum a database. Useful when trying to quickly | ||
# determine if two databases are equivalent. Takes the count of each | ||
# table, the contents of the first and last record in each table (if | ||
# any) and then md5sums the whole mess. | ||
require 'rubygems' | ||
require 'mysql' | ||
require 'digest/md5' | ||
|
||
database=ARGV[0] || 'leadgen_development' | ||
|
||
tables = [] | ||
stats = Hash.new { |h,k| h[k] = Hash.new } | ||
|
||
begin | ||
# connect to the MySQL server | ||
dbh = Mysql.real_connect("localhost", "root", "", database) | ||
|
||
# get tables | ||
|
||
res = dbh.query("SHOW TABLES") | ||
while row = res.fetch_row do | ||
tables << row[0] | ||
end | ||
res.free | ||
columns = 0 | ||
tables.each do |table| | ||
# DANGER - these leak memory because they never call res.free. | ||
# Don't use this in a long-running script! | ||
stats[table][:count] = dbh.query("SELECT COUNT(*) FROM #{table}").fetch_row[0] | ||
|
||
# Get contents of first and last row. FIXME: Not all tables have | ||
# id columns! They SHOULD in the Railsverse, but might not--habtm | ||
# tables notoriously do not have ids. | ||
end | ||
|
||
rescue Mysql::Error => e | ||
puts "Error code: #{e.errno}" | ||
puts "Error message: #{e.error}" | ||
puts "Error SQLSTATE: #{e.sqlstate}" if e.respond_to?("sqlstate") | ||
ensure | ||
# disconnect from server | ||
dbh.close if dbh | ||
end | ||
|
||
fingerprint = tables.sort.map {|t| "#{t}:#{stats[t][:count]}"} * ';' | ||
|
||
puts '-' * 80 | ||
puts "Database Signature:" | ||
puts fingerprint | ||
puts '-' * 80 | ||
puts "Database Fingerprint: #{Digest::SHA1.hexdigest(fingerprint)}" | ||
puts '-' * 80 | ||
|