From cb95c1b14fbfd1e882ed0ef8387118cd514dcdd7 Mon Sep 17 00:00:00 2001 From: Svyatoslav Kryukov Date: Thu, 25 Mar 2021 05:42:34 +0300 Subject: [PATCH] ActiveRecord: Optimize cache_key computation (#41741) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Optimize cache_key computation * After review [Svyatoslav Kryukov + Rafael Mendonça França] --- activerecord/lib/active_record/relation.rb | 3 ++- activerecord/test/cases/collection_cache_key_test.rb | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index e232aa814c..04d05e847e 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -357,7 +357,7 @@ module ActiveRecord def compute_cache_version(timestamp_column) # :nodoc: timestamp_column = timestamp_column.to_s - if loaded? || distinct_value + if loaded? size = records.size if size > 0 timestamp = records.map { |record| record.read_attribute(timestamp_column) }.max @@ -370,6 +370,7 @@ module ActiveRecord if collection.has_limit_or_offset? query = collection.select("#{column} AS collection_cache_key_timestamp") + query._select!(table[Arel.star]) if distinct_value && collection.select_values.empty? subquery_alias = "subquery_for_cache_key" subquery_column = "#{subquery_alias}.collection_cache_key_timestamp" arel = query.build_subquery(subquery_alias, select_values % subquery_column) diff --git a/activerecord/test/cases/collection_cache_key_test.rb b/activerecord/test/cases/collection_cache_key_test.rb index d8955aaa7c..df10ed972e 100644 --- a/activerecord/test/cases/collection_cache_key_test.rb +++ b/activerecord/test/cases/collection_cache_key_test.rb @@ -171,6 +171,7 @@ module ActiveRecord developers = Developer.distinct.order(:salary).limit(5) assert_match(/\Adevelopers\/query-(\h+)-(\d+)-(\d+)\z/, developers.cache_key) + assert_not_predicate developers, :loaded? end test "cache_key with a relation having custom select and order" do