Django Tests: Cannot Drop Database

Sometimes when tests crash, if you try to re-run them, the code will fail because the old database cannot be dropped and the error message will be something like:

ERROR: database "my_db" is being accessed by other users
DETAIL: There is 1 other session using the database.

Or if you are using PyCharm the message will be:

Got an error recreating the test database: database "my_db" is being accessed by other users
DETAIL: There is 1 other session using the database.

To resolve this situation, see this blog post.

Also, you can run SQL from PGAdmin.

Or you can make a Django management command:

from django.core.management.base import BaseCommand
from django.db import connection
from django.conf import settings


class Command(BaseCommand):
    help = 'Run this after tests crash'

    def handle(self, *args, **options):
        cursor = connection.cursor()

        database_name = 'test_{}'.format(settings.DATABASES['default']['NAME'])

        # Clears connections to db so that it can be dropped
        # http://www.leeladharan.com/drop-a-postgresql-database-if-there-are-active-connections-to-it
        cursor.execute(
            "SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity "
            "WHERE pg_stat_activity.datname = %s AND pid <> pg_backend_pid();", [database_name])

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s