J B
J B

Reputation: 400

Why can't I successfully use rake db:drop or rake db:purge?

Commands that work:

Commands that don't:

If I use db:rollback enough times (or with STEP), my databases drop successfully, but not when I use db:drop / db:drop:all. db:migrate:reset and db:purge leave all the data untouched. Running with trace, watching development.log, system logs and watching DB queries via the DB monitor (no SQL queries appear to run for those commands.) No errors, either.

Running:

Upvotes: 3

Views: 2593

Answers (3)

Mirror318
Mirror318

Reputation: 12663

You can't drop a PG database if a connection exists.

Unless you use this magic:

# config/initializers/postgresql_database_tasks.rb
module ActiveRecord
  module Tasks
    class PostgreSQLDatabaseTasks
      def drop
        establish_master_connection
        connection.select_all "select pg_terminate_backend(pg_stat_activity.pid) from pg_stat_activity where datname='#{configuration['database']}' AND state='idle';"
        connection.drop_database configuration['database']
      end
    end
  end
end

put that in your intializers and run this command:

rake environment db:drop

The environment argument makes rake check the initializers.

Please note that with Rails >= 6, you must replace configuration['database'] with configuration_hash[:database]

Upvotes: 3

ethaning
ethaning

Reputation: 436

If you have a backup of your db, you can reset your db using pg_restore:

pg_restore -U db_user -d db_name -h db_host .path/to/db_dump

This will reset your db with the contents of the backup.

Upvotes: 0

Giron
Giron

Reputation: 370

I had the same problem as you and this answer helped me to figure it out. You were probably editing some migration by hand and that caused this problem. In the end I had to drop all the tables by hand, that it worked. But it could be enough to just drop the schema_migrations table, where rails stores already run migrations. So try to drop all the tables if you can afford it or just drop the schema_migrations table.

EDIT: Unfortunately, It still doesn't work, dropping by hand solved just the recreation of schema.rb, but the db:drop is still not run. So the problem still persist.

Upvotes: 0

Related Questions