Skip to content
This repository
Browse code

Quote find_in_batches ORDER BY clause [#6620 state:resolved]

  • Loading branch information...
commit 3ed8a331973b80c49d56b65d726b1f8be52e5261 1 parent 7f098a6
Andrew White authored March 27, 2011
6  activerecord/lib/active_record/attribute_methods/primary_key.rb
@@ -16,6 +16,11 @@ def primary_key
16 16
           reset_primary_key
17 17
         end
18 18
 
  19
+        # Returns a quoted version of the primary key name, used to construct SQL statements.
  20
+        def quoted_primary_key
  21
+          @quoted_primary_key ||= connection.quote_column_name(primary_key)
  22
+        end
  23
+
19 24
         def reset_primary_key #:nodoc:
20 25
           key = get_primary_key(base_class.name)
21 26
           set_primary_key(key)
@@ -41,6 +46,7 @@ def get_primary_key(base_name) #:nodoc:
41 46
         #     set_primary_key "sysid"
42 47
         #   end
43 48
         def set_primary_key(value = nil, &block)
  49
+          @quoted_primary_key = nil
44 50
           define_attr_method :primary_key, value, &block
45 51
         end
46 52
         alias :primary_key= :set_primary_key
2  activerecord/lib/active_record/relation/batches.rb
@@ -83,7 +83,7 @@ def find_in_batches(options = {})
83 83
     private
84 84
 
85 85
     def batch_order
86  
-      "#{@klass.table_name}.#{@klass.primary_key} ASC"
  86
+      "#{@klass.quoted_table_name}.#{@klass.quoted_primary_key} ASC"
87 87
     end
88 88
   end
89 89
 end
10  activerecord/test/cases/batches_test.rb
@@ -82,4 +82,14 @@ def test_find_in_batches_shouldnt_excute_query_unless_needed
82 82
       Post.find_in_batches(:batch_size => post_count + 1) {|batch| assert_kind_of Array, batch }
83 83
     end
84 84
   end
  85
+
  86
+  def test_find_in_batches_should_quote_batch_order
  87
+    c = Post.connection
  88
+    assert_sql(/ORDER BY #{c.quote_table_name('posts')}.#{c.quote_column_name('id')}/) do
  89
+      Post.find_in_batches(:batch_size => 1) do |batch|
  90
+        assert_kind_of Array, batch
  91
+        assert_kind_of Post, batch.first
  92
+      end
  93
+    end
  94
+  end
85 95
 end
9  activerecord/test/cases/primary_keys_test.rb
@@ -136,4 +136,13 @@ def test_primary_key_returns_nil_if_it_does_not_exist
136 136
       assert_nil ActiveRecord::Base.connection.primary_key('developers_projects')
137 137
     end
138 138
   end
  139
+
  140
+  def test_quoted_primary_key_after_set_primary_key
  141
+    k = Class.new( ActiveRecord::Base )
  142
+    assert_equal k.connection.quote_column_name("id"), k.quoted_primary_key
  143
+    k.primary_key = "foo"
  144
+    assert_equal k.connection.quote_column_name("foo"), k.quoted_primary_key
  145
+    k.set_primary_key "bar"
  146
+    assert_equal k.connection.quote_column_name("bar"), k.quoted_primary_key
  147
+  end
139 148
 end

0 notes on commit 3ed8a33

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