Created
December 10, 2020 08:47
-
-
Save emad-elsaid/174d58f910ae494252bb945cd4868a82 to your computer and use it in GitHub Desktop.
rails_explain_sql_initializer
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 Explainer < ActiveSupport::LogSubscriber | |
def sql(event) | |
payload = event.payload | |
return if ignore_payload?(payload) | |
debug color(ActiveRecord::Base.connection.explain(payload[:sql], payload[:binds]), :yellow) | |
end | |
private | |
IGNORED_PAYLOADS = %w[SCHEMA EXPLAIN].freeze | |
EXPLAINED_SQLS = /\A\s*(with|select|update|delete|insert)\b/i.freeze | |
def ignore_payload?(payload) | |
payload[:cached] || | |
IGNORED_PAYLOADS.include?(payload[:name]) || | |
payload[:sql] !~ EXPLAINED_SQLS | |
end | |
end | |
Explainer.attach_to :active_record |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment