diora-web/diora/sqlite.py

24 lines
1,017 B
Python
Raw Normal View History

"""SQLite in write-ahead-log mode (docs/database.md): readers no longer wait for a writer.
In the old rollback-journal mode a long write (the podcast refresh every 15 minutes, a book of
30 MB going in) kept every reader out until it was done, and requests failed with "database is
locked" — even GET /books/. WAL is set once per database file and stays; synchronous=NORMAL is
the safe pairing for it. A connection that can't switch (another one holds the file) just goes
on as it is; the next one switches.
"""
from django.db.backends.signals import connection_created
def _sqlite_wal(sender, connection, **kwargs):
if connection.vendor != 'sqlite':
return
with connection.cursor() as cursor:
try:
cursor.execute('PRAGMA journal_mode=WAL')
except Exception: # noqa: BLE001 - locked right now; another connection will do it
pass
cursor.execute('PRAGMA synchronous=NORMAL')
connection_created.connect(_sqlite_wal, dispatch_uid='diora_sqlite_wal')