2011-03-14 34 views
1

我有一個運行在MySql數據庫上的Rails 2.3.8應用程序。 是否可以通過Rails應用程序檢查數據庫的實際大小(以兆字節爲單位)? 如果是這樣,我可以得到一個詳細的視圖,如某個表有多少兆字節?通過Rails檢查MySql數據庫大小

有什麼想法?

回答

1

您可以獲取所有你需要從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; 
+0

我使用'的ActiveRecord :: Base.connection.execute(SQL)'來執行查詢,什麼是處理返回值的最佳方法是什麼? – Ran 2011-03-14 14:53:36

+0

ActiveRecord :: Base.connection.execute(sql).map {| r | r}會給你這樣的東西[[「app_name_production」,「64.09M」],[「information_schema」,「0.00M」]] – ToreyHeinz 2012-02-29 00:22:53

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 
+0

是否有可能根據foreign_key獲取表的大小? – 2014-11-17 09:34:07

1

如果你只是想將結果反饋進入哈希,那麼這個工作很好:

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" 
+0

上述代碼是否適用於PostgreSQL數據庫? – 2016-09-16 20:51:20