Active Record Analyze

Public
Adds an "analyze" method to all Active Record query objects.
Icons/chart bar
Used 44 times
Created by
V Viktor Schmidt

Usage
RubyGems: https://rubygems.org/gems/activerecord-analyze

This gem adds an analyze method to Active Record query objects. It executes EXPLAIN ANALYZE on a query SQL.

You can check out this blog post for more info on how to debug and fix slow queries in Rails apps.

It lets you visualize a query plan using a visualizer tool.

Run this command in your Rails app directory in the terminal:

rails app:template LOCATION="https://railsbytes.com/script/VKAsvO"
Template Source

Review the code before running this template on your machine.

def do_bundle
  Bundler.with_unbundled_env { run "bundle install" }
end

def print_green(heredoc)
  puts set_color heredoc, :green
end

def do_commit
  git :init
  git add: "."
  Bundler.with_unbundled_env { git commit: " -m 'Add Active Record Analyze to all Active Record query objects' " }
end

say "Applying Active Record Analyze..."
inject_into_file 'Gemfile', after: 'group :development do' do
  <<-RUBY

  # Adds an "analyze" method to all Active Record query objects.
  gem "activerecord-analyze"
  RUBY
end

do_bundle

say "\nAdding documentation for developers..."
create_file "docs/performance.md", "# Performance\n" unless File.exist? "docs/performance.md"
append_file "docs/performance.md" do
  <<~EOF  

  ## Active Record Analyze

  This gem adds an analyze method to Active Record query objects.
  It executes [EXPLAIN ANALYZE](https://www.postgresql.org/docs/13/sql-explain.html)
  on a query SQL.

  You can check out this blog post for more info on
  [how to debug and fix slow queries in Rails](https://pawelurbanek.com/slow-rails-queries)
  apps.
  It lets you visualize a query plan using a visualizer tool.

  ### Examples
  
  ```ruby
  # Executes EXPLAIN ANALYZE on a query SQL
  puts User.all.analyze
  # Lets you visualize a query plan using a visualizer tool (verbose)
  puts User.all.analyze(format: :json, costs: true, buffers: true, verbose: true)
  # You can also use a raw SQL query string, extracted from the logs
  query = "SELECT * FROM users WHERE email = '[email protected]'"
  puts ActiveRecordAnalyze.analyze_sql(query, { format: :json })
  ```

  ### Options

  ```ruby
  buffers: [ boolean ]
  verbose: [ boolean ]
  costs: [ boolean ]
  settings: [ boolean ]
  timing: [ boolean ]
  summary: [ boolean ]
  format: { :text | :json | :xml | :yaml | :pretty_json }
  ```
  EOF
end

run "bin/rubocop -AS"
do_commit

print_green "\nAdded Active Record Analyze successfully!"
Comments
Viktor Schmidt