Coverage for apps / core / cache.py: 78%

9 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-04-12 10:49 +0000

1"""PostgreSQL-safe database cache backend. 

2 

3Django's built-in DatabaseCache uses a non-atomic read-then-write pattern 

4for set(), which causes IntegrityError on concurrent inserts (duplicate key). 

5This backend wraps the first attempt in a savepoint so the IntegrityError 

6doesn't poison the surrounding transaction, then retries as an update. 

7""" 

8 

9from django.core.cache.backends.db import DatabaseCache 

10from django.db import IntegrityError, transaction 

11 

12 

13class PostgreSafeDatabaseCache(DatabaseCache): 

14 """DatabaseCache that handles concurrent INSERT races gracefully.""" 

15 

16 def _base_set(self, mode, key, value, timeout=None): 

17 try: 

18 with transaction.atomic(): 

19 return super()._base_set(mode, key, value, timeout) 

20 except IntegrityError: 

21 # Another worker inserted the same key between our SELECT and INSERT. 

22 # The savepoint rolled back the failed INSERT, so the transaction is 

23 # clean. Retry — the second attempt will see the existing row and 

24 # UPDATE it. 

25 return super()._base_set(mode, key, value, timeout) 

← Back to Dashboard