Rails—how to drop a specific database? - ruby-on-rails

rake db:drop destroys everything, but I only want to drop specific db's.
I tried a parallel testing gem which created these databases: my_db_test2, my_db_test3, my_db_test4
How do I delete only those databases?

If you're using Postgres, you can use dropdb:
dropdb my_db_test2

You can specify environment while destroying databases.
bundle exec rake db:drop RAILS_ENV=test
Note: By default rake db:drop will drop all databases associated with the application.

Related

How to completely delete a DB on Ruby on Rails?

I have a small Ruby on Rails app, and I made a mistake creating a model and so on.
How can I fully delete its database? Not reseting migrations or dropping its tables, but to delete all db related files? (schema.rb, etc)
To drop database
rake db:drop
Then for creating database
rake db:create
For migrations
rake db:migrate
For seed
rake db:seed
Deleting these files will not remove the database from your system. You should never delete your schema.rb because it holds the structure of your database. (And not the database records themselves.) If you simply created a new model, Rails does not automatically create a database table (that's what migrations do).
If you still want to drop your entire database (the structure and data), this is the command you need (found when calling rake -T)
rake db:drop # Drops the database from DATABASE_URL or
# config/database.yml for the current RAILS_ENV
# (use db:drop:all to drop all databases)
By default, RAILS_ENV is not set. If you called rake db:drop during this state, all databases associated with this app will be dropped. In order to drop, say, only development:
export RAILS_ENV=development
rake db:drop
You can do the same with test and production environments.

Want to re-create table when running rake db:seed

I want to remove all tables and re-created the db when I run
rake db:create
The reason is the id's on the tables are not set to 1, so I figured i can just re-create the db if its possible, or call truncate.
rake db:reset
may be what you are looking for. or...
rake db:drop
rake db:create
Try rake db:reset (in Rails 3)
In Rails 2, maybe this will help: http://pivotallabs.com/users/alex/blog/articles/305-collapsing-migrations

How to revert all migrations at once in Ruby on Rails 3?

I tried to run:
rake db:migrate VERSION=0
It reverts all migrations except the last one.
Then I tried to run:
rake db:migrate:down VERSION=<timestamp_of_last_migration>
but it didn't revert either. Why ?
Is there a command that runs all down methods at once ?
If your database only related to this project, and you are trying to undo everything in your migrations, I'd simply drop the database, and then run rake db:create.
Then you have an empty database ready to go.
Or is there another reason you're trying to run the down scripts?
You could check this list.
Maybe this could help you
rake db:create[:all]: If :all not specified then create the database defined in config/database.yml for the current RAILS_ENV. If :all is specified then create all of the databases defined in config/database.yml.
rake db:fixtures:load: Load fixtures into the current environment's database. Load specific fixtures using FIXTURES=x,y
rake db:migrate [VERSION=n]: Migrate the database through scripts in db/migrate. Target specific version with VERSION=n
rake db:migrate:redo [STEP=n]: (2.0.2) Revert the database by rolling back "STEP" number of VERSIONS and re-applying migrations.
rake db:migrate:reset: (2.0.2) Drop the database, create it and then re-apply all migrations. The considerations outlined in the note to rake db:create apply.
rake db:reset: Drop and re-create database using db/schema.rb. The considerations outlined in the note to rake db:create apply.
rake db:rollback [STEP=N]: (2.0.2) Revert migration 1 or n STEPs back.
rake db:schema:dump: Create a db/schema.rb file that can be portably used against any DB supported by AR
rake db:schema:load: Load a schema.rb file into the database
rake db:sessions:clear: Clear the sessions table
rake db:sessions:create: Creates a sessions table for use with CGI::Session::ActiveRecordStore
rake db:structure:dump: Dump the database structure to a SQL file
rake db:test:clone: Recreate the test database from the current environment's database schema
rake db:test:clone_structure: Recreate the test databases from the development structure
rake db:test:prepare: Prepare the test database and load the schema
rake db:test:purge: Empty the test database
there is another way:
rake db:rollback STEP=100
this will revert last 100 migrations
taken from http://guides.rubyonrails.org/migrations.html#rolling-back
try:
rake db:migrate:down VERSION=<timestamp_of_first_migration>
this will run the self.down for your first migration, essentially wiping everything out. at least, it just did for me!

Purge or recreate a Ruby on Rails database

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?
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.
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.
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+
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
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.
From the command line run
rake db:migrate:reset
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/
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!
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
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.
You can use this following command line:
rake db:drop db:create db:migrate db:seed db:test:clone
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
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
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
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
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
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.
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
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.
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.
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"])
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.

Can rake db:create create tables in multiple databases?

Can I create tables in two databases using db:create? For example, can I have entries in database.yml for one_development and two_development and have both get created by rake db:create? I know rake db:create:all works -- I am just wondering if there is a way to segment what is created depending on the RAILS_ENV?
For one_development you can execute this command:
RAILS_ENV=one_development rake db:create
For two_development you can execute this command:
RAILS_ENV=two_development rake db:create
Redefine the rake task or create a new one, which runs rake db:create for two environments that you need.
It appears to do all the datasets automatically. See the source:
http://dev.rubyonrails.org/changeset/6849
It does not appear to uses RAILS_ENV like drop, etc.

Resources