Last active
October 16, 2015 20:35
-
-
Save wivarn/f3dcc4b17409b6e38f2d to your computer and use it in GitHub Desktop.
Scan the database for invalid records
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
HEADERS = [ | |
"Recrod ID", | |
"Created At", | |
"Updated At", | |
"Error Messages" | |
] | |
def all_models | |
tables = ActiveRecord::Base.connection.tables.sort | |
tables.map { |name| name.classify.safe_constantize }.compact | |
end | |
def scan_db | |
all_models.each do |model| | |
File.open("broken_records/summary.csv", "a") { |f| f.write("#{Time.now}|#{model}|#{model.count}|") } | |
invalid_record_count = 0 | |
File.open("broken_records/#{record.class}.csv", "a") do |f| | |
# sets delimiter to pipe | |
f.puts('"sep=|"') | |
f.puts(HEADERS.join("|")) | |
end | |
model.find_each do |record| | |
if record.invalid? | |
invalid_record_count += 1 | |
File.open("broken_records/#{record.class}.csv", "a") do |f| | |
f.puts("#{record.id}|#{record.created_at}|#{record.updated_at}|#{record.errors.messages}") | |
end | |
end | |
end | |
File.open("broken_records/summary.csv", "a") { |f| f.puts(invalid_record_count) } | |
end | |
end | |
namespace :invalid_records do | |
desc "Find and log all invalid records in DB (ONLY RUN ON PRODUCTION CLONE)" | |
task find: :environment do | |
FileUtils.mkdir_p "broken_records" | |
File.open("broken_records/summary.csv", "a") do |f| | |
f.puts('"sep=|"') | |
f.puts("Time|Table|Total Records|Invalid Records") | |
end | |
scan_db | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment