Skip to content

Instantly share code, notes, and snippets.

@licatajustin
Forked from itisjustlu/readme.md
Last active November 10, 2020 16:40
Show Gist options
  • Select an option

  • Save licatajustin/3595874ab5d5a0e64d1dcd004357a0fc to your computer and use it in GitHub Desktop.

Select an option

Save licatajustin/3595874ab5d5a0e64d1dcd004357a0fc to your computer and use it in GitHub Desktop.
Count sql queries in ActiveRecord, Rails
class SomeController
around_action :record_sql_queries
private
def record_sql_queries
ActiveRecord::Base.count_queries do
yield
end
end
end
module ActiveRecord
class QueryCounter
cattr_accessor :query_count do
0
end
IGNORED_SQL = [/^PRAGMA (?!(table_info))/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/, /^SAVEPOINT/, /^ROLLBACK TO SAVEPOINT/, /^RELEASE SAVEPOINT/, /^SHOW max_identifier_length/]
def call(name, start, finish, message_id, values)
# FIXME: this seems bad. we should probably have a better way to indicate
# the query was cached
unless 'CACHE' == values[:name]
self.class.query_count += 1 unless IGNORED_SQL.any? { |r| values[:sql] =~ r }
end
end
end
end
ActiveSupport::Notifications.subscribe('sql.active_record', ActiveRecord::QueryCounter.new)
module ActiveRecord
class Base
def self.count_queries(&block)
ActiveRecord::QueryCounter.query_count = 0
yield
count = ActiveRecord::QueryCounter.query_count
Rails.logger.info("COUNT: #{count}")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment