ActiveRecordでクエリ発行元をコメントに含める
ActiveRecord経由で実行されるでSQLのコメントにクエリ発行元を含めるテク
https://gist.github.com/alpaca-tc/97b875d63e0e798537e0e3d5c234e0b5
code:ruby
# frozen_string_literal: true
dowsing = Module.new do
def execute(sql, *)
source_location = query_source_location(caller.lazy)
sql = "#{sql} /* #{source_location} */" if source_location
super
end
private
def query_source_location(locations)
source_location = ActiveRecord::LogSubscriber.backtrace_cleaner.clean(locations).first
source_location&.remove!('*')
source_location
end
end
ActiveSupport.on_load(:active_record) do
ActiveRecord::ConnectionAdapters::Mysql2Adapter.prepend(dowsing)
end