Last active
April 14, 2020 23:42
-
-
Save bhelx/6685303dd8756dddfbdf5c8a22b27a9f to your computer and use it in GitHub Desktop.
Pass a block of code to `while_enabled` to sniff out any SQL queries it might be making.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SqlCanary | |
def self.enable! | |
Thread.current[:sql_canary] = true | |
end | |
def self.disable! | |
Thread.current[:sql_canary] = false | |
end | |
def self.enabled? | |
Thread.current[:sql_canary] || false | |
end | |
def self.while_enabled | |
SqlCanary.enable! | |
yield | |
ensure | |
SqlCanary.disable! | |
end | |
end | |
ActiveSupport::Notifications.subscribe('sql.active_record') do |_name, _start, _finish, _id, payload| | |
if SqlCanary.enabled? && payload[:sql] && payload[:sql].start_with?('SELECT') | |
raise StandardError.new <<-MSG | |
The code change you have made has caused a database query inside a V3 presenter. | |
This has the potential to cause n+1 queries. The sql you tried to execute was: | |
#{payload[:sql]} | |
Make sure that you have updated the V3 presenter's "association" method with the proper | |
resources to preload. | |
MSG | |
#else | |
#puts payload | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment