-
-
Save licatajustin/3595874ab5d5a0e64d1dcd004357a0fc to your computer and use it in GitHub Desktop.
Count sql queries in ActiveRecord, Rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class SomeController | |
| around_action :record_sql_queries | |
| private | |
| def record_sql_queries | |
| ActiveRecord::Base.count_queries do | |
| yield | |
| end | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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