我有一个在MySql DB上运行的Rails 2.3.8应用程序。 是否可以通过Rails应用程序检查数据库的实际大小(以兆字节为单位)? 如果是这样,我可以获得详细的视图,例如某个表占用多少兆字节?
有什么想法吗?
答案 0 :(得分:3)
我在前一段时间创建了gem
gem 'mysql_rake_tasks', '~> 0.1.0'
bundle install
rake db:mysql:stats
+--------------------------------+---------------+-----------+----------+------------+
| Table Name | Rows | Data Size | IDX Size | Total Size |
+--------------------------------+---------------+-----------+----------+------------+
| fish | 1.41 Million | 93.6 MB | 41.1 MB | 135 MB |
| birds | 0 | 16 KB | 0 Bytes | 16 KB |
| cats | 14 | 16 KB | 0 Bytes | 16 KB |
| schema_migrations | 7 | 16 KB | 0 Bytes | 16 KB |
| users | 5 | 16 KB | 32 KB | 48 KB |
+--------------------------------+---------------+-----------+----------+------------+
| | 135 MB |
+--------------------------------+---------------+-----------+----------+------------+
Database: mydb_development MySQL Server Version: 5.1.58
答案 1 :(得分:2)
该页面的一些查询:
SELECT table_schema 'database',
concat( round( sum( data_length + index_length ) / ( 1024 *1024 ) , 2 ) , 'M' ) size
FROM information_schema.TABLES
WHERE ENGINE=('MyISAM' || 'InnoDB' )
GROUP BY table_schema;
答案 2 :(得分:1)
如果你只想把结果重新变成Hash,那么这个效果非常好:
db_name = Rails.configuration.database_configuration[Rails.env]["database"]
sql = "SELECT table_name AS name, table_rows, data_length, index_length FROM information_schema.TABLES WHERE table_schema = '#{db_name}' ORDER BY (data_length + index_length) DESC;"
table_data = ActiveRecord::Base.connection.execute(sql).map{|r| {name: r[0], rows: r[1], data_size: r[2], index_size: r[3]}}
然后,如果您在Rails控制台中并想要转储结果:
c,d,i=0,0,0;table_data.each {|r| print r[:name].ljust(30),helper.number_with_delimiter(r[:rows]).rjust(16)," rows", helper.number_to_human_size(r[:data_size]).rjust(12), helper.number_to_human_size(r[:index_size]).rjust(12), helper.number_to_human_size(r[:data_size] + r[:index_size]).rjust(12),"\n";c+=r[:rows];d+=r[:data_size];i+=r[:index_size]};print "-"*90,"\n","Total".ljust(30),helper.number_with_delimiter(c).rjust(16)," rows", helper.number_to_human_size(d).rjust(12), helper.number_to_human_size(i).rjust(12), helper.number_to_human_size(d+i).rjust(12),"\n"