[Solved]-Django can't drop database: psycopg2.OperationalError: cannot drop the currently open database

28šŸ‘

TL;DR

If you just want the solution, here it is.
Make sure that your Postgres server has a ā€œpostgresā€ database. You can check by connecting via psql, and running /list or /l. You can create the database by running: CREATE DATABASE postgres in psql.

Extended

Django prefers to not run ā€œinitialization queriesā€ (presumably things like creating the test database) from the ā€œdefaultā€ database specified in your DATABASES setting. This is presumed to be the production database, so it would be in Djangoā€™s best interests to not mess around there.

This is why at the beginning of the tests, this is shown (ignore my filesystem):

    /Users/dcgoss/Desktop/Pickle/PickleBackend/venv/lib/python3.4/site-packages/django/db/backends/postgresql/base.py:247: 
    RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed 
    (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the default database instead.
    RuntimeWarning

Django looks for a database named ā€œpostgresā€ on the host specified in your DATABASES settings, this is where it runs the queries to create and delete your test database. (Note: Django does not need the ā€œpostgresā€ database to be explicitly specified in your settings, it just looks for it on whatever database server is specified in your settings).

It appears that if this ā€œpostgresā€ database does not exist, Django can create the test database and run the tests, but it cannot delete the test database. This may be because Postgres does not allow you to drop the database you are currently connected to, however to me it seems that there is no reason that Django couldnā€™t just drop the test database from the ā€œdefaultā€ (production) database specified in the settings. I presume it is using the ā€œdefaultā€ database to create the test database, so it seems thereā€™s no reason why it canā€™t delete it as well.

Regardless, the solution was just to create that ā€œpostgresā€ database with a simple SQL statement: CREATE DATABASE postgres. After that database was created, everything worked fine.

šŸ‘¤dcgoss

7šŸ‘

If postgres database exists, try adding access to ā€˜postgresā€™ database in pg_hba.conf. Refer: https://www.postgresql.org/docs/9.1/static/auth-pg-hba-conf.html

0šŸ‘

You might want to add postgres database to the list of database in pgbouncer.ini file, if youā€™re using pgbouncer with postgresql

Leave a comment