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

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

上级 4300855e
...@@ -29,6 +29,14 @@ def cache ...@@ -29,6 +29,14 @@ def cache
@query_cache_enabled = old @query_cache_enabled = old
end 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. # Disable the query cache within the block.
def uncached def uncached
old, @query_cache_enabled = @query_cache_enabled, false old, @query_cache_enabled = @query_cache_enabled, false
......
...@@ -27,10 +27,31 @@ def initialize(app) ...@@ -27,10 +27,31 @@ def initialize(app)
@app = app @app = app
end end
def call(env) class BodyProxy # :nodoc:
ActiveRecord::Base.cache do def initialize(original_cache_value, target)
@app.call(env) @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
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
end end
...@@ -10,6 +10,7 @@ class QueryCacheTest < ActiveRecord::TestCase ...@@ -10,6 +10,7 @@ class QueryCacheTest < ActiveRecord::TestCase
def setup def setup
Task.connection.clear_query_cache Task.connection.clear_query_cache
ActiveRecord::Base.connection.disable_query_cache!
end end
def test_middleware_delegates def test_middleware_delegates
...@@ -39,6 +40,31 @@ def test_cache_enabled_during_call ...@@ -39,6 +40,31 @@ def test_cache_enabled_during_call
mw.call({}) mw.call({})
end 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 def test_find_queries
assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) { Task.find(1); Task.find(1) } assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) { Task.find(1); Task.find(1) }
end end
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册