Andrey Yasinishyn
Andrey Yasinishyn

Reputation: 1861

how to check where mysql dababase exists from rails env?

My app, must work with multiple db's for many reasons. I work on custom model for db connection establishing, where I need to establish new db connection, based on arg's, . So, for example, before establishing new connection using:

ActiveRecord::Base.establish_connection new_config 

Where new_config is customized clone, of database.yml

I want to check whether new DB exists before any db connections establishing. So I need a function db_exists? db_name that will return boolean value, based on whether db exists or not.

Upvotes: 3

Views: 355

Answers (2)

Tom Wilson
Tom Wilson

Reputation: 837

We use Rails apps to manage databases themselves, so have to do stuff like this all the time. It's perfectly reasonable to want to know about databases besides the current Rails data store. It's a lot like checking for the existence of a file that's not part of the current Rails app.

Here's a solution that may be useful in certain situations (this for MySQL):

def db_exists?(db_name)
  ActiveRecord::Base.connection.execute("SHOW DATABASES LIKE '#{db_name}'").size > 0
end

You have to have SOME database connection but it certainly does not have to be for the database you are querying for existence. (Note this implementation is NOT protected against sql injection... it requires you only pass in clean, valid db_name.)

Upvotes: 1

Richard_G
Richard_G

Reputation: 4820

It seems a bit illogical to be able to check whether or not a database exists without a connection to that database, but that may just be me.

I recommend you consider using a rescue block to attempt the connection and then handle the appropriate exceptions.

The exceptions you can receive from that attempt are discussed here.

Just ran across a very good discussion on using rescue here.

Upvotes: 2

Related Questions