diff --git a/CHANGELOG.md b/CHANGELOG.md index e7d4dd0d9..24ec3670f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ ### Changes + * [#761](https://github.com/toptal/chewy/pull/761): Avoid fetching scope data to check if it is blank ([@dalthon][]) + ### Bugs Fixed ## 6.0.0 (2021-02-11) diff --git a/lib/chewy/type/import.rb b/lib/chewy/type/import.rb index 310c8d8da..92ed1cecb 100644 --- a/lib/chewy/type/import.rb +++ b/lib/chewy/type/import.rb @@ -127,7 +127,8 @@ def compose(object, crutches = nil, fields: []) private def import_routine(*args) - return if args.first.blank? && !args.first.nil? + return if !args.first.nil? && empty_objects_or_scope?(args.first) + routine = Routine.new(self, **args.extract_options!) routine.create_indexes! @@ -138,6 +139,14 @@ def import_routine(*args) end end + def empty_objects_or_scope?(objects_or_scope) + if objects_or_scope.respond_to?(:empty?) + objects_or_scope.empty? + else + objects_or_scope.blank? + end + end + def import_linear(objects, routine) ActiveSupport::Notifications.instrument 'import_objects.chewy', type: self do |payload| adapter.import(*objects, routine.options) do |action_objects| diff --git a/spec/chewy/type/import_spec.rb b/spec/chewy/type/import_spec.rb index 30fe14ba9..833e671a8 100644 --- a/spec/chewy/type/import_spec.rb +++ b/spec/chewy/type/import_spec.rb @@ -158,6 +158,15 @@ def subscribe_notification specify do expect { import City.where(id: dummy_cities.first.id) }.to update_index(CitiesIndex::City).and_reindex(dummy_cities.first).only end + + specify do + allow(CitiesIndex::City).to receive(:import_linear).and_return(double(present?: false)) + allow(CitiesIndex::City).to receive(:import_parallel).and_return(double(present?: false)) + + expects_no_query(except: /SELECT\s+1\s+AS\s+one\s+FROM/) do + import City.where(id: dummy_cities.first.id) + end + end end end diff --git a/spec/support/active_record.rb b/spec/support/active_record.rb index 8a79b91c1..5bc56eb97 100644 --- a/spec/support/active_record.rb +++ b/spec/support/active_record.rb @@ -39,14 +39,15 @@ def expects_db_queries(&block) raise 'Expected some db queries, but none were made' unless have_queries end - def expects_no_query(&block) + def expects_no_query(except: nil, &block) queries = [] ActiveSupport::Notifications.subscribed( ->(*args) { queries << args[4][:sql] }, 'sql.active_record', &block ) - raise "Expected no DB queries, but the following ones were made: #{queries.join(', ')}" if queries.present? + ofending_queries = except ? queries.find_all { |query| !query.match(except) } : queries + raise "Expected no DB queries, but the following ones were made: #{ofending_queries.join(', ')}" if ofending_queries.present? end def stub_model(name, superclass = nil, &block)