Skip to content

Commit

Permalink
perf: improve query performance for Metric.latest (#18)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
paulsturgess authored May 1, 2024
1 parent 62f2d56 commit 1974d7b
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 2 deletions.
4 changes: 3 additions & 1 deletion Gemfile
Original file line number Diff line number Diff line change
@@ -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
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
2 changes: 1 addition & 1 deletion lib/metricks/models/metric.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit 1974d7b

Please sign in to comment.