Rails + Postgres drop error: database is being accessed by other users

前端 未结 16 2138
时光取名叫无心
时光取名叫无心 2020-12-04 06:26

I have a rails application running over Postgres.

I have two servers: one for testing and the other for production.

Very often I need to clone the production

16条回答
  •  借酒劲吻你
    2020-12-04 06:57

    You can simply monkeypatch the ActiveRecord code that does the dropping.

    For Rails 3.x:

    # lib/tasks/databases.rake
    def drop_database(config)
      raise 'Only for Postgres...' unless config['adapter'] == 'postgresql'
      Rake::Task['environment'].invoke
      ActiveRecord::Base.connection.select_all "select pg_terminate_backend(pg_stat_activity.pid) from pg_stat_activity where datname='#{config['database']}' AND state='idle';"
      ActiveRecord::Base.establish_connection config.merge('database' => 'postgres', 'schema_search_path' => 'public')
      ActiveRecord::Base.connection.drop_database config['database']
    end
    

    For Rails 4.x:

    # 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
    

    (from: http://www.krautcomputing.com/blog/2014/01/10/how-to-drop-your-postgres-database-with-rails-4/)

提交回复
热议问题