提交 951e18ab 编写于 作者: A Aaron Patterson

introduce a body proxy to ensure that query cache is enabled during streaming

上级 4300855e
......@@ -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
......
......@@ -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
......@@ -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
......@@ -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
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册