Preventing "table already exists" error when canceling migrations in Django tests
Django
2018-09-27 02:37 (7 years ago)

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
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.
We look forward to discussing your development needs.