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
Remove PgSearch, convert add_search_scope to standard scopes, deprecate unused scopes
Damian Legawiec994b95d8b6b4
diff --git a/spree/core/app/models/concerns/spree/product_scopes.rb b/spree/core/app/models/concerns/spree/product_scopes.rbindex 7b92354851..3adda77f7b 100644--- a/spree/core/app/models/concerns/spree/product_scopes.rb+++ b/spree/core/app/models/concerns/spree/product_scopes.rb@@ -3,41 +3,20 @@ module Spreeextend ActiveSupport::Concernincluded do- cattr_accessor :search_scopes do- []- end-- def self.add_search_scope(name, &block)- singleton_class.send(:define_method, name.to_sym, &block)- search_scopes << name.to_sym- end-- def self.simple_scopes- [- :ascend_by_updated_at,- :descend_by_updated_at,- :ascend_by_name,- :descend_by_name- ]- end-- def self.add_simple_scopes(scopes)- scopes.each do |name|- # We should not define price scopes here, as they require something slightly different- next if name.to_s.include?('master_price')-- parts = name.to_s.match(/(.*)_by_(.*)/)- scope(name.to_s, -> { order(Arel.sql(sanitize_sql("#{Product.quoted_table_name}.#{parts[2]} #{parts[1] == 'ascend' ? 'ASC' : 'DESC'}"))) })- end- end-- add_simple_scopes simple_scopes-- add_search_scope :ascend_by_master_price do+ scope :ascend_by_updated_at, -> { order("#{Product.quoted_table_name}.updated_at ASC") }+ scope :descend_by_updated_at, -> { order("#{Product.quoted_table_name}.updated_at DESC") }+ scope :ascend_by_name, -> { order("#{Product.quoted_table_name}.name ASC") }+ scope :descend_by_name, -> { order("#{Product.quoted_table_name}.name DESC") }++ # Deprecated — master variant being removed in 6.0. Use ascend_by_price / descend_by_price instead.+ def self.ascend_by_master_price+ Spree::Deprecation.warn('ascend_by_master_price is deprecated and will be removed in Spree 6.0. Use ascend_by_price instead.')order(price_table_name => { amount: :asc })end- add_search_scope :descend_by_master_price do+ # Deprecated — master variant being removed in 6.0. Use ascend_by_price / descend_by_price instead.+ def self.descend_by_master_price+ Spree::Deprecation.warn('descend_by_master_price is deprecated and will be removed in Spree 6.0. Use descend_by_price instead.')order(price_table_name => { amount: :desc })end@@ -47,7 +26,7 @@ module Spree# Uses Arel::Nodes::As for select expressions so that:# - PG allows ORDER BY with DISTINCT (expressions must appear in SELECT list)# - Mobility's select_for_count can safely call .right on all select_values- add_search_scope :ascend_by_price do+ scope :ascend_by_price, -> {price_agg_sql = Price.non_zero.joins(:variant).select("#{Variant.table_name}.product_id AS product_id, MIN(#{Price.table_name}.amount) AS agg_price").group("#{Variant.table_name}.product_id")@@ -59,9 +38,9 @@ module Spreeselect("#{Product.table_name}.*").select(Arel::Nodes::As.new(price_expr, Arel.sql('min_price'))).order(price_expr.asc)- end+ }- add_search_scope :descend_by_price do+ scope :descend_by_price, -> {price_agg_sql = Price.non_zero.joins(:variant).select("#{Variant.table_name}.product_id AS product_id, MAX(#{Price.table_name}.amount) AS agg_price").group("#{Variant.table_name}.product_id")@@ -73,17 +52,21 @@ module Spreeselect("#{Product.table_name}.*").select(Arel::Nodes::As.new(price_expr, Arel.sql('max_price'))).order(price_expr.desc)- end+ }- add_search_scope :price_between do |low, high|+ scope :price_between, ->(low, high) {where(Price.table_name => { amount: low..high })- end+ }- add_search_scope :master_price_lte do |price|+ # Deprecated — master variant being removed in 6.0. Use price_lte / price_gte instead.+ def self.master_price_lte(price)+ Spree::Deprecation.warn('master_price_lte is deprecated and will be removed in Spree 6.0. Use price_lte instead.')where(Price.table_name => { amount: ..price })end- add_search_scope :master_price_gte do |price|+ # Deprecated — master variant being removed in 6.0. Use price_lte / price_gte instead.+ def self.master_price_gte(price)+ Spree::Deprecation.warn('master_price_gte is deprecated and will be removed in Spree 6.0. Use price_gte instead.')where(Price.table_name => { amount: price.. })end@@ -106,7 +89,6 @@ module Spree)}- # Can't use add_search_scope for this as it needs a default argument# Ransack calls with '1' to activate, '0' or nil to skip# In Ruby code: in_stock(true) for in-stock, in_stock(false) for out-of-stockdef self.in_stock(in_stock = true)@@ -117,14 +99,13 @@ module Spreeendend- add_search_scope :price_lte do |price|+ scope :price_lte, ->(price) {where(Price.table_name => { amount: ..price })- end+ }- add_search_scope :price_gte do |price|+ scope :price_gte, ->(price) {where(Price.table_name => { amount: price.. })- end- search_scopes << :in_stock+ }def self.out_of_stock(out_of_stock = true)if out_of_stock == '0' || !out_of_stock@@ -133,13 +114,12 @@ module Spreewhere.not(id: join_variants_and_stock_items.in_stock_or_backorderable_condition)endend- search_scopes << :out_of_stock- add_search_scope :backorderable do+ def self.backorderablejoin_variants_and_stock_items.where(StockItem.table_name => { backorderable: true })end- add_search_scope :in_stock_or_backorderable do+ def self.in_stock_or_backorderablejoin_variants_and_stock_items.in_stock_or_backorderable_conditionend@@ -152,34 +132,22 @@ module Spree# `:distinct` option as well:## Spree::Product.in_taxon(taxon).count(distinct: true)- #- # This is so that the count query is distinct'd:- #- # SELECT COUNT(DISTINCT "spree_products"."id") ...- #- # vs.- #- # SELECT COUNT(*) ...- add_search_scope :in_taxon do |taxon|+ scope :in_taxon, ->(taxon) {joins(:classifications).where("#{Classification.table_name}.taxon_id" => taxon.cached_self_and_descendants_ids).distinct- end+ }# Alias for in_taxon — public API name- add_search_scope :in_category do |category|- in_taxon(category)- end+ scope :in_category, ->(category) { in_taxon(category) }- # This scope selects products in all taxons AND all its descendants- # If you need products only within one taxon use- #- # Spree::Product.taxons_id_eq([x,y])- add_search_scope :in_taxons do |*taxons|+ # Deprecated — remove in 6.0. Use in_taxon instead.+ def self.in_taxons(*taxons)+ Spree::Deprecation.warn('in_taxons is deprecated and will be removed in Spree 6.0. Use in_taxon instead.')taxons = get_taxons(taxons)taxons.first ? prepare_taxon_conditions(taxons) : where(nil)end- add_search_scope :ascend_by_taxons_min_position do |taxon_ids|+ scope :ascend_by_taxons_min_position, ->(taxon_ids) {min_position_sql = "MIN(#{Classification.table_name}.position)"joins(:classifications).@@ -187,9 +155,11 @@ module Spreeselect("#{Product.table_name}.*", "#{min_position_sql} AS min_taxon_position").group("#{Product.table_name}.id").order(Arel.sql("#{min_position_sql} ASC"))- end+ }- add_search_scope :with_option do |option|+ # Deprecated — remove in 6.0. Not used internally.+ def self.with_option(option)+ Spree::Deprecation.warn('with_option is deprecated and will be removed in Spree 6.0.')if option.is_a?(OptionType)joins(:option_types).where(spree_option_types: { id: option.id })elsif option.is_a?(Integer)@@ -201,7 +171,7 @@ module Spreeendend- add_search_scope :with_option_value do |option, value|+ scope :with_option_value, ->(option, value) {option_type_id = case optionwhen OptionType then option.idwhen Integer then option@@ -210,89 +180,66 @@ module SpreeOptionType.where(id: option).or(OptionType.where(name: option))&.first&.idelseOptionType.where(name: option)&.first&.id- OptionType.where(name: option)&.first&.idendend- return Product.group("#{Spree::Product.table_name}.id").none if option_type_id.blank?+ next Product.group("#{Spree::Product.table_name}.id").none if option_type_id.blank?group("#{Spree::Product.table_name}.id").joins(variants: :option_values).where(Spree::OptionValue.table_name => { name: value, option_type_id: option_type_id })- end+ }# Filters products by option value IDs (prefix IDs like 'optval_xxx')# Accepts an array of option value IDs- add_search_scope :with_option_value_ids do |*ids|+ scope :with_option_value_ids, ->(*ids) {ids = ids.flatten.compact- return none if ids.empty?+ next none if ids.empty?# Handle prefixed IDs (optval_xxx) by decoding to actual IDsactual_ids = ids.map do |id|id.to_s.include?('_') ? OptionValue.decode_prefixed_id(id) : idend.compact- return none if actual_ids.empty?+ next none if actual_ids.empty?joins(variants: :option_values).where(Spree::OptionValue.table_name => { id: actual_ids })- end+ }- # Finds all products which have an option value with the name matching the one given- add_search_scope :with do |value|+ # Deprecated — remove in 6.0. Not used internally.+ def self.with(value)+ Spree::Deprecation.warn('Product.with is deprecated and will be removed in Spree 6.0.')includes(variants: :option_values).where("#{OptionValue.table_name}.name = ?", value)end- # Finds all products that have a name containing the given words.- add_search_scope :in_name do |words|+ # Deprecated — remove in 6.0. Use .search scope instead.+ def self.in_name(words)+ Spree::Deprecation.warn('in_name is deprecated and will be removed in Spree 6.0. Use .search instead.')like_any([:name], prepare_words(words))end- # Finds all products that have a name or meta_keywords containing the given words.- add_search_scope :in_name_or_keywords do |words|+ # Deprecated — remove in 6.0. Use .search scope instead.+ def self.in_name_or_keywords(words)+ Spree::Deprecation.warn('in_name_or_keywords is deprecated and will be removed in Spree 6.0. Use .search instead.')like_any([:name, :meta_keywords], prepare_words(words))end- # Finds all products that have a name, description, meta_description or meta_keywords containing the given keywords.- add_search_scope :in_name_or_description do |words|+ # Deprecated — remove in 6.0. Use .search scope instead.+ def self.in_name_or_description(words)+ Spree::Deprecation.warn('in_name_or_description is deprecated and will be removed in Spree 6.0. Use .search instead.')like_any([:name, :description, :meta_description, :meta_keywords], prepare_words(words))end- # Finds all products that have the ids matching the given collection of ids.- # Alternatively, you could use find(collection_of_ids), but that would raise an exception if one product couldn't be found- add_search_scope :with_ids do |*ids|+ # Deprecated — remove in 6.0. Use where(id: ids) directly.+ def self.with_ids(*ids)+ Spree::Deprecation.warn('with_ids is deprecated and will be removed in Spree 6.0. Use where(id: ids) instead.')where(id: ids)end- # Sorts products from most popular (popularity is extracted from how many- # times use has put product in cart, not completed orders)- #- # there is alternative faster and more elegant solution, it has small drawback though,- # it doesn stack with other scopes :/- #- # joins: "LEFT OUTER JOIN (SELECT line_items.variant_id as vid, COUNT(*) as cnt FROM line_items GROUP BY line_items.variant_id) AS popularity_count ON variants.id = vid",- # order: 'COALESCE(cnt, 0) DESC'- add_search_scope :descend_by_popularity do- joins(:master).- order(%Q{- COALESCE((- SELECT- COUNT(#{LineItem.quoted_table_name}.id)- FROM- #{LineItem.quoted_table_name}- JOIN- #{Variant.quoted_table_name} AS popular_variants- ON- popular_variants.id = #{LineItem.quoted_table_name}.variant_id- WHERE- popular_variants.product_id = #{Product.quoted_table_name}.id- ), 0) DESC- })- end-- add_search_scope :not_deleted do+ scope :not_deleted, -> {where("#{Product.quoted_table_name}.deleted_at IS NULL or #{Product.quoted_table_name}.deleted_at >= ?", Time.zone.now)- end+ }def self.not_discontinued(only_not_discontinued = true)if only_not_discontinued != '0' && only_not_discontinued@@ -301,7 +248,6 @@ module Spreeallendend- search_scopes << :not_discontinueddef self.with_currency(currency)joins(variants_including_master: :prices).@@ -309,9 +255,7 @@ module Spreewhere.not(Price.table_name => { amount: nil }).distinctend- search_scopes << :with_currency- # Can't use add_search_scope for this as it needs a default argumentdef self.available(available_on = nil, currency = nil)scope = not_discontinued.where(status: 'active')if available_on@@ -326,21 +270,22 @@ module Spreescopeend- search_scopes << :availabledef self.active(currency = nil)available(nil, currency)end- search_scopes << :active+ # Deprecated — remove in 6.0. Use active(currency).in_taxon(taxon) directly.def self.for_filters(currency, taxon: nil)+ Spree::Deprecation.warn('for_filters is deprecated and will be removed in Spree 6.0. Use active(currency).in_taxon(taxon) instead.')scope = active(currency)scope = scope.in_taxon(taxon) if taxon.present?scopeend- search_scopes << :for_filters+ # Deprecated — remove in 6.0. Not used internally.def self.for_user(user = nil)+ Spree::Deprecation.warn('for_user is deprecated and will be removed in Spree 6.0.')if user.try(:has_spree_role?, 'admin')with_deletedelse@@ -348,7 +293,9 @@ module Spreeendend- add_search_scope :taxons_name_eq do |name|+ # Deprecated — remove in 6.0. Not used internally.+ def self.taxons_name_eq(name)+ Spree::Deprecation.warn('taxons_name_eq is deprecated and will be removed in Spree 6.0.')group('spree_products.id').joins(:taxons).where(Taxon.arel_table[:name].eq(name))end@@ -357,7 +304,7 @@ module Spree## Uses Arel::Nodes::As so that ORDER BY expressions appear in SELECT# and work with DISTINCT (same pattern as the price sorting scopes).- add_search_scope :by_best_selling do |order_direction = :desc|+ scope :by_best_selling, ->(order_direction = :desc) {sp_table = StoreProduct.table_nameunits_expr = Arel.sql("COALESCE(#{sp_table}.units_sold_count, 0)")revenue_expr = Arel.sql("COALESCE(#{sp_table}.revenue, 0)")@@ -369,19 +316,32 @@ module Spreeselect(Arel::Nodes::As.new(revenue_expr, Arel.sql('best_selling_revenue'))).order(units_expr.send(order_dir)).order(revenue_expr.send(order_dir))- end+ }- # .search_by_name- if defined?(PgSearch)- include PgSearch::Model+ # Deprecated — remove in 6.0. Use by_best_selling instead.+ def self.descend_by_popularity+ Spree::Deprecation.warn('descend_by_popularity is deprecated and will be removed in Spree 6.0. Use by_best_selling instead.')+ joins(:master).+ order(%Q{+ COALESCE((+ SELECT+ COUNT(#{LineItem.quoted_table_name}.id)+ FROM+ #{LineItem.quoted_table_name}+ JOIN+ #{Variant.quoted_table_name} AS popular_variants+ ON+ popular_variants.id = #{LineItem.quoted_table_name}.variant_id+ WHERE+ popular_variants.product_id = #{Product.quoted_table_name}.id+ ), 0) DESC+ })+ end- pg_search_scope :search_by_name, against: { name: 'A', meta_title: 'B' }, using: { trigram: { threshold: 0.3, word_similarity: true } }- else- def self.search_by_name(query)- i18n { name.lower.matches("%#{query.downcase}%") }- end+ # .search_by_name — simple ILIKE on product name+ def self.search_by_name(query)+ i18n { name.lower.matches("%#{query.downcase}%") }end- search_scopes << :search_by_namedef self.price_table_namePrice.quoted_table_namediff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rbindex 8b4b648962..70c01dbbc1 100644--- a/spree/core/app/models/spree/product.rb+++ b/spree/core/app/models/spree/product.rb@@ -34,6 +34,7 @@ module Spreeinclude Spree::Metadatainclude Spree::Product::Webhooksinclude Spree::Product::Slugs+ include Spree::SearchIndexableif defined?(Spree::VendorConcern)include Spree::VendorConcernend@@ -58,12 +59,6 @@ module Spreeself::Translation.class_eval donormalizes :name, :meta_title, with: ->(value) { value&.to_s&.squish&.presence }-- if defined?(PgSearch)- include PgSearch::Model-- pg_search_scope :search_by_name, against: { name: 'A', meta_title: 'B' }, using: { trigram: { threshold: 0.3, word_similarity: true } }- endend# we need to have this callback before any dependent: :destroy associations@@ -169,32 +164,15 @@ module Spreewhere("#{Spree::Price.table_name}.compare_at_amount > #{Spree::Price.table_name}.amount")}- if defined?(PgSearch)- scope :multi_search, lambda { |query, include_options = false|- return none if query.blank?+ scope :search, ->(query) {+ next none if query.blank?- product_ids = if Spree.use_translations?- Spree::Product::Translation.search_by_name(query).pluck(:spree_product_id)- else- Spree::Product.search_by_name(query).ids- end+ product_ids = Spree::Variant.search_by_product_name_or_sku(query).pluck(:product_id)+ where(id: product_ids.uniq.compact)+ }- variant_product_ids = if include_options.present?- Spree::Variant.search_by_sku_or_options(query).pluck(:product_id)- else- Spree::Variant.search_by_sku(query).pluck(:product_id)- end-- where(id: (product_ids + variant_product_ids).uniq.compact)- }- else- scope :multi_search, lambda { |query|- return none if query.blank?-- product_ids = Spree::Variant.search_by_product_name_or_sku(query).pluck(:product_id)- where(id: product_ids.uniq.compact)- }- end+ # Backward compatibility alias — remove in Spree 6.0+ scope :multi_search, ->(*args) { search(*args) }scope :archivable, -> { where(status: %w[active draft]) }scope :by_source, ->(source) { send(source) }@@ -224,7 +202,7 @@ module Spreeshipping_category classifications option_types]self.whitelisted_ransackable_scopes = %w[not_discontinued search_by_name in_taxon price_betweenprice_lte price_gte- multi_search in_stock out_of_stock with_option_value_ids+ search multi_search in_stock out_of_stock with_option_value_idsascend_by_price descend_by_price]diff --git a/spree/core/app/models/spree/taxon.rb b/spree/core/app/models/spree/taxon.rbindex 8776fd9ecf..287f47b98f 100644--- a/spree/core/app/models/spree/taxon.rb+++ b/spree/core/app/models/spree/taxon.rb@@ -103,13 +103,8 @@ module Spree## Search#- if defined?(PgSearch)- include PgSearch::Model- pg_search_scope :search_by_name, against: :name, using: { tsearch: { any_word: true, prefix: true } }- else- def self.search_by_name(query)- i18n { name.lower.matches("%#{query.downcase}%") }- end+ def self.search_by_name(query)+ i18n { name.lower.matches("%#{query.downcase}%") }endscope :with_matching_name, lambda { |name_to_match|diff --git a/spree/core/spec/models/spree/product/scopes_spec.rb b/spree/core/spec/models/spree/product/scopes_spec.rbindex cc590bd12a..479e2146ce 100644--- a/spree/core/spec/models/spree/product/scopes_spec.rb+++ b/spree/core/spec/models/spree/product/scopes_spec.rb@@ -95,35 +95,15 @@ describe 'Product scopes', type: :model doendend- context '#add_simple_scopes' do- let(:simple_scopes) { [:ascend_by_updated_at, :descend_by_name] }-- before do- Spree::Product.add_simple_scopes(simple_scopes)+ context 'sorting scopes' do+ context 'ascend_by_updated_at' do+ it { expect(Spree::Product.ascend_by_updated_at.to_sql).to include('updated_at ASC') }+ it { expect(Spree::Product.limit(2).ascend_by_updated_at.to_sql).to include('updated_at ASC') }end- context 'define scope' do- context 'ascend_by_updated_at' do- context 'on class' do- it { expect(Spree::Product.ascend_by_updated_at.to_sql).to eq Spree::Product.order(Arel.sql("#{Spree::Product.quoted_table_name}.updated_at ASC")).to_sql }- end-- context 'on ActiveRecord::Relation' do- it { expect(Spree::Product.limit(2).ascend_by_updated_at.to_sql).to eq Spree::Product.limit(2).order(Arel.sql("#{Spree::Product.quoted_table_name}.updated_at ASC")).to_sql }- it { expect(Spree::Product.limit(2).ascend_by_updated_at.to_sql).to eq Spree::Product.ascend_by_updated_at.limit(2).to_sql }- end- end-- context 'descend_by_name' do- context 'on class' do- it { expect(Spree::Product.descend_by_name.to_sql).to eq Spree::Product.order(Arel.sql("#{Spree::Product.quoted_table_name}.name DESC")).to_sql }- end-- context 'on ActiveRecord::Relation' do- it { expect(Spree::Product.limit(2).descend_by_name.to_sql).to eq Spree::Product.limit(2).order(Arel.sql("#{Spree::Product.quoted_table_name}.name DESC")).to_sql }- it { expect(Spree::Product.limit(2).descend_by_name.to_sql).to eq Spree::Product.descend_by_name.limit(2).to_sql }- end- end+ context 'descend_by_name' do+ it { expect(Spree::Product.descend_by_name.to_sql).to include('name DESC') }+ it { expect(Spree::Product.limit(2).descend_by_name.to_sql).to include('name DESC') }endend