Skip to content

Commit

Permalink
Wrap in a transaction, rollback on dry-run or error
Browse files Browse the repository at this point in the history
  • Loading branch information
jrafanie committed Jun 18, 2018
1 parent 8b4fe07 commit 51be173
Showing 1 changed file with 27 additions and 16 deletions.
43 changes: 27 additions & 16 deletions tools/remove_grouping_from_report_results.rb
Expand Up @@ -18,9 +18,11 @@
# Load rails after trollop options are set. No one wants to wait for -h.
require File.expand_path('../config/environment', __dir__)

# Wrap all changes in a transaction and roll them back if dry-run or an error occurs.
ActiveRecord::Base.connection.begin_transaction(:joinable => false)

if opts[:dry_run]
puts "Running in dry-run, changes will be rolled back when complete."
ActiveRecord::Base.connection.begin_transaction(:joinable => false)
puts "Running in dry-run, all changes will be rolled back when complete."

at_exit do
ActiveRecord::Base.connection.rollback_transaction
Expand All @@ -30,23 +32,32 @@
start = Time.now.utc
total = 0
fixed = 0

MiqReportResult.find_each(:batch_size => opts[:batch_size]).with_index do |rr, i|
break if opts[:count].positive? && i == opts[:count]
next if rr.report.nil? || rr.report.extras.nil?

if rr.report.extras.key?(:grouping)
rr.report.extras.except!(:grouping)
rr.save!
if rr.reload.report.extras.key?(:grouping)
puts "MiqReportResult: #{rr.id} could NOT be fixed"
begin
break if opts[:count].positive? && i == opts[:count]
next if rr.report.nil? || rr.report.extras.nil?

if rr.report.extras.key?(:grouping)
rr.report.extras.except!(:grouping)
rr.save!
if rr.reload.report.extras.key?(:grouping)
puts "MiqReportResult: #{rr.id} could NOT be fixed"
else
puts "MiqReportResult: #{rr.id} fixed"
fixed += 1
end
else
puts "MiqReportResult: #{rr.id} fixed"
fixed += 1
puts "MiqReportResult: #{rr.id} doesn't need fixing"
end
else
puts "MiqReportResult: #{rr.id} doesn't need fixing"

total += 1
rescue => err
puts "\nWarning: Rolling back all changes since an error occurred on MiqReportResult with id: #{rr.try(:id)}: #{err.message}"
ActiveRecord::Base.connection.rollback_transaction unless opts[:dry_run]
exit 1
end
total += 1
end

puts "Processed #{total} rows. #{fixed} were fixed. #{Time.now.utc - start} seconds"
ActiveRecord::Base.connection.commit_transaction unless opts[:dry_run]
puts "\nProcessed #{total} rows. #{fixed} were fixed. #{Time.now.utc - start} seconds"

0 comments on commit 51be173

Please sign in to comment.