当前位置 : 主页 > 编程语言 > ruby >

ruby-on-rails – 强制$rake db:重置尽管其他用户使用Postgres

来源:互联网 收集:自由互联 发布时间:2021-06-23
参见英文答案 Rails + Postgres drop error: database is being accessed by other users13个 有没有办法强制数据库重置,即使Postgres有其他用户使用它.当我尝试$rake db时,我几乎总是遇到这个错误:reset:
参见英文答案 > Rails + Postgres drop error: database is being accessed by other users                                    13个
有没有办法强制数据库重置,即使Postgres有其他用户使用它.当我尝试$rake db时,我几乎总是遇到这个错误:reset:

Couldn't drop example_database_name :
 #<ActiveRecord::StatementInvalid: PG::Error: ERROR:  database "example_database_name" is being accessed by other users DETAIL: 
 There are 2 other session(s) using the database.
如果您发现自己在开发中使用了db:reset,那么将它放在lib / database.rake文件中.

require 'active_record/connection_adapters/postgresql_adapter'
module ActiveRecord
  module ConnectionAdapters
    class PostgreSQLAdapter < AbstractAdapter
      def drop_database(name)
        raise "Nah, 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

显然只是设计用于非生产数据库.它将导致所有现有数据库连接被切断,因此如果unicorn / passenger / pow正在汇集数据库连接,则下一页加载可能会出错.如果发生这种情况,简单的页面刷新将导致服务器打开一个新连接,一切都会很好.

网友评论