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
Improved 5.5 migration path (#14121)
Damian Legawiec0449c4a72e03
diff --git a/spree/core/app/models/spree/store_product.rb b/spree/core/app/models/spree/store_product.rbnew file mode 100644index 0000000000..953190f883--- /dev/null+++ b/spree/core/app/models/spree/store_product.rb@@ -0,0 +1,17 @@+module Spree+ # Thin AR wrapper over the legacy +spree_products_stores+ join table.+ # Pre-5.5 core used this table to attach products to stores; 5.5+ moved+ # that responsibility onto +Spree::Product#store_id+ + +ProductPublication+.+ #+ # The model exists only to power the 5.4 → 5.5 backfill rake task+ # (+spree:upgrade:populate_publications+). Host apps upgrading from 5.4+ # still have the table; after the backfill runs, +spree_multi_store+ (for+ # multi-store catalogs) keeps the table around, and single-store+ # installations may drop it.+ class StoreProduct < Spree.base_class+ self.table_name = 'spree_products_stores'++ belongs_to :product, class_name: 'Spree::Product'+ belongs_to :store, class_name: 'Spree::Store'+ end+enddiff --git a/spree/core/lib/tasks/publications.rake b/spree/core/lib/tasks/publications.rakeindex c01f0abe86..9cfa8edbe5 100644--- a/spree/core/lib/tasks/publications.rake+++ b/spree/core/lib/tasks/publications.rake@@ -8,78 +8,53 @@ namespace :spree doRun once after upgrading to Spree 5.5+. Multi-store merchants must install+spree_multi_store+ before running; running on a multi-store catalog without- the extension picks one "home" store per product per the rules below:-- 1. The store flagged +default: true+ if the product is published there- 2. Otherwise the first store (by +spree_products_stores.created_at+)+ the extension picks the earliest +spree_products_stores+ row (by+ +created_at+) as the product's home store.DESCtask populate_publications: :environment do- legacy_table = 'spree_products_stores'-- unless ActiveRecord::Base.connection.table_exists?(legacy_table)- puts " #{legacy_table} table not found — nothing to migrate."+ unless ActiveRecord::Base.connection.table_exists?(Spree::StoreProduct.table_name)+ puts " #{Spree::StoreProduct.table_name} table not found — nothing to migrate."nextend- products_processed = 0+ batch_size = (ENV['BATCH_SIZE'] || 1_000).to_ipublications_created = 0- # Legacy +spree_products_stores+ pre-5.5 carries only product_id,- # store_id, created_at (plus the +units_sold_count+/+revenue+ columns- # we no longer read here). Channel attribution + publication windows- # are derived from the destination store's default channel.- Spree::Product.where(store_id: nil).find_each do |product|- sql = ActiveRecord::Base.sanitize_sql_array([- "SELECT store_id, created_at FROM #{legacy_table} WHERE product_id = ? ORDER BY created_at ASC",- product.id- ])- rows = ActiveRecord::Base.connection.select_all(sql).to_a-- next if rows.empty?-- home_store_id = pick_home_store(rows)- store_ids = rows.map { |r| r['store_id'] }.uniq-- # Build publications + store_id assignment atomically. If the- # publication writes fail (validation, deadlock, etc.) we rollback- # so a re-run can retry — the +store_id IS NULL+ filter at the top- # of the loop only matches products that didn't finish.- ActiveRecord::Base.transaction do- store_ids.each do |store_id|- channel = Spree::Store.find(store_id).default_channel- next unless channel+ # Pass 1: per store, batch-publish products onto the store's default+ # channel via +Channel#add_products+. One upsert + one touch_all per+ # batch beats the previous per-product loop by orders of magnitude on+ # large catalogs. +add_products+ is upsert-based with +on_duplicate:+ # :skip+, so existing publications on re-run are no-ops.+ Spree::Store.find_each do |store|+ channel = store.default_channel+ unless channel+ puts " Store '#{store.name}' has no default channel — skipping."+ next+ end- publication = Spree::ProductPublication.find_or_initialize_by(- product_id: product.id,- channel_id: channel.id- )+ store_publications = 0+ Spree::StoreProduct.where(store_id: store.id).in_batches(of: batch_size) do |batch|+ store_publications += channel.add_products(batch.pluck(:product_id))+ end- next if publication.persisted?+ publications_created += store_publications+ puts " Store '#{store.name}': created #{store_publications} publication(s)" if store_publications.positive?+ end- publication.save!- publications_created += 1- end+ # Pass 2: assign +store_id+ on products that still don't have one,+ # using the earliest legacy row per product.+ products_processed = 0- product.update_column(:store_id, home_store_id)- end+ Spree::Product.where(store_id: nil).find_each(batch_size: batch_size) do |product|+ store_id = Spree::StoreProduct.where(product_id: product.id).order(:created_at).limit(1).pick(:store_id)+ next unless store_id+ product.update_column(:store_id, store_id)products_processed += 1endputs " Processed #{products_processed} products"puts " Created #{publications_created} publications"end-- # When a product was attached to multiple stores via the legacy join,- # pick the default store if it's in the list — otherwise the earliest- # row (rows are pre-sorted by +created_at+).- def pick_home_store(rows)- default_store_id = Spree::Store.find_by(default: true)&.id- if default_store_id && rows.any? { |r| r['store_id'] == default_store_id }- default_store_id- else- rows.first['store_id']- end- endendenddiff --git a/spree/core/spec/lib/tasks/publications_spec.rb b/spree/core/spec/lib/tasks/publications_spec.rbnew file mode 100644index 0000000000..9aa0a77e3a--- /dev/null+++ b/spree/core/spec/lib/tasks/publications_spec.rb@@ -0,0 +1,105 @@+require 'spec_helper'+require 'rake'++describe 'spree:upgrade:populate_publications' do+ subject { Rake::Task[task_name] }++ let(:task_name) { 'spree:upgrade:populate_publications' }++ before(:all) do+ Rake::Task.define_task(:environment)+ load Spree::Core::Engine.root.join('lib', 'tasks', 'publications.rake')+ end++ before { subject.reenable }++ # Simulate the pre-5.5 catalog state: a row in +spree_products_stores+ for+ # the product/store pair, +Product#store_id+ nil, and no +ProductPublication++ # for the store's default channel. The product factory auto-attaches both,+ # so we strip them and rebuild the legacy join row directly.+ def downgrade!(product, store)+ product.product_publications.destroy_all+ product.update_columns(store_id: nil)+ Spree::StoreProduct.create!(product: product, store: store)+ end++ let!(:default_store) { Spree::Store.default || create(:store, default: true) }++ context 'single store' do+ let!(:channel) { default_store.default_channel || create(:channel, store: default_store) }+ let!(:product) { create(:product, store: default_store) }++ before { downgrade!(product, default_store) }++ it 'creates a publication on the default channel' do+ expect { subject.invoke }.to change {+ Spree::ProductPublication.where(product_id: product.id, channel_id: channel.id).exists?+ }.from(false).to(true)+ end++ it 'sets store_id on the product' do+ expect { subject.invoke }.to change { product.reload.store_id }.from(nil).to(default_store.id)+ end++ it 'is idempotent — a re-run creates no extra publications' do+ subject.invoke+ subject.reenable+ expect { subject.invoke }.not_to change { Spree::ProductPublication.count }+ end+ end++ context 'multi-store catalog (single-store backfill mode)' do+ let!(:other_store) { create(:store, default: false) }+ let!(:default_channel) { default_store.default_channel || create(:channel, store: default_store) }+ let!(:other_channel) { other_store.default_channel || create(:channel, store: other_store) }+ let!(:product) { create(:product, store: default_store) }++ before do+ downgrade!(product, default_store)+ # Earliest legacy row wins for store_id. Backdate +default_store+'s+ # row so it's older than +other_store+'s and assert it's chosen.+ Spree::StoreProduct.where(product_id: product.id).update_all(created_at: 2.days.ago)+ Spree::StoreProduct.create!(product: product, store: other_store, created_at: 1.day.ago)+ end++ it 'publishes the product on every store it was attached to' do+ subject.invoke+ expect(Spree::ProductPublication.where(product_id: product.id).pluck(:channel_id))+ .to match_array([default_channel.id, other_channel.id])+ end++ it 'sets product.store_id from the earliest legacy row' do+ expect { subject.invoke }.to change { product.reload.store_id }.from(nil).to(default_store.id)+ end+ end++ context 'store without a default channel' do+ let!(:other_store) { create(:store, default: false) }+ let!(:product) { create(:product, store: default_store) }++ before do+ downgrade!(product, default_store)+ # Strip channels off +other_store+ to simulate the warning path.+ other_store.channels.destroy_all+ Spree::StoreProduct.create!(product: product, store: other_store)+ end++ it 'skips that store with a warning and still processes the rest' do+ expect { subject.invoke }+ .to output(/has no default channel/).to_stdout+ .and change { product.reload.store_id }.from(nil).to(default_store.id)+ end+ end++ context 'legacy table not present' do+ before do+ allow(ActiveRecord::Base.connection).to receive(:table_exists?).and_call_original+ allow(ActiveRecord::Base.connection)+ .to receive(:table_exists?).with('spree_products_stores').and_return(false)+ end++ it 'no-ops with a message' do+ expect { subject.invoke }.to output(/nothing to migrate/).to_stdout+ end+ end+end