3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
# File 'app/controllers/devformance/playground_controller.rb', line 3
def run
query_string = params[:query]
unless query_string.present?
return render json: { status: "error", output: "Empty query" }, status: :unprocessable_entity
end
result = nil
duration = 0
slow_queries_detected = []
begin
ActiveSupport::Notifications.subscribe("sql.active_record") do |name, start, finish, id, payload|
if payload[:sql] !~ /SCHEMA/
Rails.logger.debug "SQL: #{payload[:sql]}"
end
end
Bullet.start_request if defined?(Bullet)
duration = Benchmark.ms do
result = eval(query_string)
result = result.to_a if result.is_a?(ActiveRecord::Relation)
end
if defined?(Bullet) && Bullet.notification_collector.notifications_present?
Bullet.notification_collector.collection.each do |notification|
next unless notification.is_a?(Bullet::Notification::NPlusOneQuery)
model = notification.base_class rescue "Unknown"
suggestion = notification.body
sq = Devformance::SlowQuery.create!(
model_class: model,
line_number: caller.first.match(/:(\d+):/)&.captures&.first&.to_i || 0,
fix_suggestion: suggestion
)
slow_queries_detected << sq
ActionCable.server.broadcast("devformance:metrics", {
type: "new_slow_query",
payload: {
id: sq.id,
model_class: sq.model_class,
line_number: sq.line_number,
fix_suggestion: sq.fix_suggestion,
duration: duration.round(2)
}
})
end
end
Bullet.end_request if defined?(Bullet)
QueryLog.create(query: query_string, duration: duration) rescue nil
render json: {
status: "success",
duration: duration.round(2),
output: result.inspect.truncate(1000)
}
rescue Exception => e
Bullet.end_request if defined?(Bullet)
QueryLog.create(query: query_string, duration: 0) rescue nil
render json: {
status: "error",
duration: duration.round(2),
output: "#{e.class}: #{e.message}\n#{e.backtrace.first(3).join("\n")}"
}
ensure
ActiveSupport::Notifications.unsubscribe("sql.active_record") rescue nil
end
end
|