在执行 rake db:setup 之前如何检查数据库是否存在于 rails 中 [英] How to check if the database exists or not in rails before doing a rake db:setup

查看:31
本文介绍了在执行 rake db:setup 之前如何检查数据库是否存在于 rails 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我想在执行 db:create 之前检查数据库是否已经存在.到目前为止,我还没有在 Rails 中看到特定的方式,但我知道这可以使用 mysql 脚本来完成

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

推荐答案

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

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.

在 lib/tasks/db_exists.rake 中:

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

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

So now I can run a simple bash command:

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

然后我将其进一步自动化为 Makefile(为简洁起见进行了修剪):

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

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

翻译成:

make database

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

For all of my local database needs.

这篇关于在执行 rake db:setup 之前如何检查数据库是否存在于 rails 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆