ActiveRecord(oracle_enhanced_adapter)のモンキーパッチ
oracle_enhanced_adapterのtablesメソッドは他のConnectionAdapter同様にテーブルしか列挙しないため、Oracleの既存のView(ビュー)、Synonym(シノニム)をActiveRecordで活用できない。
def tables(name = nil) #:nodoc: select_all("select lower(table_name) from all_tables where owner = sys_context('userenv','session_user')").inject([]) do | tabs, t | tabs << t.to_a.first.last end end
是非は別にして、スキーマからはテーブルだけではなく、ビューとシノニムも列挙する、以下のようなtableメソッドに対してのモンキーパッチを書いてみたのだが※、
- oracle_enahnced_adapter_view_and_synonym.rb
require 'active_record/connection_adapters/oracle_enhanced_adapter' module ActiveRecord module ConnectionAdapters class OracleEnhancedAdapter < AbstractAdapter def tables(name = nil) select_all(<<-END_SQL select name from ( select lower(table_name) as name, owner from all_tables union all select lower(view_name) as name, owner from all_views union all select lower(synonym_name) as name, owner from all_synonyms ) where owner = sys_context('userenv','session_user') END_SQL ).inject([]) do | tabs, t | tabs << t.to_a.first.last end end end end end
※SQLに関してはあまり自信が無い。もっと効率の良い書き方があるのかもしれない
このようなRailsのコンポーネント(ActiveRecord)に対してのモンキーパッチはどこに配置するのが適当なんだろうか。
試しにemvironment.rbにrequireを書いたんだがdb:schema:dumpを実行すると接続が確立してないぞと怒られてしまった。
E:\www>rake db:schema:dump (in E:/www) rake aborted! uninitialized constant ActiveRecord::ConnectionNotEstablished (See full trace by running task with --trace)
なるほど、establish_connectionが呼ばれる際にはもう既に読み込まれている必要があるのか。
new_rails_defaults.rbに書くことで上手く動くことを確認したんだが、そもそもこのスクリプトに手を入れるのが正しいのかもわからん。