Skip to content

Commit

Permalink
introduce a body proxy to ensure that query cache is enabled during s…
Browse files Browse the repository at this point in the history
…treaming
  • Loading branch information
tenderlove committed May 2, 2011
1 parent 4300855 commit 951e18a
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,14 @@ def cache
@query_cache_enabled = old
end

def enable_query_cache!
@query_cache_enabled = true
end

def disable_query_cache!
@query_cache_enabled = false
end

# Disable the query cache within the block.
def uncached
old, @query_cache_enabled = @query_cache_enabled, false
Expand Down
27 changes: 24 additions & 3 deletions activerecord/lib/active_record/query_cache.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,31 @@ def initialize(app)
@app = app
end

def call(env)
ActiveRecord::Base.cache do
@app.call(env)
class BodyProxy # :nodoc:
def initialize(original_cache_value, target)
@original_cache_value = original_cache_value
@target = target
end

def each(&block)
@target.each(&block)
end

def close
@target.close if @target.respond_to?(:close)
ensure
unless @original_cache_value
ActiveRecord::Base.connection.disable_query_cache!
end
end
end

def call(env)
old = ActiveRecord::Base.connection.query_cache_enabled
ActiveRecord::Base.connection.enable_query_cache!

status, headers, body = @app.call(env)
[status, headers, BodyProxy.new(old, body)]
end
end
end
26 changes: 26 additions & 0 deletions activerecord/test/cases/query_cache_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ class QueryCacheTest < ActiveRecord::TestCase

def setup
Task.connection.clear_query_cache
ActiveRecord::Base.connection.disable_query_cache!
end

def test_middleware_delegates
Expand Down Expand Up @@ -39,6 +40,31 @@ def test_cache_enabled_during_call
mw.call({})
end

def test_cache_on_during_body_write
streaming = Class.new do
def each
yield ActiveRecord::Base.connection.query_cache_enabled
end
end

mw = ActiveRecord::QueryCache.new lambda { |env|
[200, {}, streaming.new]
}
body = mw.call({}).last
body.each { |x| assert x, 'cache should be on' }
body.close
assert !ActiveRecord::Base.connection.query_cache_enabled, 'cache disabled'
end

def test_cache_off_after_close
mw = ActiveRecord::QueryCache.new lambda { |env| }
body = mw.call({}).last

assert ActiveRecord::Base.connection.query_cache_enabled, 'cache enabled'
body.close
assert !ActiveRecord::Base.connection.query_cache_enabled, 'cache disabled'
end

def test_find_queries
assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) { Task.find(1); Task.find(1) }
end
Expand Down

0 comments on commit 951e18a

Please sign in to comment.