module PgsqlStats class Index include ActionView::Helpers::NumberHelper attr_accessor :oid, :table_oid, :name, :table_name, :schema_name, :scans, :entries_read, :rows_fetched, :blocks_read, :cache_hits attr_accessor :analysis def initialize(connection, row, io_row) @connection = connection @analysis = nil load(row) load_io(io_row) end def refresh @connection.transaction do load(@connection.select_one("SELECT * FROM pg_stat_all_indexes WHERE indexrelid = #{oid}")) load_io(@connection.select_one("SELECT * FROM pg_statio_all_indexes WHERE indexrelid = #{oid}")) end @analysis = nil @pages = nil @table = nil end def table unless @table stats = @connection.select_one("SELECT * FROM pg_stat_all_tables WHERE relid = #{table_oid}") io = @connection.select_one("SELECT * FROM pg_statio_all_tables WHERE relid = #{table_oid}") @table = Table.new(@connection, stats, io) end @table end def cache_hit_rate cache_hits.to_f / (blocks_read + cache_hits) * 100 end def pages @pages ||= @connection.select_one("SELECT SUM(relpages) FROM pg_class WHERE relname = '#{name}'")["sum"].to_i end private def load(row) self.oid = row["indexrelid"].to_i self.table_oid = row["relid"].to_i self.name = row["indexrelname"] self.table_name = row["relname"] self.schema_name = row["schemaname"] self.scans = row["idx_scan"].to_i self.entries_read = row["idx_tup_read"].to_i self.rows_fetched = row["idx_tup_fetch"].to_i end def load_io(row) self.blocks_read = row["idx_blks_read"].to_i self.cache_hits = row["idx_blks_hit"].to_i end end end