我有一个运行在MySql数据库上的Rails 2.3.8应用程序。 是否可以通过Rails应用程序检查数据库的实际大小(以兆字节为单位)? 如果是这样,我可以得到一个详细的视图,如某个表有多少兆字节?通过Rails检查MySql数据库大小
有什么想法?
我有一个运行在MySql数据库上的Rails 2.3.8应用程序。 是否可以通过Rails应用程序检查数据库的实际大小(以兆字节为单位)? 如果是这样,我可以得到一个详细的视图,如某个表有多少兆字节?通过Rails检查MySql数据库大小
有什么想法?
您可以获取所有你需要从INFORMATION_SCHEMA
从该页面中的一些查询:
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;
我创建了一个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
是否有可能根据foreign_key获取表的大小? – 2014-11-17 09:34:07
如果你只是想将结果反馈进入哈希,那么这个工作很好:
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"
上述代码是否适用于PostgreSQL数据库? – 2016-09-16 20:51:20
我使用'的ActiveRecord :: Base.connection.execute(SQL)'来执行查询,什么是处理返回值的最佳方法是什么? – Ran 2011-03-14 14:53:36
ActiveRecord :: Base.connection.execute(sql).map {| r | r}会给你这样的东西[[“app_name_production”,“64.09M”],[“information_schema”,“0.00M”]] – ToreyHeinz 2012-02-29 00:22:53