Skip to content
This repository
Browse code

Ensure ActiveRecord::Base.find_in_batches fires doesnt fire an extra …

…query unless needed
  • Loading branch information...
commit 106976df0911e423042ec4abc165fd561766a047 1 parent f23adf0
Pratik authored March 11, 2009
5  activerecord/lib/active_record/batches.rb
@@ -49,12 +49,15 @@ def find_in_batches(options = {})
49 49
         raise "You can't specify a limit, it's forced to be the batch_size"  if options[:limit]
50 50
 
51 51
         start = options.delete(:start).to_i
  52
+        batch_size = options.delete(:batch_size) || 1000
52 53
 
53  
-        with_scope(:find => options.merge(:order => batch_order, :limit => options.delete(:batch_size) || 1000)) do
  54
+        with_scope(:find => options.merge(:order => batch_order, :limit => batch_size)) do
54 55
           records = find(:all, :conditions => [ "#{table_name}.#{primary_key} >= ?", start ])
55 56
 
56 57
           while records.any?
57 58
             yield records
  59
+
  60
+            break if records.size < batch_size
58 61
             records = find(:all, :conditions => [ "#{table_name}.#{primary_key} > ?", records.last.id ])
59 62
           end
60 63
         end
12  activerecord/test/cases/batches_test.rb
@@ -46,4 +46,16 @@ def test_find_in_batches_should_start_from_the_start_option
46 46
       end
47 47
     end
48 48
   end
  49
+
  50
+  def test_find_in_batches_shouldnt_excute_query_unless_needed
  51
+    post_count = Post.count
  52
+
  53
+    assert_queries(2) do
  54
+      Post.find_in_batches(:batch_size => post_count) {|batch| assert_kind_of Array, batch }
  55
+    end
  56
+
  57
+    assert_queries(1) do
  58
+      Post.find_in_batches(:batch_size => post_count + 1) {|batch| assert_kind_of Array, batch }
  59
+    end
  60
+  end
49 61
 end
2  activerecord/test/cases/named_scope_test.rb
@@ -324,7 +324,7 @@ def test_named_scopes_batch_finders
324 324
       Topic.approved.find_each(:batch_size => 1) {|t| assert t.approved? }
325 325
     end
326 326
 
327  
-    assert_queries(3) do
  327
+    assert_queries(2) do
328 328
       Topic.approved.find_in_batches(:batch_size => 2) do |group|
329 329
         group.each {|t| assert t.approved? }
330 330
       end

0 notes on commit 106976d

Please sign in to comment.
Something went wrong with that request. Please try again.