Skip to content

Instantly share code, notes, and snippets.

@MaherSaif
Forked from fatkodima/inspect_queries.rb
Created January 22, 2024 20:05
Show Gist options
  • Save MaherSaif/29f63a660cc3d9c5df398160140f7173 to your computer and use it in GitHub Desktop.
Save MaherSaif/29f63a660cc3d9c5df398160140f7173 to your computer and use it in GitHub Desktop.
Inspect db queries
# Make sure to have prepared statements enabled.
# config/database.yml
# test:
# database: ...
# prepared_statements: true
# Add this to the top scope of test/test_helper.rb or spec/rails_helper.rb and
# run tests as usual.
queries = Hash.new(0)
ActiveSupport::Notifications.subscribe("sql.active_record") do |*, payload|
queries[payload[:sql]] += 1
end
at_exit do
puts "Queries count = #{queries.values.sum}"
queries = queries.sort_by { |k, v| -v }.to_h
queries.each { |k, v| puts "#{v} | #{k}" }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment