I have a ruby script that is using ActiveRecord (2.3.12) to access a MySQL database. The flow goes something like, “read database values from a config file”, “connect to database”, “Create table A if it doesn’t exist”, “download and parse a file”, “save parsed records to A“.
The code looks like the following:
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?
However, if I put incorrect DB credentials, or a non-existent database name into the establish_connection method, the script doesn’t seem to give any errors or throw any exceptions until I actually try to perform some operation on the database (i.e., create table A). I tried a begin-rescue-end around establish_connection, but it never went into the rescue block.
Why does establish_connection seem to not really…well…establish the connection? And for the life of me, I can’t figure out what it is even supposed to return. The docs HERE sure don’t seem to be any help.
Or am I doing something wrong? Please help!
I usually use
ActiveRecord::Base.connection.active?statement to check the whether the ActiveRecord is really connected to database.Without ActiveRecord::Base.connection.active? statement the above code won’t raise any error on invalid credentials.