Skip to content

Commit

Permalink
Added dbsum--simple database checksum program
Browse files Browse the repository at this point in the history
  • Loading branch information
dbrady committed Feb 17, 2009
1 parent a519a87 commit 11ea108
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions dbsum
@@ -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

0 comments on commit 11ea108

Please sign in to comment.