Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize number of transactions sent in refresh #14670

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 18 additions & 8 deletions app/models/ems_refresh/save_inventory_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,17 +53,21 @@ def save_inventory_multi(association, hashes, deletes, find_key, child_keys = []

new_records = []

hashes.each do |h|
found = save_inventory_with_findkey(association, h.except(*remove_keys), deletes_index, new_records, record_index)
save_child_inventory(found, h, child_keys)
ActiveRecord::Base.transaction do
hashes.each do |h|
found = save_inventory_with_findkey(association, h.except(*remove_keys), deletes_index, new_records, record_index)
save_child_inventory(found, h, child_keys)
end
end

# Delete the items no longer found
deletes = deletes_index.values
unless deletes.blank?
type = association.proxy_association.reflection.name
_log.info("[#{type}] Deleting #{log_format_deletes(deletes)}")
disconnect ? deletes.each(&:disconnect_inv) : association.delete(deletes)
ActiveRecord::Base.transaction do
type = association.proxy_association.reflection.name
_log.info("[#{type}] Deleting #{log_format_deletes(deletes)}")
disconnect ? deletes.each(&:disconnect_inv) : association.delete(deletes)
end
end

# Add the new items
Expand All @@ -80,7 +84,7 @@ def save_inventory_single(type, parent, hash, child_keys = [], extra_keys = [],
child_keys = Array.wrap(child_keys)
remove_keys = Array.wrap(extra_keys) + child_keys + [:id]
if child
child.update_attributes!(hash.except(:type, *remove_keys))
update_attributes!(child, hash, [:type, *remove_keys])
else
child = parent.send("create_#{type}!", hash.except(*remove_keys))
end
Expand All @@ -94,12 +98,18 @@ def save_inventory_with_findkey(association, hash, deletes, new_records, record_
found = association.build(hash.except(:id))
new_records << found
else
found.update_attributes!(hash.except(:id, :type))
update_attributes!(found, hash, [:id, :type])
deletes.delete(found) unless deletes.blank?
end
found
end

def update_attributes!(ar_model, attributes, remove_keys)
ar_model.assign_attributes(attributes.except(*remove_keys))
# HACK: Avoid empty BEGIN/COMMIT pair until fix is made for https://github.com/rails/rails/issues/17937
ar_model.save! if ar_model.changed?
end

def backup_keys(hash, keys)
keys.each_with_object({}) { |k, backup| backup[k] = hash.delete(k) if hash.key?(k) }
end
Expand Down