如何在执行rake db:setup之前检查rails中是否存在数据库

时间:2013-06-17 14:32:05

标签: ruby-on-rails ruby-on-rails-3

如何在执行rake db:setup?

之前检查数据库是否存在于rails中

我想在db:create完成之前检查数据库是否已经存在。到目前为止,我还没有在rails中看到过具体的方法,但我知道这可以使用mysql脚本完成

8 个答案:

答案 0 :(得分:20)

以下是检查数据库是否已存在的方法:

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

<强>参考

答案 1 :(得分:18)

我做了一个rake任务,扩展了之前的一些答案。我在Vagrant + Docker设置中经常使用它,因此我可以非常轻松地发出单个命令并创建新数据库或发布到当前数据库的迁移。我使用branched database范例进行开发。我经常需要播种新数据库或更新现有数据库。

在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

所以现在我可以运行一个简单的bash命令:

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

然后我进一步自动化为Makefile(为简洁而修剪):

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

转换为:

make database

满足我所有的本地数据库需求。

答案 2 :(得分:8)

如果数据库尚不存在,您还可以指望rake db:migrate返回错误。

我在我的脚本中使用了类似的东西:

rake db:migrate 2>/dev/null || rake db:setup

(灵感来自penguincoder

答案 3 :(得分:7)

以下是我为此目的制作的一些bash脚本:

的Postgres

if echo "\c $PGDATABASE; \dt" | psql | grep schema_migrations 2>&1 >/dev/null
then
   bundle exec rake db:migrate
else
   bundle exec rake db:setup
fi

Mysql的

 if echo "use $MYSQLDATABASE; show tables" | mysql | grep schema_migrations 2>&1 > /dev/null
 then
     bundle exec rake db:migrate
 else
     bundle exec rake db:setup
 fi

这些检查是否存在schema_migrations表,以确定先前是否已运行rake db:setup

答案 4 :(得分:2)

如果数据库不存在或连接不活动(至少在Rails 4+中),则返回false。

::ActiveRecord::Base.connection_pool.with_connection(&:active?) rescue false

答案 5 :(得分:1)

Rails 6 现在有一个 rails db:prepare 任务。

db:prepare 将运行 db:migrate。如果 db:migrate 失败,则运行 db:createdb:seeddb:migrate

使用 rails --tasks

查看所有 rails 任务
rails db:prepare                            # Runs setup if database does not exist, or runs migrations if it does
...
rails db:setup                              # Creates the database, loads the schema, and initializes with the seed data (use db:reset to also drop the database first)
...

答案 6 :(得分:0)

尝试

 IF EXISTS 
       (
         SELECT name FROM master.dbo.sysdatabases 
        WHERE name = N'New_Database'
        )
    BEGIN
        SELECT 'Database Name already Exist' AS Message
    END
    ELSE
    BEGIN
        CREATE DATABASE [New_Database]
        SELECT 'New Database is Created'
    END

答案 7 :(得分:0)

以下是我用来检查数据库状态的信息:

<dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.5</version>
</dependency>