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

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

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

这是一个检查数据库是否已存在的方法:

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

参考

  • 的ActiveRecord :: Base.connection
  • 的ActiveRecord :: NoDatabaseError

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

在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 

对于我所有的本地数据库需求。

以下是我为此目的制作的一些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

如果数据库尚不存在,您还可以依赖rake db:migrate返回错误的事实。

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

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

(灵感来自penguincoder )

试试这个

  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