2017-06-01 10:10:17 -04:00
|
|
|
# Inspired by https://github.com/peek/peek-pg/blob/master/lib/peek/views/pg.rb
|
2017-07-17 10:44:00 -04:00
|
|
|
# PEEK_DB_CLIENT is a constant set in config/initializers/peek.rb
|
2017-06-01 10:10:17 -04:00
|
|
|
module Gitlab
|
|
|
|
module PerformanceBar
|
2017-06-07 10:53:13 -04:00
|
|
|
module PeekQueryTracker
|
|
|
|
def sorted_queries
|
2017-06-21 09:48:12 -04:00
|
|
|
PEEK_DB_CLIENT.query_details
|
|
|
|
.sort { |a, b| b[:duration] <=> a[:duration] }
|
2017-06-01 10:10:17 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def results
|
2017-06-07 10:53:13 -04:00
|
|
|
super.merge(queries: sorted_queries)
|
2017-06-01 10:10:17 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def setup_subscribers
|
|
|
|
super
|
|
|
|
|
|
|
|
# Reset each counter when a new request starts
|
|
|
|
before_request do
|
2017-06-07 10:53:13 -04:00
|
|
|
PEEK_DB_CLIENT.query_details = []
|
2017-06-01 10:10:17 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
subscribe('sql.active_record') do |_, start, finish, _, data|
|
|
|
|
if RequestStore.active? && RequestStore.store[:peek_enabled]
|
2017-07-17 10:44:00 -04:00
|
|
|
# data[:cached] is only available starting from Rails 5.1.0
|
|
|
|
# https://github.com/rails/rails/blob/v5.1.0/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb#L113
|
|
|
|
# Before that, data[:name] was set to 'CACHE'
|
|
|
|
# https://github.com/rails/rails/blob/v4.2.9/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb#L80
|
|
|
|
unless data.fetch(:cached, data[:name] == 'CACHE')
|
|
|
|
track_query(data[:sql].strip, data[:binds], start, finish)
|
|
|
|
end
|
2017-06-01 10:10:17 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def track_query(raw_query, bindings, start, finish)
|
|
|
|
query = Gitlab::Sherlock::Query.new(raw_query, start, finish)
|
2017-07-18 13:00:46 -04:00
|
|
|
query_info = { duration: query.duration.round(3), sql: query.formatted_query }
|
2017-06-07 13:55:07 -04:00
|
|
|
|
2017-06-07 10:53:13 -04:00
|
|
|
PEEK_DB_CLIENT.query_details << query_info
|
2017-06-01 10:10:17 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|