2011-09-05 57 views
6

如何在Heroku上管理我的數據庫索引?我知道點擊,但似乎是推/拉數據。在Heroku上管理數據庫索引

如何查看,更新,刪除我的索引?我的開發數據庫是sqlite3而在Heroku它的postgres。

+0

這是$ 15 /月postgres,20演出。我不確定它是共享的還是專用的。 – Brand

回答

1

看起來你正在使用一個共享的而不是專用的數據庫,所以你必須這樣做的困難。如果你有專門的數據庫,那麼你可以heroku pg:psql,然後\di and assorted other psql commands得到你要的。

雖然總是有困難的方式,並涉及內部目錄表。您將需要很少的SQL塊,您可以將它們包裝在ActiveRecord::Base.connection.select_rows調用中,並從Rails控制檯訪問結果。

你可以得到你的表及其索引與此列表:

select c2.relname as table, c2.oid as table_oid, c.relname as name, c.oid as index_oid 
from pg_catalog.pg_class c 
join pg_catalog.pg_index i on i.indexrelid = c.oid 
join pg_catalog.pg_class c2 on i.indrelid = c2.oid 
left join pg_catalog.pg_user u on u.usesysid = c.relowner 
left join pg_catalog.pg_namespace n on n.oid = c.relnamespace 
where c.relkind = 'i' 
    and n.nspname <> 'pg_catalog' 
    and pg_catalog.pg_table_is_visible(c.oid) 
order by c2.relname, c.relname 

然後你可以使用index_oid來獲得指標的問題,跟這個有描述:

select c.relname, c.oid, i.indisprimary, i.indisunique, i.indisclustered, i.indisvalid, pg_catalog.pg_get_indexdef(i.indexrelid, 0, true), c.reltablespace 
from pg_catalog.pg_class c 
join pg_catalog.pg_index i on c.oid = i.indexrelid 
where c.oid = '#{index_oid}' 

或者您可以使用table_oid獲得該表的索引列表:

select ci.relname, ci.oid, i.indisprimary, i.indisunique, i.indisclustered, i.indisvalid, pg_catalog.pg_get_indexdef(i.indexrelid, 0, true), ci.reltablespace 
from pg_catalog.pg_index i 
join pg_catalog.pg_class ci on i.indexrelid = ci.oid 
where i.indrelid = '#{table_oid}' 
order by ci.relname 

你可能想包裝所有這些東西在輕鬆訪問的工具類:

class PGInfo 
    def self.list_indexes 
     data = ActiveRecord::Base.connection.select_rows(%Q{ 
      select c2.relname as table, c.relname as name, c.oid as oid 
      ... 
     }) 
     # do something pretty with the array of arrays that is in data 
    end 
    # etc. 
end 

我還沒有在Heroku的共享數據庫嘗試這些(對不起,我只有一個專用數據庫打用)。可能有更簡單的方法,但這些應該完成工作,並且如果將它們包裝到PGInfo類中,它們將很容易使用。

所有爲您提供所需的索引信息,然後您可以使用正常的遷移添加,刪除或修改您的索引。

+0

非常詳細的答案謝謝你 – Brand

+0

@品牌:不客氣,我實際上使用答案來記錄自己有時:) –

1

您應該通過您的遷移來管理您的索引,以便它們在您的環境中保持同步。

+0

這不讓我查看我的索引是否做到了?或者你在談論看看schema.rb? – Brand

+0

那麼,如果你想要的話,你可以在所有的遷移中grep add_index,但是schema.rb是要查看的地方。我不知道一個更好的方法,我認爲做任何與Heroku有關的事情都會讓你改變生產數據庫模式,而這種方式將會變得醜陋。 – spike