I’m trying to make Django app that runs on sqlite3 db in memory (in production). The steps seems simple
- Get an in-memory database running
- Attach the disk database (file)
- Recreate tables / indexes and copy over contents
- Detach the disk database (file)
but his is all new to me and I have problems with implementing them.
So far I’ve written:
settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
app.py
from django.apps import AppConfig
import sqlite3
import os
from StringIO import StringIO
from django.conf import settings
class EnquirerConfig(AppConfig):
name = 'enquirer'
def ready(self):
con = sqlite3.connect(os.path.join(settings.BASE_DIR, 'db.sqlite3'))
tempfile = StringIO()
for line in con.iterdump():
tempfile.write('%s\n' % line)
con.close()
tempfile.seek(0)
sqlite = sqlite3.connect(":memory:")
sqlite.cursor().executescript(tempfile.read())
sqlite.commit()
sqlite.row_factory = sqlite3.Row
This is all based on the following: How to load existing db file to memory in Python sqlite3? Django - in memory sqlite in production
I've also tried
if settings.DATABASES['default']['NAME'] == ':memory:':
call_command('migrate', interactive=True)
However, this does not seem to work - I still have unapplied migrations and ‘no such table’ exception.