Skip to content

Instantly share code, notes, and snippets.

@fatkodima
Created January 17, 2024 00:35
Show Gist options
  • Save fatkodima/36648a642364976777a64fe3f44f091b to your computer and use it in GitHub Desktop.
Save fatkodima/36648a642364976777a64fe3f44f091b 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