How to know if DB exists from within Rake task

2019-07-24 18:15发布

问题:

How do i find out if the database exists from within a rake task?

that is, i'd like to do something like:

  task :drop_and_create => :environment do
    Rails.env = "development"
    if (db_exists?)
      Rake::Task["db:drop"].invoke
    end
    Rake::Task["db:create"].invoke
    #more stuff...
  end

how do i write the db_exists? condition?

回答1:

How about instead doing a begin/rescue:

task :drop_and_create => :environment do
    Rails.env = "development"
    if (db_exists?)
    begin
      Rake::Task["db:drop"].invoke

    rescue Exception => e
      logger.debug("Error:#{e}")
    Rake::Task["db:create"].invoke
    #more stuff...
  end


回答2:

  task :drop_and_create => :environment do
    Rails.env = "development"
    Rake::Task["db:reset"].invoke
    #more stuff...
  end