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

前端 未结 16 2084
时光取名叫无心
时光取名叫无心 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 07:13

    Solution

    Bash script

    ENV=development
    
    # restart postgresql
    brew services restart postgresql
    
    # get name of the db from rails app
    RAILS_CONSOLE_COMMAND="bundle exec rails c -e $ENV"
    DB_NAME=$(echo 'ActiveRecord::Base.connection_config[:database]' | $RAILS_CONSOLE_COMMAND | tail -2 | tr -d '\"')
    
    # delete all connections to $DB_NAME
    for pid in $(ps -ef | grep $DB_NAME | awk {'print$2'})
    do
       kill -9 $pid
    done
    
    # drop db
    DISABLE_DATABASE_ENVIRONMENT_CHECK=1 RAILS_ENV=$ENV bundle exec rails db:drop:_unsafe
    
    0 讨论(0)
  • 2020-12-04 07:15

    Rails is likely connecting to the database to drop it but when you log in via phppgadmin it is logging in via the template1 or postgres database, thus you are not affected by it.

    0 讨论(0)
  • 2020-12-04 07:17

    Let your application close the connection when it's done. PostgreSQL doesn't keep connections open , it's the application keeping the connection.

    0 讨论(0)
  • 2020-12-04 07:17

    This worked for me (rails 6): rake db:drop:_unsafe

    I think we had something in our codebase that initiated a db connection before the rake task attempted to drop it.

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