2012-02-27 9 views
2

私は、ActiveRecord(2.3.12)を使ってMySQLデータベースにアクセスしているRubyスクリプトを持っています。このフローは、「設定ファイルからデータベース値を読み込む」、「データベースに接続する」、「テーブルが作成されていない場合はAを作成する」、「ファイルをダウンロードして解析する」、「解析されたレコードをAに保存する」などです。ActiveRecordは実際にどの時点でデータベースに接続しますか?

コードは次のようになります。

ActiveRecord::Base.establish_connection(
    :adapter => 'mysql', 
    :database => database_name, 
    :username => username, 
    :password => password, 
    :host => "localhost", 
    :port => 3306 
) 

    ... 

ActiveRecord::Schema.define do 
    create_table a, :force => true do |t| 
    t.string :last_name, :limit => 60, :default => "", :null => false 
    t.string :first_name, :limit => 30, :default => "", :null => false 
    t.string :middle_initial, :limit => 2, :default => "" 
    t.string :dob, :limit => 12, :default => "", :null => false 
    end 
end unless A.table_exists? 

私はestablish_connection法に間違ったDBの資格情報、または存在しないデータベース名を入れる場合は、このスクリプトは、すべてのエラーを与えていないようですか実際にデータベース上で何らかの操作を実行しようとするまで(つまり、テーブルAを作成するまで)例外をスローします。私はbegin-rescue-endを約establish_connectionにしようとしましたが、ブロックrescueには決して行きませんでした。

なぜestablish_connectionは実際にはそうではないようですね...よく接続を確立しますか?そして、私の人生のために、私はそれが戻ってくるはずのものを理解することができません。ドキュメントHEREは必ずしも役立たないようです。

または何か間違っていますか?助けてください!

答えて

3

、接続定義の以上であったと仮定ActiveRecord::Base.connection.active? ActiveRecordが実際にデータベースに接続されているかどうかを確認するステートメント。

def establish_database_connection 
    begin 
    ActiveRecord::Base.establish_connection config["database"] 
    ActiveRecord::Base.connection.active? 
    logger.info "Connected to Database" 
    rescue Exception => e 
    logger.error "Exception db connection : #{e.message} " 
    raise "Database connection failed" 
    end 
end 

なしActiveRecord :: Base.connection.active?このコードでは、無効な資格情報でエラーが発生しません。

0

私は専門家ではないんだけど、私はいつもそれが使用されている場合、実際の接続が行われているのに対し、establish_connectionはこの場合、私は通常使用table_exists?実行

2

RSKのソリューションでは、現在のスレッドに対して接続がチェックアウトされたままになります。あなたはそれをしたくない場合は、これを試してください(だけPostgresのためである、https://gist.github.com/limhoff-r7/71ee6b1568b604e131a8から適応):

ActiveRecord::Base.establish_connection 

# Check if the spec passed to `ActiveRecord::Base.establish_connection` can connect to the database. 
# 
# @return [true] if an active connection can be made to the database using the current config. 
# @return [false] if an active connection cannot be made to the database. 
def connection_established? 
    begin 
    # use with_connection so the connection doesn't stay pinned to the thread. 
    ActiveRecord::Base.connection_pool.with_connection { 
     ActiveRecord::Base.connection.active? 
    } 
    rescue Exception 
    false 
    end 
end 
1

私は@Luke Imhoff氏に同意する:手動でのActiveRecordの接続プールからチェックアウトされている接続に持っています手動でプールに戻すことができます。注意点としては は、しかし、私はブロック

ActiveRecord::Base.connection_pool.with_connection { |con| con.active? } 

にActiveRecordの利回りはdocumentation of :with_connectionを参照した接続を使用することをお勧め:

関連する問題