简体   繁体   English

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

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

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

I would like to check if a database already exists before a db:create is being done .我想在 db:create 完成之前检查数据库是否已经存在。 I have not seen a specific way in rails so far but i know this can be done using mysql scripts到目前为止,我还没有在 Rails 中看到具体的方法,但我知道这可以使用 mysql 脚本来完成

Here is a method that checks if the database already exists:这是一个检查数据库是否已经存在的方法:

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

References参考

I made a rake task that expands on some of the previous answers.我做了一个 rake 任务,扩展了之前的一些答案。 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.我在 Vagrant+Docker 设置中经常使用它,因此我可以非常轻松地发出单个命令,然后创建新数据库或发出迁移到当前数据库。 I use a branched database paradigm for development.我使用分支数据库范例进行开发。 I constantly need to seed a new database or update my existing one.我经常需要播种一个新数据库或更新我现有的数据库。

In lib/tasks/db_exists.rake:在 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

So now I can run a simple bash command:所以现在我可以运行一个简单的 bash 命令:

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

Which I have then further automated into a Makefile (trimmed for brevity):然后我将其进一步自动化为 Makefile(为简洁起见):

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

Translates into:翻译成:

make database

For all of my local database needs.满足我所有的本地数据库需求。

You can also count on the fact that rake db:migrate:status returns an error if the database does not yet exist.如果数据库尚不存在,您还可以依靠rake db:migrate:status返回错误这一事实。

I'm using something like this in my scripts:我在我的脚本中使用这样的东西:

(rake db:migrate:status 2>/dev/null || rake db:setup) && rake db:migrate

(Inspired by [penguincoder] (灵感来自 [penguincoder]

Here are some bash scripts I made for this purpose:以下是我为此目的制作的一些 bash 脚本:

Postgres 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 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

These check for the presence of the schema_migrations table to determine whether rake db:setup has been run previously.这些检查schema_migrations表的存在以确定之前是否运行过rake db:setup

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

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

Rails 6 now has a rails db:prepare task. Rails 6 现在有一个rails db:prepare任务。

db:prepare will run db:migrate . db:prepare将运行db:migrate If db:migrate fails, then db:create , db:seed , followed by db:migrate are run.如果db:migrate失败,则运行db:createdb:seed ,然后运行db:migrate

See all rails tasks with rails --tasks使用rails --tasks查看所有 rails 任务

...
rails db:exists                             # Checks to see if the database exists
...
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)
...

NOTE: db:setup will remove any data currently in the database.注意: db:setup将删除数据库中当前的所有数据。 See Joshua Pinters's comment .Joshua Pinters 的评论

TRY THIS尝试这个

 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

Here is what I use to check the state of the DB:这是我用来检查数据库状态的内容:

if db_version=$(bundle exec rake db:version 2>/dev/null)
then
    if [ "$db_version" = "Current version: 0" ]; then
        echo "DB is empty"
    else
        echo "DB exists"
    fi
else
    echo "DB does not exist"
fi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在保存到数据库之前检查记录是否存在-Rails,Twitter,ActiveRecord - check if record exists before saving to db - Rails, Twitter, ActiveRecord 通过“ rake db:setup”破坏了数据库? (RoR) - ruined database through 'rake db:setup'? (RoR) 成功运行 rake db:create 后,docker 中的 Rails 应用程序返回数据库不存在 - Rails app in docker returns database does not exists after successfully running rake db:create Rails rake db:迁移最近创建的数据库 - Rails rake db:migrate of a recently created database Rails - rake db:重置不清除我的数据库 - Rails - rake db:reset not clearing my database Rails 3.1.0:在进行rake db:migrate的同时运行插入脚本 - Rails 3.1.0: Run Insert Script while doing rake db:migrate 做heroku rake db时出现问题:迁移到rails应用 - problem when doing heroku rake db:migrate to rails app 打开Rails控制台或执行rake db:create时出错 - error while open rails console or while doing rake db:create 如何在使用devise rails 5题词之前检查用户是否存在? - How to check if user exists before inscription with devise rails 5? 在rails3中创建新记录之前如何检查记录是否存在? - How to check if a record exists before creating a new one in rails3?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM