清除或重新创建 Ruby on Rails 数据库

发布于 2024-10-01 11:45:23 字数 122 浏览 4 评论 0原文

我有一个充满数据的开发 Ruby on Rails 数据库。我想删除所有内容并重建数据库。我正在考虑使用类似的东西:

rake db:recreate

这可能吗?

I have a dev Ruby on Rails database full of data. I want to delete everything and rebuild the database. I'm thinking of using something like:

rake db:recreate

Is this possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(24

青瓷清茶倾城歌 2024-10-08 11:45:24

TL;DR - 我在开发过程中使用这个 rake 脚本来清除所有内容,包括架构文件,然后直接从迁移脚本重建。它同时重建 devtest 数据库。这是我发现的保证一切都按照我的预期进行的唯一方法。使用它多年没有任何问题。

# lib/tasks/db_rebuild.rake

require 'fileutils'

namespace :db do
  desc "Create DB if it doesn't exist, then migrate and seed"
  task :build do
    Rake::Task["db:create"].invoke
    Rake::Task["db:migrate"].invoke
    Rake::Task["db:seed"].invoke
  end

  desc "Drop database and rebuild directly from migrations (ignores schema.rb)"
  task :rebuild do
    raise "Task not permitted in production." if ENV["RAILS_ENV"] == "production"

    puts "*** Deleting schema.rb"
    system "rm -f #{Rails.root.join("db", "schema.rb")}"

    puts "*** Deleting seed lock files"
    system "rm -f #{Rails.root.join("db", ".loaded*")}"

    puts "*** Recreate #{ENV['RAILS_ENV']} database"
    begin
      Rake::Task['environment'].invoke
      ActiveRecord::Base.connection
    rescue ActiveRecord::NoDatabaseError
      # database doesn't exist yet, just create it.
      Rake::Task["db:build"].invoke
    rescue Exception => e
      raise e
    else
      Rake::Task["db:environment:set"].invoke
      # https://github.com/rails/rails/issues/26319#issuecomment-244015760
      # ENV["DISABLE_DATABASE_ENVIRONMENT_CHECK"] = '1'
      Rake::Task["db:drop"].invoke
      Rake::Task["db:build"].invoke
    end
    Rake::Task["db:retest"].invoke
  end

  desc "Recreate the test DB"
  task :retest do
    system("rake db:drop db:build RAILS_ENV=test")
  end
end

基本原理 - 所有提供的解决方案的问题在于 Rails 提供的本机 Rake 任务依赖于 schema.rb。当我进行大量数据建模时,我直接对迁移文件进行更改;只有在它们被提交到上游之后,我们才会将它们视为不可变的。但是,如果我对迁移文件进行更改,它们不会反映在 schema.rb 中。

另一个问题是开发环境和测试环境之间的区别。 Rails 数据库任务独立处理它们,但根据我的经验,devtest 数据库应始终保持奇偶性,这意味着我在开发时必须运行大量重复的数据库清理。

TL;DR - I use this rake script during development to blow away everything, including the schema file, then rebuild directly from migration scripts. It rebuilds both dev and test databases simultaneously. It's the only way I've found to guarantee everything lines up the way I expect. Been using it for years without a problem.

# lib/tasks/db_rebuild.rake

require 'fileutils'

namespace :db do
  desc "Create DB if it doesn't exist, then migrate and seed"
  task :build do
    Rake::Task["db:create"].invoke
    Rake::Task["db:migrate"].invoke
    Rake::Task["db:seed"].invoke
  end

  desc "Drop database and rebuild directly from migrations (ignores schema.rb)"
  task :rebuild do
    raise "Task not permitted in production." if ENV["RAILS_ENV"] == "production"

    puts "*** Deleting schema.rb"
    system "rm -f #{Rails.root.join("db", "schema.rb")}"

    puts "*** Deleting seed lock files"
    system "rm -f #{Rails.root.join("db", ".loaded*")}"

    puts "*** Recreate #{ENV['RAILS_ENV']} database"
    begin
      Rake::Task['environment'].invoke
      ActiveRecord::Base.connection
    rescue ActiveRecord::NoDatabaseError
      # database doesn't exist yet, just create it.
      Rake::Task["db:build"].invoke
    rescue Exception => e
      raise e
    else
      Rake::Task["db:environment:set"].invoke
      # https://github.com/rails/rails/issues/26319#issuecomment-244015760
      # ENV["DISABLE_DATABASE_ENVIRONMENT_CHECK"] = '1'
      Rake::Task["db:drop"].invoke
      Rake::Task["db:build"].invoke
    end
    Rake::Task["db:retest"].invoke
  end

  desc "Recreate the test DB"
  task :retest do
    system("rake db:drop db:build RAILS_ENV=test")
  end
end

Rationale - The problem with all the provided solutions is that native Rake tasks provided by Rails rely on schema.rb. When I am doing heavy data modeling, I make changes directly to the migration files; only after they've been committed upstream do we treat them as immutable. But if I make changes to the migration file, they aren't reflected in schema.rb.

The other problem is the distinction between dev and test environments. Rails db tasks handle them independently, but in my experience dev and test databases should always maintain parity, which means I had to run lots of duplicative database cleanup when developing.

飘落散花 2024-10-08 11:45:24

我自己请注意,如果您只想清除数据,

$ bin/rails db:truncate_all  

它将从表中删除数据。我喜欢 rails 前缀,因为我通常通过以下方式运行 db 命令

rails db:migrate
rails db:rollback 

Note for myself if you want to just clear data

$ bin/rails db:truncate_all  

it will delete data from tables. I like rails prefix because I usually run db command via

rails db:migrate
rails db:rollback 
初相遇 2024-10-08 11:45:23

我知道有两种方法可以做到这一点:

这将重置您的数据库并重新加载当前架构:

rake db:reset db:migrate

这将销毁您的数据库,然后创建它,然后迁移您当前的架构:

rake db:drop db:create db:migrate

在这两种情况下,所有数据都将丢失。

I know two ways to do this:

This will reset your database and reload your current schema with all:

rake db:reset db:migrate

This will destroy your db and then create it and then migrate your current schema:

rake db:drop db:create db:migrate

All data will be lost in both scenarios.

缪败 2024-10-08 11:45:23

在 Rails 4 上,所需要做的就是

$ rake db:schema:load

删除数据库上的全部内容并从 schema.rb 文件重新创建架构,而不必一一应用所有迁移。

On Rails 4, all needed is

$ rake db:schema:load

That would delete the entire contents on your DB and recreate the schema from your schema.rb file, without having to apply all migrations one by one.

凉月流沐 2024-10-08 11:45:23

我在终端中使用以下一种班轮。

$ rake db:drop && rake db:create && rake db:migrate && rake db:schema:dump && rake db:test:prepare

我把它作为 shell 别名并将其命名为 remigrate

现在,您可以轻松地“链接”Rails 任务:

$ rake db:drop db:create db:migrate db:schema:dump db:test:prepare # db:test:prepare no longer available since Rails 4.1.0.rc1+

I use the following one liner in Terminal.

$ rake db:drop && rake db:create && rake db:migrate && rake db:schema:dump && rake db:test:prepare

I put this as a shell alias and named it remigrate

By now, you can easily "chain" Rails tasks:

$ rake db:drop db:create db:migrate db:schema:dump db:test:prepare # db:test:prepare no longer available since Rails 4.1.0.rc1+
2024-10-08 11:45:23

更新:在 Rails 5 中,可以通过以下命令访问此命令:

rails db:purge db:create db:migrate RAILS_ENV=test


从最新的 Rails 4.2 版本开始,您现在可以运行:

rake db:purge 

来源:< a href="https://github.com/rails/rails/commit/e2f232aba15937a4b9d14bd91e0392c6d55be58d" rel="noreferrer">commit

# desc "Empty the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all to drop all databases in the config). Without RAILS_ENV it defaults to purging the development and test databases."
  task :purge => [:load_config] do
    ActiveRecord::Tasks::DatabaseTasks.purge_current
  end

可以像上面提到的那样一起使用:

rake db:purge db:create db:migrate RAILS_ENV=test

Update: In Rails 5, this command will be accessible through this command:

rails db:purge db:create db:migrate RAILS_ENV=test


As of the newest rails 4.2 release you can now run:

rake db:purge 

Source: commit

# desc "Empty the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all to drop all databases in the config). Without RAILS_ENV it defaults to purging the development and test databases."
  task :purge => [:load_config] do
    ActiveRecord::Tasks::DatabaseTasks.purge_current
  end

It can be used together like mentioned above:

rake db:purge db:create db:migrate RAILS_ENV=test
绳情 2024-10-08 11:45:23

根据您的需求,您可以使用...

rake db:create

...从 config/database.yml 从头开始​​构建数据库,或者...

rake db:schema:load

...从您的 schema.rb 文件从头开始构建数据库。

Depending on what you're wanting, you can use…

rake db:create

…to build the database from scratch from config/database.yml, or…

rake db:schema:load

…to build the database from scratch from your schema.rb file.

风吹过旳痕迹 2024-10-08 11:45:23

从命令行运行

rake db:migrate:reset

From the command line run

rake db:migrate:reset
是你 2024-10-08 11:45:23

在 Rails 6 中,有一种重置数据库并再次播种的便捷方法:

rails db:seed:replant # Truncates tables of each database for current environment and loads the seeds

https://weblog.rubyonrails.org/2019/3/15/this-week-in-rails-security-fixes-bulk-insert- and-upsert-seeds-replanting/

In Rails 6 there is a convenient way for resetting DB and planting seeds again:

rails db:seed:replant # Truncates tables of each database for current environment and loads the seeds

https://weblog.rubyonrails.org/2019/3/15/this-week-in-rails-security-fixes-bulk-insert-and-upsert-seeds-replanting/

邮友 2024-10-08 11:45:23

使用就像

rake db:drop db:create db:migrate db:seed

“全部在一行”一样。由于环境不会一次又一次地重新加载,因此速度更快。

db:drop - 将删除数据库。

db:create - 将创建数据库(主机/db/密码将从 config/database.yml 中获取)

db:migrate - 将运行来自目录(db/migration/.rb)*的现有迁移。

db:seed - 将从目录(db/migration/seed.rb)运行种子数据。

我通常更喜欢:

rake db:reset

一次完成所有操作。

干杯!

Use like

rake db:drop db:create db:migrate db:seed

All in one line. This is faster since the environment doesn't get reloaded again and again.

db:drop - will drop database.

db:create - will create database (host/db/password will be taken from config/database.yml)

db:migrate - will run existing migrations from directory (db/migration/.rb)*.

db:seed - will run seed data possible from directory (db/migration/seed.rb)..

I usually prefer:

rake db:reset

to do all at once.

Cheers!

黑凤梨 2024-10-08 11:45:23

只需执行以下步骤顺序:删除数据库,然后重新创建数据库,迁移数据,如果您有种子,则播种数据库:

rake db:drop db:create db:migrate db:seed

由于 rake 的默认环境是 开发,如果您在规范测试中看到异常,您应该为测试环境重新创建数据库,如下所示:

RAILS_ENV=test rake db:drop db:create db:migrate

在大多数情况下,测试数据库是在测试过程中播种的,因此不需要传递 db:seed 任务操作。否则,您应该准备数据库:

rake db:test:prepare

或者

RAILS_ENV=test rake db:seed

此外,要使用重新创建任务,您可以将以下代码添加到Rakefile中:

namespace :db do
   task :recreate => [ :drop, :create, :migrate ] do
      if ENV[ 'RAILS_ENV' ] !~ /test|cucumber/
         Rake::Task[ 'db:seed' ].invoke
      end
   end
end

然后发出:

rake db:recreate

Just issue the sequence of the steps: drop the database, then re-create it again, migrate data, and if you have seeds, sow the database:

rake db:drop db:create db:migrate db:seed

Since the default environment for rake is development, in case if you see the exception in spec tests, you should re-create db for the test environment as follows:

RAILS_ENV=test rake db:drop db:create db:migrate

In most cases the test database is being sowed during the test procedures, so db:seed task action isn't required to be passed. Otherwise, you shall to prepare the database:

rake db:test:prepare

or

RAILS_ENV=test rake db:seed

Additionally, to use the recreate task you can add into Rakefile the following code:

namespace :db do
   task :recreate => [ :drop, :create, :migrate ] do
      if ENV[ 'RAILS_ENV' ] !~ /test|cucumber/
         Rake::Task[ 'db:seed' ].invoke
      end
   end
end

Then issue:

rake db:recreate
迷爱 2024-10-08 11:45:23

您可以手动执行以下操作:

rake db:drop
rake db:create
rake db:migrate

或者只是 rake db:reset,这将运行上述步骤,但也会运行您的 db/seeds.rb 文件。

另一个细微差别是,rake db:reset 直接从 schema.rb 文件加载,而不是再次运行所有迁移文件。

在所有情况下,您的数据都会被破坏。

You can manually do:

rake db:drop
rake db:create
rake db:migrate

Or just rake db:reset, which will run the above steps but will also run your db/seeds.rb file.

An added nuance is that rake db:reset loads directly from your schema.rb file as opposed to running all the migrations files again.

You data gets blown away in all cases.

深海蓝天 2024-10-08 11:45:23

您可以使用以下命令行:

rake db:drop db:create db:migrate db:seed db:test:clone

You can use this following command line:

rake db:drop db:create db:migrate db:seed db:test:clone
酷到爆炸 2024-10-08 11:45:23

要删除特定数据库,您可以在 Rails 控制台上执行此操作:

$rails console
Loading development environment
1.9.3 > ActiveRecord::Migration.drop_table(:<table_name>)
1.9.3 > exit

然后再次迁移数据库

$bundle exec rake db:migrate 

To drop a particular database, you can do this on rails console:

$rails console
Loading development environment
1.9.3 > ActiveRecord::Migration.drop_table(:<table_name>)
1.9.3 > exit

And then migrate DB again

$bundle exec rake db:migrate 
野の 2024-10-08 11:45:23

在 Rails 4.2 上,删除所有数据但保留数据库

$ bin/rake db:purge && bin/rake db:schema:load

https ://github.com/rails/rails/blob/4-2-stable/activerecord/CHANGELOG.md

On rails 4.2, to remove all data but preserve the database

$ bin/rake db:purge && bin/rake db:schema:load

https://github.com/rails/rails/blob/4-2-stable/activerecord/CHANGELOG.md

欢烬 2024-10-08 11:45:23

3 个选项,相同结果:

1. 所有步骤:

  $ rake db:drop           # deletes the database for the current env
  $ rake db:create         # creates the database for the current env
  $ rake db:schema:load    # loads the schema already generated from schema.rb / erases data
  $ rake db:seed           # seed with initial data

2. 重置:

  $ rake db:reset          # drop / schema:load / seed

3. 迁移:重置:

  $ rake db:migrate:reset  # drop / create / migrate
  $ rake db:seed

备注:

  • 如果使用 schema:load 比执行所有迁移更快,但结果相同。
  • 所有数据都将丢失。
  • 您可以在一条线上运行多个耙子。
  • 与导轨 3 配合使用。

3 options, same result:

1. All steps:

  $ rake db:drop           # deletes the database for the current env
  $ rake db:create         # creates the database for the current env
  $ rake db:schema:load    # loads the schema already generated from schema.rb / erases data
  $ rake db:seed           # seed with initial data

2. Reset:

  $ rake db:reset          # drop / schema:load / seed

3. Migrate:reset:

  $ rake db:migrate:reset  # drop / create / migrate
  $ rake db:seed

Notes:

  • If schema:load is used is faster than doing all migrations, but same result.
  • All data will be lost.
  • You can run multiple rakes in one line.
  • Works with rails 3.
落叶缤纷 2024-10-08 11:45:23

您可以使用
db:reset - 用于运行 db:drop 和 db:setup 或
db:migrate:reset - 运行 db:drop、db:create 和 db:migrate。

依赖于您想要使用现有的 schema.rb

You can use
db:reset - for run db:drop and db:setup or
db:migrate:reset - which runs db:drop, db:create and db:migrate.

dependent at you want to use exist schema.rb

终止放荡 2024-10-08 11:45:23

根据 Rails 指南,应该使用这个衬垫,因为它会加载从 schema.rb 而不是逐一重新加载迁移文件:

rake db:reset

According to Rails guide, this one liner should be used because it would load from the schema.rb instead of reloading the migration files one by one:

rake db:reset
此刻的回忆 2024-10-08 11:45:23

因为在开发中,您总是想要重新创建数据库,您可以像这样在 lib/tasks 文件夹中定义一个 rake 任务。

  namespace :db do
      task :all => [:environment, :drop, :create, :migrate] do
   end 
end

在终端中,您将运行

rake db:all

它将重建您的数据库

Because in development , you will always want to recreate the database,you can define a rake task in your lib/tasks folder like that.

  namespace :db do
      task :all => [:environment, :drop, :create, :migrate] do
   end 
end

and in terminal you will run

rake db:all

it will rebuild your database

作妖 2024-10-08 11:45:23

我认为运行此命令的最佳方法:

**rake db:reset** it does db:drop, db:setup
 rake db:setup does db:create, db:schema:load, db:seed

I think the best way to run this command:

**rake db:reset** it does db:drop, db:setup
 rake db:setup does db:create, db:schema:load, db:seed
无敌元气妹 2024-10-08 11:45:23

只需运行

rake db:setup ,

如果您使用一些数据创建了种子文件,它将删除数据库,创建新数据库并从种子填充数据库。

Simply you can run

rake db:setup

It will drop database, create new database and populate db from seed if you created seed file with some data.

余厌 2024-10-08 11:45:23

我使用:

  • rails db:drop 来删除数据库。
  • rails db:create 基于 config/database.yml 创建数据库

前面的命令可以替换为 rails db:reset

不要忘记运行 rails db:migrate 来运行迁移。

I use:

  • rails db:drop to delete the databases.
  • rails db:create to create the databases based on config/database.yml

The previous commands may be replaced with rails db:reset.

Don't forget to run rails db:migrate to run the migrations.

清欢 2024-10-08 11:45:23

RAILS 7 及更高版本
只需运行:

rails db:reset

注意:这将删除测试、开发数据库中的数据,然后加载 seeds.rb(如果有)。它将按此顺序运行

db:drop => db:setup => db:seed 

希望这有帮助!

RAILS 7 and above
Just simply run:

rails db:reset

Note: This would delete the data in test, development database and then load the seeds.rb if any. It would run in this order

db:drop => db:setup => db:seed 

Hope this helps!

汐鸠 2024-10-08 11:45:23

今天我对我的 Rails 架构做了相当多的更改。我意识到我需要在层次结构中添加两个模型,并删除其他一些模型。模型和控制器需要进行许多小的更改。

我添加了两个新模型并创建了它们,使用:

rake db:migrate

然后我编辑了 schema.rb 文件。我手动删除了不再需要的旧模型,根据需要更改了外键字段,然后稍微重新排序以使其更清晰。我删除了所有迁移,然后通过以下方式重新运行构建:

rake db:reset

它运行得很好。当然,所有数据都必须重新加载。 Rails 意识到迁移已被删除并重置了高水位线:

-- assume_migrated_upto_version(20121026094813, ["/Users/sean/rails/f4/db/migrate"])

I've today made quite a few changes to my rails schema. I realised I needed an additional two models in a hierarchy and some others to be deleted. There were many little changes required to the models and controllers.

I added the two new models and created them, using:

rake db:migrate

Then I edited the schema.rb file. I manually removed the old models that were no longer required, changed the foreign key field as required and just reordered it a bit to make it clearer to me. I deleted all the migrations, and then re-ran the build via:

rake db:reset

It worked perfectly. All the data has to be reloaded, of course. Rails realised the migrations had been deleted and reset the high-water mark:

-- assume_migrated_upto_version(20121026094813, ["/Users/sean/rails/f4/db/migrate"])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文