From 1974d7b7612b26a6901d2c0d414dc94ced9416c6 Mon Sep 17 00:00:00 2001 From: Paul Sturgess Date: Wed, 1 May 2024 16:58:11 +0100 Subject: [PATCH] perf: improve query performance for Metric.latest (#18) Currently it pulls all records from the database but only uses the most recent amount value. This is inefficient, particularly if the database is large. Now it only retrieves the amount from the most recent record and ignores all the old ones. --- Gemfile | 4 +++- README.md | 7 +++++++ lib/metricks/models/metric.rb | 2 +- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/Gemfile b/Gemfile index af83767..9312a50 100644 --- a/Gemfile +++ b/Gemfile @@ -1,7 +1,9 @@ source 'https://rubygems.org' gemspec + +# Other dependencies are defined in the Appraisals file group :development do gem 'appraisal', '~> 2.4' gem 'rspec' - gem 'sqlite3' + gem 'sqlite3', '~> 1.4' end diff --git a/README.md b/README.md index 6aac194..dc25b97 100644 --- a/README.md +++ b/README.md @@ -227,3 +227,10 @@ compared_point.sum.percentage_change # => The % change between 2019-01 and 2018 # In addition to `sum`, there is also `count` and `last` as you expect from any # other point. ``` + +## Run the tests + +To run the tests you can use the following commands from the [appraisal gem](https://github.com/thoughtbot/appraisal): + +- `bundle exec appraisal install` +- `bundle exec appraisal rspec` diff --git a/lib/metricks/models/metric.rb b/lib/metricks/models/metric.rb index 8f4da39..07c4bc8 100644 --- a/lib/metricks/models/metric.rb +++ b/lib/metricks/models/metric.rb @@ -67,7 +67,7 @@ def record(type, **options) # @return [Float] def latest(type, **options) scope = self.last(type, **options) - value = scope.pluck(:amount)&.first || 0.0 + value = scope.select(:amount).first&.amount || 0.0 type.transform_amount(value, options[:associations]) end