Skip to content

Instantly share code, notes, and snippets.

@mhorbul
Created April 10, 2009 16:39
Show Gist options
  • Save mhorbul/93158 to your computer and use it in GitHub Desktop.
Save mhorbul/93158 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
#
# Detect the models which are associated with non existing account.
#
# Usage:
# $ cd RAILS_ROOT
# $ RAILS_ENV=test ./check-assoc
#
require 'config/environment'
db_config = YAML.load(File.open("config/database.yml"))[RAILS_ENV]
cmd = case db_config["adapter"]
when "mysql" then
"mysqldump #{db_config["database"]} -u root --compact -d | ruby -pe 'gsub /([\(,])\n/, \"\\1\"' | grep 'CREATE TABLE' | grep account_id | cut -d' ' -f3 | sed 's/`//g'"
when "sqlite3" then
"echo '.schema' | sqlite3 #{RAILS_ROOT}/#{db_config["database"]} | grep 'CREATE TABLE' | grep account_id | cut -d' ' -f 3 | sed 's/\"//g'"
else
raise "dabase driver is not supported"
end
account_ids = Account.all.map(&:id)
pipe = IO.popen(cmd)
pipe.readlines.each do |l|
table = l.strip
klass = Object.class_eval { const_get table.classify }
ids = klass.all(:conditions => "account_id not in (#{account_ids.join(',')})").map(&:id)
puts "#{klass}: #{ids.empty? ? 'ok' : ids.inspect}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment