在Ruby on Rails中获取ActiveRecord连接的查询数量/计数的简单方法是什么?
订阅as explained in this SO thread似乎有点复杂,因为我只想要在连接的整个生命周期内发出的实际总查询数。
答案 0 :(得分:0)
所以我自己做了一个monkeypatch初始化程序:)
### Query Counter for mysql2 adapter
module ActiveRecord
module ConnectionAdapters
class AbstractAdapter
@@querycount = 0
attr_reader :querycount
def self.querycount; @@querycount; end
end
class Mysql2Adapter < AbstractMysqlAdapter
def exec_query(sql, name = 'SQL', binds = [])
@@querycount += 1
@querycount = 0 if @querycount.nil?
@querycount += 1
result = execute(sql, name)
ActiveRecord::Result.new(result.fields, result.to_a)
end
end
end
end
然后,您可以使用
获取所有连接的总查询次数ActiveRecord::ConnectionAdapters::AbstractAdapter.querycount