diff options
Diffstat (limited to 'activerecord/lib/active_record')
-rw-r--r-- | activerecord/lib/active_record/relation/query_methods.rb | 2 | ||||
-rw-r--r-- | activerecord/lib/active_record/statement_cache.rb | 57 |
2 files changed, 49 insertions, 10 deletions
diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index ffcdcd1169..226f1b8176 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -948,7 +948,7 @@ module ActiveRecord def create_binds(opts, idx) bindable, non_binds = opts.partition do |column, value| case value - when String, Integer + when String, Integer, ActiveRecord::StatementCache::Substitute @klass.columns_hash.include? column.to_s else false diff --git a/activerecord/lib/active_record/statement_cache.rb b/activerecord/lib/active_record/statement_cache.rb index 90d4748d84..8372d54c15 100644 --- a/activerecord/lib/active_record/statement_cache.rb +++ b/activerecord/lib/active_record/statement_cache.rb @@ -14,25 +14,64 @@ 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 + Substitute = Struct.new :name + + class Params + def [](name); Substitute.new name; end + end + + class BindMap + def initialize(bind_values) + @value_map = {} + @bind_values = bind_values + + bind_values.each_with_index do |(column, value), i| + if Substitute === value + @value_map[value.name] = i + end + end + end + + def bind(values) + bvs = @bind_values.map { |pair| pair.dup } + values.each { |k,v| bvs[@value_map[k]][1] = v } + bvs + end + end + def initialize(block = Proc.new) @mutex = Mutex.new @relation = nil + @sql = nil + @binds = nil @block = block + @params = Params.new end - def execute(*vals) - rel = relation vals - @mutex.synchronize do - rel.set_binds vals - rel.to_a - end + def execute(params) + rel = relation @params + + arel = rel.arel + klass = rel.klass + bv = binds rel + + klass.find_by_sql sql(klass, arel, bv), bv.bind(params) end + alias :call :execute private - def relation(values) - @relation || @mutex.synchronize { - @block.call(*values) + def binds(rel) + @binds || @mutex.synchronize { @binds ||= BindMap.new rel.bind_values } + end + + def sql(klass, arel, bv) + @sql || @mutex.synchronize { + @sql ||= klass.connection.to_sql arel, bv } end + + def relation(values) + @relation || @mutex.synchronize { @relation ||= @block.call(values) } + end end end |