Skip to content

Commit

Permalink
capture the number of rows instantiated for active record (#585)
Browse files Browse the repository at this point in the history
This is close to telling you the number of rows brought back from the database
It doesn't show pluck results, so just need to keep that in mind.

But it does help you understand why so much memory is being taken up from active
record queries.
  • Loading branch information
kbrock committed Dec 6, 2023
1 parent f564b12 commit 0869490
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 1 deletion.
4 changes: 4 additions & 0 deletions lib/mini_profiler/profiling_methods.rb
Expand Up @@ -17,6 +17,10 @@ def record_sql(query, elapsed_ms, params = nil)
)
end

def report_reader_duration(elapsed_ms, row_count = nil, class_name = nil)
current&.current_timer&.report_reader_duration(elapsed_ms, row_count, class_name)
end

def start_step(name)
return unless current
parent_timer = current.current_timer
Expand Down
6 changes: 6 additions & 0 deletions lib/mini_profiler/timer_struct/request.rb
Expand Up @@ -125,6 +125,12 @@ def move_sql(sql, destination)
end
end

# please call SqlTiming#report_reader_duration instead
def report_reader_duration(elapsed_ms, row_count = nil, class_name = nil)
last_time = self[:sql_timings]&.last
last_time&.report_reader_duration(elapsed_ms, row_count, class_name)
end

def add_custom(type, elapsed_ms, page)
TimerStruct::Custom.new(type, elapsed_ms, page, self).tap do |timer|
timer[:parent_timing_id] = self[:id]
Expand Down
4 changes: 3 additions & 1 deletion lib/mini_profiler/timer_struct/sql.rb
Expand Up @@ -51,12 +51,14 @@ def initialize(query, duration_ms, page, parent, params = nil, skip_backtrace =
)
end

def report_reader_duration(elapsed_ms)
def report_reader_duration(elapsed_ms, row_count = nil, class_name = nil)
return if @reported
@reported = true
self[:duration_milliseconds] += elapsed_ms
@parent[:sql_timings_duration_milliseconds] += elapsed_ms
@page[:duration_milliseconds_in_sql] += elapsed_ms
self[:row_count] = self[:row_count].to_i + row_count if row_count
self[:class_name] = class_name if class_name
end

def trim_binds(binds)
Expand Down
10 changes: 10 additions & 0 deletions lib/mini_profiler_rails/railtie.rb
Expand Up @@ -114,6 +114,16 @@ def self.initialize!(app)
Rack::MiniProfiler.binds_to_params(payload[:binds])
)
end

subscribe("instantiation.active_record") do |name, start, finish, id, payload|
next if !should_measure?

Rack::MiniProfiler.report_reader_duration(
(finish - start) * 1000,
payload[:record_count],
payload[:class_name]
)
end
end
end
@already_initialized = true
Expand Down

0 comments on commit 0869490

Please sign in to comment.