From 04b07a1ff57301cfe37c579d6ce1781fe3403a63 Mon Sep 17 00:00:00 2001 From: Maikel Linke Date: Fri, 28 Jun 2019 16:22:28 +1000 Subject: [PATCH] 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. --- app/models/exchange.rb | 2 +- lib/open_food_network/products_cache.rb | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/app/models/exchange.rb b/app/models/exchange.rb index c85c2f9d8d..5566737a3f 100644 --- a/app/models/exchange.rb +++ b/app/models/exchange.rb @@ -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| diff --git a/lib/open_food_network/products_cache.rb b/lib/open_food_network/products_cache.rb index f099b43fba..089dc83030 100644 --- a/lib/open_food_network/products_cache.rb +++ b/lib/open_food_network/products_cache.rb @@ -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