Kill a postgresql session/connection

前端 未结 20 1819
暖寄归人
暖寄归人 2020-11-28 00:11

How can I kill all my postgresql connections?

I\'m trying a rake db:drop but I get:

ERROR:  database \"database_name\" is being accessed         


        
相关标签:
20条回答
  • 2020-11-28 00:53

    MacOS, if postgresql was installed with brew:

    brew services restart postgresql
    

    Source: Kill a postgresql session/connection

    0 讨论(0)
  • 2020-11-28 00:54

    I use the following rake task to override the Rails drop_database method.

    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
    

    Edit: This is for Postgresql 9.2+

    0 讨论(0)
提交回复
热议问题