Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Stop listing variants a query at a time (#14556)
Damian Legawiec6bc302291a38
diff --git a/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rbindex e1fb8a2269..5d74f741ab 100644--- a/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rb@@ -15,15 +15,22 @@ module SpreeSpree.api.admin_variant_serializerend+ # Chains onto the base scope rather than replacing it: building the+ # relation from scratch dropped `scope_includes`, so every listed+ # variant fell back to per-row price and stock queries.def scope- current_store.variants.eligible.accessible_by(current_ability, ability_action_for_request)+ super.eligible.accessible_by(current_ability, ability_action_for_request)end+ # `active_stock_reservations` rides along with the stock levels:+ # without it the quantifier falls back to a SUM per variant, which+ # is the whole cost of listing variants.def scope_includes[- :prices, stock_levels: :stock_location,- option_values: :option_type,- primary_media: [attachment_attachment: :blob, poster_attachment: :blob]+ :prices,+ { stock_levels: [:stock_location, :active_stock_reservations] },+ { option_values: :option_type },+ { primary_media: [{ attachment_attachment: :blob }, { poster_attachment: :blob }] }]endenddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/variants_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/variants_controller_spec.rbindex 37c86f6297..3b18cd15bd 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/variants_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/variants_controller_spec.rb@@ -20,6 +20,50 @@ RSpec.describe Spree::Api::V3::Admin::VariantsController, type: :controller doexpect(json_response['data'].map { |v| v['id'] }).to include(variant.prefixed_id)end+ # The variant picker asks for only the three fields it renders, which+ # keeps the autocomplete's payload to what it displays.+ it 'returns only the requested fields, plus id' do+ get :index, params: { fields: 'product_name,sku,options_text' }, as: :json++ expect(response).to have_http_status(:ok)+ row = json_response['data'].first+ expect(row.keys).to match_array(%w[id product_name sku options_text])+ end++ # The controller's `scope_includes` only applies if `scope` chains onto+ # the base rather than rebuilding the relation. When it does not, prices+ # and stock are read once per listed variant and nothing fails — so the+ # guard is that the cost does not grow with the number of rows.+ it 'reads prices and stock once, not once per variant' do+ rows = []+ counts = [0, 3].map do |extra_variants|+ create_list(:variant, extra_variants, product: product) if extra_variants > 0++ stock_and_price = 0+ subscription = ActiveSupport::Notifications.subscribe('sql.active_record') do |*, payload|+ next if payload[:cached]+ next unless payload[:name].to_s.match?(/Price|StockLevel|StockReservation/)++ stock_and_price += 1+ end+ begin+ get :index, as: :json+ ensure+ # A leaked subscriber would keep counting into later examples.+ ActiveSupport::Notifications.unsubscribe(subscription)+ end++ expect(response).to have_http_status(:ok)+ rows << json_response['data'].size+ stock_and_price+ end++ # The second request really did list more variants — otherwise equal+ # query counts would prove nothing.+ expect(rows.last).to eq(rows.first + 3)+ expect(counts.last).to eq(counts.first)+ end+it 'includes the default variant' dosubjectreturned_ids = json_response['data'].map { |v| v['id'] }diff --git a/spree/core/spec/models/spree/stock/quantifier_spec.rb b/spree/core/spec/models/spree/stock/quantifier_spec.rbindex 3b42ec4a34..1018488e43 100644--- a/spree/core/spec/models/spree/stock/quantifier_spec.rb+++ b/spree/core/spec/models/spree/stock/quantifier_spec.rb@@ -21,6 +21,53 @@ module Spreespecify { expect(subject.stock_levels).to eq([stock_level]) }specify { expect(subject.variant).to eq(stock_level.variant) }+ # The quantifier answers from memory when the caller has already loaded+ # the rows, and falls back to SQL when it has not. Listing endpoints+ # preload precisely so they take the first path — without coverage, a+ # dropped `includes` turns a page of variants back into a query per row+ # with nothing failing.+ describe 'preloaded associations' do+ def count_queries+ count = 0+ subscription = ActiveSupport::Notifications.subscribe('sql.active_record') do |*, payload|+ next if payload[:cached] || payload[:name].to_s.match?(/SCHEMA|TRANSACTION/)+ # Only stock reads matter here: `should_track_inventory?` looks up+ # the product and store, which no amount of stock preloading avoids.+ next unless payload[:name].to_s.match?(/StockLevel|StockReservation/)++ count += 1+ end+ yield+ count+ ensure+ ActiveSupport::Notifications.unsubscribe(subscription)+ end++ let(:variant) { stock_level.variant }++ it 'answers from the loaded rows without querying' do+ preloaded = Spree::Variant.+ where(id: variant.id).+ includes(stock_levels: [:stock_location, :active_stock_reservations]).+ first+ quantifier = described_class.new(preloaded)++ queries = count_queries do+ quantifier.available_stock+ quantifier.reserved_quantity+ end++ expect(queries).to eq(0)+ expect(quantifier.available_stock).to eq(described_class.new(variant).available_stock)+ end++ it 'queries when the rows are not loaded' do+ quantifier = described_class.new(Spree::Variant.find(variant.id))++ expect(count_queries { quantifier.available_stock }).to be > 0+ end+ end+context 'with a single stock location/item' doit 'total_on_hand should match stock_level' doexpect(subject.total_on_hand).to eq(stock_level.count_on_hand)