Preventing "table already exists" error when canceling migrations in Django tests

Django
2018-09-27 11:37 (6 years ago) ytyng

Django==1.9.13
Mezzanine==4.3.0

During testing with Django Mezzanine Cartridge, when the migration was canceled

In settings

if 'test' in sys.argv:
CAPTCHA_TEST_MODE = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
DATABASE_ROUTERS = []

class DisableMigrations(object):
def __contains__(self, item):
return True

def __getitem__(self, item):
return 'notmigrations'

MIGRATION_MODULES = DisableMigrations()

I was doing it like this,

but due to issues related to the trouth= in ManyToMany fields, the create table was stopped with "table already exists" error and the tests could not proceed.

Therefore, by patching the CREATE TABLE statement of BaseDatabaseSchemaEditor to CREATE TABLE IF NOT EXISTS, you can execute without stopping.

from django.db.backends.sqlite3.schema import DatabaseSchemaEditor

# Patch CREATE TABLE
DatabaseSchemaEditor.sql_create_table = \
"CREATE TABLE IF NOT EXISTS %(table)s (%(definition)s)"
DatabaseSchemaEditor.sql_create_index = \
"CREATE INDEX IF NOT EXISTS %(name)s ON %(table)s (%(columns)s)%(extra)s"
DatabaseSchemaEditor.sql_create_unique = \
"CREATE UNIQUE INDEX IF NOT EXISTS %(name)s ON %(table)s (%(columns)s)"

It might be a good idea to patch django.db.utils.DatabaseErrorWrapper to suppress the errors.

Currently unrated

Comments

Archive

2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011