@akrzos Check out ActiveRecord::TestCase#assert_queries which uses
ActiveRecord::SQLCounter
I have a vmdb/config/initializers/sql_query_counter.rb with some local changes for mysql and oracle schema related queries to ignore and some other logic for choosing to selectively ignore some queries.
I haven’t run this in many months, but with this initializer, I can run assert_queries(10) { SomeClass.new.method_with_lots_of_queries } in rails console and it yells at me if the the query counts don’t match.
It could be easily changed to yell if > x number of queries occur and could be used in combination with a Rails runner script to run a specific task and verify the query count.
Here is the contents of my sql_query_counter.rb initializers file that was borrowed from the Rails code above:
if !Rails.env.production? && defined?(ActiveSupport::Notifications)
# lifted from lib/active_record/test_case.rb
def assert_queries(num = 1, options = {})
ignore_none = options.fetch(:ignore_none) { num == :any }
SQLCounter.clear_log
yield
ensure
the_log = ignore_none ? SQLCounter.log_all : SQLCounter.log
if num == :any
STDERR.puts("1 or more queries expected, but none were executed.") if the_log.size >= 1
else
mesg = "#{the_log.size} instead of #{num} queries were executed.#{the_log.size == 0 ? '' : "\nQueries:\n#{the_log.join("\n")}"}"
STDERR.puts(mesg) unless num == the_log.size
end
end
def assert_no_queries(&block)
assert_queries(0, :ignore_none => true, &block)
end
class SQLCounter
class << self
attr_accessor :ignored_sql, :log, :log_all
def clear_log; self.log = []; self.log_all = []; end
end
self.clear_log
self.ignored_sql = [/^PRAGMA (?!(table_info))/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/, /^SAVEPOINT/, /^ROLLBACK TO SAVEPOINT/, /^RELEASE SAVEPOINT/, /^SHOW max_identifier_length/, /^BEGIN/, /^COMMIT/]
# FIXME: this needs to be refactored so specific database can add their own
# ignored SQL, or better yet, use a different notification for the queries
# instead examining the SQL content.
oracle_ignored = [/^select .*nextval/i, /^SAVEPOINT/, /^ROLLBACK TO/, /^\s*select .* from all_triggers/im]
mysql_ignored = [/^SHOW TABLES/i, /^SHOW FULL FIELDS/]
postgresql_ignored = [/^\s*select\b.*\bfrom\b.*pg_namespace\b/im, /^\s*select\b.*\battname\b.*\bfrom\b.*\bpg_attribute\b/im]
[oracle_ignored, mysql_ignored, postgresql_ignored].each do |db_ignored_sql|
ignored_sql.concat db_ignored_sql
end
attr_reader :ignore
def initialize(ignore = Regexp.union(self.class.ignored_sql))
@ignore = ignore
end
def call(name, start, finish, message_id, values)
sql = values[:sql]
# FIXME: this seems bad. we should probably have a better way to indicate
# the query was cached
return if 'CACHE' == values[:name]
self.class.log_all << sql
self.class.log << sql unless ignore =~ sql
end
end
ActiveSupport::Notifications.subscribe('sql.active_record', SQLCounter.new)
end