Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the database exists or not in rails before doing a rake db:setup

How to check if the database exists or not in rails before doing a rake db:setup?

I would like to check if a database already exists before a db:create is being done . I have not seen a specific way in rails so far but i know this can be done using mysql scripts

like image 958
Bearish_Boring_dude Avatar asked Jun 17 '13 14:06

Bearish_Boring_dude


2 Answers

Here is a method that checks if the database already exists:

def database_exists?   ActiveRecord::Base.connection rescue ActiveRecord::NoDatabaseError   false else   true end 

References

  • ActiveRecord::Base.connection
  • ActiveRecord::NoDatabaseError
like image 200
Dwayne Crooks Avatar answered Sep 28 '22 03:09

Dwayne Crooks


I made a rake task that expands on some of the previous answers. I use this a lot in a Vagrant+Docker setup, so I can very easily issue a single command and either create a new database or issue a migrate to the current database. I use a branched database paradigm for development. I constantly need to seed a new database or update my existing one.

In lib/tasks/db_exists.rake:

namespace :db do
  desc "Checks to see if the database exists"
  task :exists do
    begin
      Rake::Task['environment'].invoke
      ActiveRecord::Base.connection
    rescue
      exit 1
    else
      exit 0
    end
  end
end

So now I can run a simple bash command:

rake db:exists && rake db:migrate || rake db:setup

Which I have then further automated into a Makefile (trimmed for brevity):

.PHONY database
database:
        rake db:exists && rake db:migrate || rake db:setup

Translates into:

make database

For all of my local database needs.

like image 40
penguincoder Avatar answered Sep 28 '22 02:09

penguincoder