class RuntimeProfiler::SqlEvent

Attributes

finished_at[R]
payload[R]
started_at[R]
trace[R]

Public Class Methods

new(args: , trace: ) click to toggle source
# File lib/runtime_profiler/events/sql_event.rb, line 7
def initialize(args: , trace: )
  _name, @started_at, @finished_at, _unique_id, @payload = args
  @trace = sanitize_trace!(trace)
end

Public Instance Methods

key() click to toggle source
# File lib/runtime_profiler/events/sql_event.rb, line 34
def key
  @key ||= Digest::MD5.hexdigest(sql.downcase)
end
recordable?() click to toggle source
# File lib/runtime_profiler/events/sql_event.rb, line 12
def recordable?
  return true unless RuntimeProfiler.profiled_sql_commands.respond_to?(:join)
  profiled_sql_matcher =~ sql
end
sanitized_sql() click to toggle source
# File lib/runtime_profiler/events/sql_event.rb, line 21
def sanitized_sql
  sql.squish!

  sql.gsub!(/(\s(=|>|<|>=|<=|<>|!=)\s)('[^']+'|[\$\+\-\w\.]+)/, '\1xxx')
  sql.gsub!(/(\sIN\s)\([^\(\)]+\)/i, '\1(xxx)')
  sql.gsub!(/(\sBETWEEN\s)('[^']+'|[\+\-\w\.]+)(\sAND\s)('[^']+'|[\+\-\w\.]+)/i, '\1xxx\3xxx')
  sql.gsub!(/(\sVALUES\s)\(.+\)/i, '\1(xxx)')
  sql.gsub!(/(\s(LIKE|ILIKE|SIMILAR TO|NOT SIMILAR TO)\s)('[^']+')/i, '\1xxx')
  sql.gsub!(/(\s(LIMIT|OFFSET)\s)(\d+)/i, '\1xxx')

  sql
end
total_runtime() click to toggle source
# File lib/runtime_profiler/events/sql_event.rb, line 17
def total_runtime
  1000.0 * (@finished_at - @started_at)
end

Private Instance Methods

profiled_sql_matcher() click to toggle source
# File lib/runtime_profiler/events/sql_event.rb, line 44
def profiled_sql_matcher
  @profiled_sql_matcher ||= /\A#{RuntimeProfiler.profiled_sql_commands.join('|')}/i
end
sanitize_trace!(trace) click to toggle source
# File lib/runtime_profiler/events/sql_event.rb, line 52
def sanitize_trace!(trace)
  return trace unless defined?(Rails)
  return trace unless Rails.respond_to?(:backtrace_cleaner)

  if Rails.backtrace_cleaner.instance_variable_get(:@root) == '/'
    Rails.backtrace_cleaner.instance_variable_set :@root, Rails.root.to_s
  end

  Rails.backtrace_cleaner.remove_silencers!

  if RuntimeProfiler.profiled_paths.respond_to?(:join)
    Rails.backtrace_cleaner.add_silencer do |line|
      line !~ trace_path_matcher
    end
  end

  Rails.backtrace_cleaner.clean(trace)
end
sql() click to toggle source
# File lib/runtime_profiler/events/sql_event.rb, line 40
def sql
  @sql ||= @payload[:sql].dup
end
trace_path_matcher() click to toggle source
# File lib/runtime_profiler/events/sql_event.rb, line 48
def trace_path_matcher
  @trace_path_matcher ||= %r{^(#{RuntimeProfiler.profiled_paths.join('|')})\/}
end