Further optimise querying affected exchanges

The implementation queried the database for each incoming variant that
was changed. This rewrite combines ActiveRecord relations so that it
creates only one query. This saves another 5-10% of execution time when
updating enterprise fees on production instances.
This commit is contained in:
Maikel Linke
2019-06-28 16:22:28 +10:00
parent 0da7c93bc6
commit 04b07a1ff5
2 changed files with 8 additions and 8 deletions

View File

@@ -38,7 +38,7 @@ class Exchange < ActiveRecord::Base
}
scope :with_any_variant, lambda { |variant_ids|
joins(:exchange_variants).
where('exchange_variants.variant_id IN (?)', variant_ids).
where(exchange_variants: { variant_id: variant_ids }).
select('DISTINCT exchanges.*')
}
scope :with_product, lambda { |product|

View File

@@ -165,13 +165,13 @@ module OpenFoodNetwork
private_class_method :incoming_exchanges
def self.outgoing_exchanges_affected_by(exchanges)
incoming_exchanges(exchanges).map do |incoming_exchange|
outgoing_exchanges_with_variants(
incoming_exchange.order_cycle,
incoming_exchange.variant_ids
)
end.flatten.uniq { |ex| [ex.receiver_id, ex.order_cycle_id]}
# Comparing only on these two ids is much faster.
incoming = incoming_exchanges(exchanges)
order_cycle_ids = incoming.select(:order_cycle_id)
variant_ids = ExchangeVariant.where(exchange_id: incoming).select(:variant_id)
Exchange.outgoing.
in_order_cycle(order_cycle_ids).
with_any_variant(variant_ids).
except(:select).select("DISTINCT receiver_id, order_cycle_id")
end
private_class_method :outgoing_exchanges_affected_by