aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--activerecord/lib/active_record/statement_cache.rb22
-rw-r--r--activerecord/test/cases/statement_cache_test.rb26
2 files changed, 26 insertions, 22 deletions
diff --git a/activerecord/lib/active_record/statement_cache.rb b/activerecord/lib/active_record/statement_cache.rb
index dd4ee0c4a0..90d4748d84 100644
--- a/activerecord/lib/active_record/statement_cache.rb
+++ b/activerecord/lib/active_record/statement_cache.rb
@@ -14,13 +14,25 @@ module ActiveRecord
# The relation returned by the block is cached, and for each +execute+ call the cached relation gets duped.
# Database is queried when +to_a+ is called on the relation.
class StatementCache
- def initialize
- @relation = yield
- raise ArgumentError.new("Statement cannot be nil") if @relation.nil?
+ def initialize(block = Proc.new)
+ @mutex = Mutex.new
+ @relation = nil
+ @block = block
end
- def execute
- @relation.dup.to_a
+ def execute(*vals)
+ rel = relation vals
+ @mutex.synchronize do
+ rel.set_binds vals
+ rel.to_a
+ end
+ end
+
+ private
+ def relation(values)
+ @relation || @mutex.synchronize {
+ @block.call(*values)
+ }
end
end
end
diff --git a/activerecord/test/cases/statement_cache_test.rb b/activerecord/test/cases/statement_cache_test.rb
index ae34b174db..3c8f34c851 100644
--- a/activerecord/test/cases/statement_cache_test.rb
+++ b/activerecord/test/cases/statement_cache_test.rb
@@ -15,13 +15,13 @@ module ActiveRecord
Book.create(name: "my book")
Book.create(name: "my other book")
- cache = StatementCache.new do
- Book.where(:name => "my book")
+ cache = StatementCache.new do |name|
+ Book.where(:name => name)
end
- b = cache.execute name: "my book"
+ b = cache.execute "my book"
assert_equal "my book", b[0].name
- b = cache.execute name: "my other book"
+ b = cache.execute "my other book"
assert_equal "my other book", b[0].name
end
@@ -31,13 +31,13 @@ module ActiveRecord
Book.create(name: "my book")
Book.create(name: "my other book")
- cache = StatementCache.new do
- Book.where(id: "1")
+ cache = StatementCache.new do |id|
+ Book.where(id: id)
end
- b = cache.execute id: "1"
+ b = cache.execute "1"
assert_equal "my book", b[0].name
- b = cache.execute id: "2"
+ b = cache.execute "2"
assert_equal "my other book", b[0].name
end
@@ -64,14 +64,6 @@ module ActiveRecord
assert_equal "my book", books[0].name
end
- def test_statement_cache_with_nil_statement_raises_error
- assert_raise(ArgumentError) do
- ActiveRecord::StatementCache.new do
- nil
- end
- end
- end
-
def test_statement_cache_with_complex_statement
cache = ActiveRecord::StatementCache.new do
Liquid.joins(:molecules => :electrons).where('molecules.name' => 'dioxane', 'electrons.name' => 'lepton')
@@ -104,4 +96,4 @@ module ActiveRecord
assert first_books != additional_books
end
end
-end \ No newline at end of file
+end