Rails N+1 queries auto-detection with zero false positives / false negatives
Rails N+1 queries auto-detection with zero false positives / false negatives
Prosopite is able to auto-detect Rails N+1 queries with zero false positives / false negatives.
…The need for prosopite emerged after dealing with various false positives / negatives using the bullet gem.
Prosopite can auto-detect the following extra cases of N+1 queries:
FactoryBot.create_list(:leg, 10)
Leg.last(10).each do |l|
l.chair
endLeg.last(4).each do |l|
Chair.find(l.chair_id)
endChair.last(20).each do |c|
c.legs.first
c.legs.last
c.legs.pluck(:id)
endChair.last(20).map{ |c| c.becomes(ArmChair) }.each do |ac|
ac.legs.map(&:id)
endclass Leg::Design
include Mongoid::Document
...
field :cid, as: :chair_id, type: Integer
...
def chair
@chair ||= Chair.where(id: chair_id).first!
end
end
Leg::Design.last(20) do |l|
l.chair
endCreating a new gem makes more sense since bullet's core mechanism is completely different from prosopite's.
Prosopite monitors all SQL queries using the Active Support instrumentation and looks for the following pattern which is present in all N+1 query cases:
More than one queries have the same call stack and the same query fingerprint.
Add this line to your application's Gemfile:
gem 'prosopite'If you're not using MySQL/MariaDB, you should also add:
gem 'pg_query'And then execute:
$ bundle installOr install it yourself as:
$ gem install prosopiteThe preferred type of notifications can be configured with:
Prosopite.min_n_queries: Minimum number of N queries to report per N+1 case. Defaults to 2.Prosopite.raise = true: Raise warnings as exceptions. Defaults to false.Prosopite.start_raise: Raises warnings as exceptions from when this is called. Overrides Proposite.raise.Propsoite.stop_raise: Disables raising warnings as exceptions if previously enabled with Proposite.start_raise.Prosopite.local_raise?: Returns true if Prosopite.start_raise has been called previously.Prosopite.rails_logger = true: Send warnings to the Rails log. Defaults to false.Prosopite.prosopite_logger = true: Send warnings to log/prosopite.log. Defaults to false.Prosopite.stderr_logger = true: Send warnings to STDERR. Defaults to false.Prosopite.backtrace_cleaner = my_custom_backtrace_cleaner: use a different ActiveSupport::BacktraceCleaner. Defaults to Rails.backtrace_cleaner.Prosopite.custom_logger = my_custom_logger: Set a custom logger. See the following section for the details. Defaults to false.Prosopite.enabled = true: Enables or disables the gem. Defaults to true.Prosopite auto-detection can be enabled on all controllers:
class ApplicationController < ActionController::Base
unless Rails.env.production?
around_action :n_plus_one_detection
def n_plus_one_detection
Prosopite.scan
yield
ensure
Prosopite.finish
end
end
endAnd the preferred notification channel should be configured:
# config/environments/development.rb
config.after_initialize do
Prosopite.rails_logger = true
end## Test Environment Usage
Tests with N+1 queries can be configured to fail with:
```ruby
# config/environments/test.rb
config.after_initialize do
Prosopite.rails_logger = true
Prosopite.raise = true
endAnd each test can be scanned with:
# spec/spec_helper.rb
config.before(:each) do
Prosopite.scan
end
config.after(:each) do
Prosopite.finish
endWARNING: scan/finish should run before/after each test and NOT before/after the whole suite.
Instead of using an around_action hook in a Rails Controller, you can also use the rack middleware instead
implementing auto detect for all controllers.
Add the following line into your config/initializers/prosopite.rb file.
unless Rails.env.production?
require 'prosopite/middleware/rack'
Rails.configuration.middleware.use(Prosopite::Middleware::Rack)
endWe also provide a middleware for sidekiq 6.5.0+ so that you can auto detect n+1 queries that may occur in a sidekiq job.
You just need to add the following to your sidekiq initializer.
Sidekiq.configure_server do |config|
unless Rails.env.production?
config.server_middleware do |chain|
require 'prosopite/middleware/sidekiq'
chain.add(Prosopite::Middleware::Sidekiq)
end
end
endFor applications running sidekiq < 6.5.0 but want to add the snippet, you can guard the snippet with something like this and remove it once you upgrade sidekiq:
if Sidekiq::VERSION >= '6.5.0' && (Rails.env.development? || Rails.env.test?)
.....
endIgnore notifications for call stacks containing one or more substrings / regex:
Prosopite.allow_stack_paths = ['substring_in_call_stack', /regex/]Ignore notifications matching a specific SQL query:
Prosopite.ignore_queries = [/regex_match/, "SELECT * from EXACT_STRING_MATCH"]All you have to do is to wrap the code with:
Prosopite.scan
<code to scan>
Prosopite.finishIn block form the Prosopite.finish is called automatically for you at the end of the block:
Prosopite.scan do
<code to scan>
endThe result of the code block is also returned by Prosopite.scan, so you can wrap calls as follows:
my_object = Prosopite.scan do
MyObjectFactory.create(params)
endScans can be paused:
Prosopite.scan
# <code to scan>
Prosopite.pause
# <code that has n+1s>
Prosopite.resume
# <code to scan>
Prosopite.finishYou can also pause items in a block, and the Prosopite.resume will be done
for you automatically:
Prosopite.scan
# <code to scan>
result = Prosopite.pause do
# <code that has n+1s>
end
Prosopite.finish
…
ruby
Proposite.raise = false# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
def raise_on_n_plus_ones!(**options)
return if Rails.env.production?
prepend_around_action(:_raise_on_n_plus_ones, **options)
end
unless Rails.env.production?
around_action :n_plus_one_detection
def n_plus_one_detection
...
end
def _raise_on_n_plus_ones
Proposite.start_raise
yield
ensure
Prosopite.stop_raise
end
end
end# app/controllers/books_controller.rb
class BooksController < ApplicationController
raise_on_n_plus_ones!(only: [:index])
def index
@books = Book.all.map(&:author) # This will raise N+1 errors
end
def show
@book = Book.find(params[:id])
@book.reviews.map(&:author) # This will not raise N+1 errors
end
endYou can supply a custom logger with the Prosopite.custom_logger setting.
This is useful for circumstances where you don't want your logs to be highlighted with red, or you want logs sent to a custom location.
One common scenario is that you may be generating json logs and sending them to Datadog, ELK stack, or similar, and don't want to have to remove the default red escaping data from messages sent to the Rails logger, or want to tag them differently with your own custom logger.
# Turns off logging with red highlights, but still sends them to the Rails logger
Prosopite.custom_logger = Rails.logger# Use a completely custom logging instance
Prosopite.custom_logger = MyLoggerClass.newBug reports and pull requests are welcome on GitHub at https://github.com/charkost/prosopite.
Prosopite is licensed under the Apache License, Version 2.0. See LICENSE.txt for the full license text.
No open issues yet, or sync has not completed.