ruby-on-rails - 运行 rake db :drop without failure if database doesn't exist

标签 ruby-on-rails exception rake rake-task

This comment说:

db:drop can run without failure when db does not exist



这正是我所需要的:我需要运行 db:drop 但如果数据库不存在则不抛出异常或停止我的整个过程,如果数据库存在则删除该数据库或什么都不做。

我怎样才能做到这一点?我怎么知道db:drop如果数据库不存在,不要破坏我的生活?

这是我遇到问题的代码(它有帮助):
namespace :db do
  task import: :environment do
    Rake::Task["db:drop"].invoke # If the database doesn't already exist, the whole import process terminates!
    Rake::Task["db:create"].invoke
    Rake::Task["db:migrate"].invoke
    database_config = Rails.configuration.database_configuration[Rails.env]
    system "psql --username=#{database_config['username']} #{database_config['database']} < PostgreSQL.sql"
  end
end

最佳答案

为什么不能进行简单的异常处理

namespace :db do
  task import: :environment do
    begin
      Rake::Task["db:drop"].invoke # If the database doesn't already exist, the whole import process terminates!
      Rake::Task["db:create"].invoke
      Rake::Task["db:migrate"].invoke
      database_config = Rails.configuration.database_configuration[Rails.env]
      system "psql --username=#{database_config['username']} #{database_config['database']} < PostgreSQL.sql"
   rescue Exception => e
     p "The Exception is #{e.message}"
   end
  end
end

关于ruby-on-rails - 运行 rake db :drop without failure if database doesn't exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16532772/

相关文章:

c# - 检查字符串是否可以被解析的最快方法

c# - 如何在 C# 中创建自定义异常

java - 捕获可扔物的好理由是什么?

ruby-on-rails - rails : Make this rake task aware that it is in the test environment

ruby-on-rails - Sidekiq 是否按照将作业发送给 worker 的顺序执行作业?

javascript - 如何将 ruby​​ 代码值添加到 disqus javascript 变量

ruby-on-rails - 如何统计 Ruby on Rails App 中的记录?

mysql - Ruby on Rails Errno::EPIPE 断管

ruby-on-rails - rails 4 : How to set cookies in redirect?

ruby-on-rails - 如何将多个模式加载到 Rails 引擎或应用程序中?