2018-03-29 09:47:54 +00:00
|
|
|
module ActiveRecord
|
|
|
|
class QueryRecorder
|
2018-06-03 10:31:41 +00:00
|
|
|
attr_reader :log, :skip_cached, :cached
|
2018-03-29 09:47:54 +00:00
|
|
|
|
2018-06-03 10:31:41 +00:00
|
|
|
def initialize(skip_cached: true, &block)
|
2018-03-29 09:47:54 +00:00
|
|
|
@log = []
|
|
|
|
@cached = []
|
2018-06-03 10:31:41 +00:00
|
|
|
@skip_cached = skip_cached
|
2018-03-29 09:47:54 +00:00
|
|
|
ActiveSupport::Notifications.subscribed(method(:callback), 'sql.active_record', &block)
|
|
|
|
end
|
|
|
|
|
|
|
|
def show_backtrace(values)
|
|
|
|
Rails.logger.debug("QueryRecorder SQL: #{values[:sql]}")
|
2019-06-14 23:13:07 +00:00
|
|
|
Gitlab::Profiler.clean_backtrace(caller).each { |line| Rails.logger.debug(" --> #{line}") }
|
2018-03-29 09:47:54 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def callback(name, start, finish, message_id, values)
|
|
|
|
show_backtrace(values) if ENV['QUERY_RECORDER_DEBUG']
|
|
|
|
|
2019-01-15 21:05:36 +00:00
|
|
|
if values[:cached] && skip_cached
|
2018-03-29 09:47:54 +00:00
|
|
|
@cached << values[:sql]
|
|
|
|
elsif !values[:name]&.include?("SCHEMA")
|
|
|
|
@log << values[:sql]
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def count
|
|
|
|
@log.count
|
|
|
|
end
|
|
|
|
|
|
|
|
def cached_count
|
|
|
|
@cached.count
|
|
|
|
end
|
|
|
|
|
|
|
|
def log_message
|
|
|
|
@log.join("\n\n")
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|