LoginSignup
23
16

More than 5 years have passed since last update.

RailsでPostgreSQLを使ってるときに、rake db:resetが失敗する場合

Posted at

データの状態を見ようと、psqlで操作した時とか、セッションが残っていてリセット(DROP)出来なかったりする。

% rake db:reset                                                                                                                                                    PG::ObjectInUse: ERROR:  database "sample_development" is being accessed by other users
DETAIL:  There are 2 other sessions using the database.
: DROP DATABASE IF EXISTS "sample_development"

以下のようなRakeタスクをlib/taskの中に入れておく。

lib/tasks/database.rake
require 'active_record/connection_adapters/postgresql_adapter'
module ActiveRecord
  module ConnectionAdapters
    class PostgreSQLAdapter < AbstractAdapter
      def drop_database(name)
        raise "I won't drop the production database" if Rails.env.production?
        execute <<-SQL
          UPDATE pg_catalog.pg_database
          SET datallowconn=false WHERE datname='#{name}'
        SQL

        execute <<-SQL
          SELECT pg_terminate_backend(pg_stat_activity.pid)
          FROM pg_stat_activity
          WHERE pg_stat_activity.datname = '#{name}';
        SQL
        execute "DROP DATABASE IF EXISTS #{quote_table_name(name)}"
      end
    end
  end
end

これでrake db:resetができる。

イェア

23
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
16