From 20fd254a5bdf35347d231dcc44d7b94cc5c00c1e Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 18 Feb 2014 11:45:42 -0800 Subject: cache queries in the Model.find(id) path --- .../connection_adapters/abstract_adapter.rb | 2 ++ activerecord/lib/active_record/core.rb | 26 ++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index 2ba028e658..ea81cf1736 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -90,6 +90,8 @@ module ActiveRecord end end + attr_reader :prepared_statements + def initialize(connection, logger = nil, pool = nil) #:nodoc: super() diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb index adc9383bdc..941ff6bffd 100644 --- a/activerecord/lib/active_record/core.rb +++ b/activerecord/lib/active_record/core.rb @@ -117,6 +117,32 @@ module ActiveRecord super end + def find(*ids) + # We don't have cache keys for this stuff yet + return super unless ids.length == 1 + return super if block_given? || + primary_key.nil? || + default_scopes.any? || + columns_hash.include?(inheritance_column) || + !connection.prepared_statements || + ids.first.kind_of?(Array) + + id = ids.first + id = id.id if ActiveRecord::Base === id + key = primary_key + + s = find_by_statement_cache[key] || find_by_statement_cache.synchronize { + find_by_statement_cache[key] ||= StatementCache.new { |params| + where(key => params[key]).limit(1) + } + } + record = s.execute(key => id).first + unless record + raise RecordNotFound, "Couldn't find #{name} with '#{primary_key}'=#{id}" + end + record + end + def find_by(*args) return super if current_scope || args.length > 1 || reflect_on_all_aggregations.any? -- cgit v1.2.3