edge badge

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.

Namespace
Methods
C
E
N
P
Q
Attributes
[R] bind_map
[R] query_builder
Class Public methods
create(connection, block = Proc.new)
# File activerecord/lib/active_record/statement_cache.rb, line 79
def self.create(connection, block = Proc.new)
  relation      = block.call Params.new
  bind_map      = BindMap.new relation.bind_values
  query_builder = connection.cacheable_query relation.arel
  new query_builder, bind_map
end
new(query_builder, bind_map)
# File activerecord/lib/active_record/statement_cache.rb, line 86
def initialize(query_builder, bind_map)
  @query_builder = query_builder
  @bind_map      = bind_map
end
partial_query(visitor, ast, collector)
# File activerecord/lib/active_record/statement_cache.rb, line 49
def self.partial_query(visitor, ast, collector)
  collected = visitor.accept(ast, collector).value
  PartialQuery.new collected
end
query(visitor, ast)
# File activerecord/lib/active_record/statement_cache.rb, line 45
def self.query(visitor, ast)
  Query.new visitor.accept(ast, Arel::Collectors::SQLString.new).value
end
Instance Public methods
call(params, klass, connection)
Alias for: execute
execute(params, klass, connection)
Also aliased as: call
# File activerecord/lib/active_record/statement_cache.rb, line 91
def execute(params, klass, connection)
  bind_values = bind_map.bind params

  sql = query_builder.sql_for bind_values, connection

  klass.find_by_sql sql, bind_values
end