blob: 90d4748d840252ee378161aba18fd67ed3bf684d (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
module ActiveRecord
# Statement cache is used to cache a single statement in order to avoid creating the AST again.
# Initializing the cache is done by passing the statement in the initialization block:
#
# cache = ActiveRecord::StatementCache.new do
# Book.where(name: "my book").limit(100)
# end
#
# The cached statement is executed by using the +execute+ method:
#
# cache.execute
#
# 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(block = Proc.new)
@mutex = Mutex.new
@relation = nil
@block = block
end
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
|