When using multiple branches that have slightly different db schemas - I have found myself needing to recreate my local development and test db fairly often.

For example when running rails db:reset often I get an error message like this:

PG::ObjectInUse: ERROR:  database "app_test" is being accessed by other users
DETAIL:  There is 1 other session using the database.
Couldn't drop database 'app_test'
rails aborted!
ActiveRecord::StatementInvalid: PG::ObjectInUse: ERROR:  database "app_test" is being accessed by other users
DETAIL:  There is 1 other session using the database.


Caused by:
PG::ObjectInUse: ERROR:  database "app_test" is being accessed by other users
DETAIL:  There is 1 other session using the database.

Which is easy enough to fix (by killing the postgres sessions) - but I’d prefer not to have to manually do that ever, as I need not care about any sessions that are attached.

There is a super simple monkey patch that I’ve added to ensure that I can always kill the db:

# config/initializers/monkey_patch_activerecord.rb
class ActiveRecord::Tasks::PostgreSQLDatabaseTasks
  def drop
    establish_master_connection
    connection.execute "DROP DATABASE IF EXISTS \"#{db_config.database}\" WITH (FORCE)"
  end
end

The important bit above, is the WITH (FORCE) – of course :)