Clone ExchangeVariant objects in bulk

An ExchangeVariant is a simple representation of a join table between Exchange and Variant. Previously this code was triggering an additional INSERT query for every variant added to the newly cloned exchange. Some exchanges have ~3000 variants! The code now creates them in bulk in a single INSERT statement. When cloning large order cycles this can improve performance by ~1000% or so.
This commit is contained in:
Matt-Yorkley
2023-05-11 20:28:28 +01:00
parent 1bdb668cd3
commit b139087c5f

View File

@@ -86,9 +86,9 @@ class Exchange < ApplicationRecord
exchange = dup
exchange.order_cycle = new_order_cycle
exchange.enterprise_fee_ids = enterprise_fee_ids
exchange.variant_ids = variant_ids
exchange.tag_ids = tag_ids
exchange.save!
clone_all_exchange_variants(exchange.id)
exchange
end
@@ -105,4 +105,14 @@ class Exchange < ApplicationRecord
receiver.touch_later
end
private
def clone_all_exchange_variants(exchange_id)
return unless variant_ids.any?
ExchangeVariant.insert_all(
variant_ids.map{ |variant_id| { variant_id: variant_id, exchange_id: exchange_id } }
)
end
end