Opened 104 minutes ago
Last modified 100 minutes ago
#36610 assigned Bug
[Cache] DatabaseCache resets expiration date on incr/decr
Reported by: | Simone Macri | Owned by: | Simone Macri |
---|---|---|---|
Component: | Core (Cache system) | Version: | 5.2 |
Severity: | Normal | Keywords: | cache incr dect |
Cc: | Simone Macri | Triage Stage: | Unreviewed |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | yes | UI/UX: | no |
Description (last modified by )
[Cache] DatabaseCache resets expiration date on incr/decr
Problem description
When using DatabaseCache with the incr() and decr() methods, if a key already has a custom timeout set, its expiration date is reset to the default value instead of keeping the existing one.
This leads to loss of the correct expiry value, causing keys with custom timeouts to be invalidated earlier or later than expected.
Steps to reproduce
- Configure a DatabaseCache.
- Save a key with an explicit timeout:
cache.set("key", 1, timeout=86400) # 1 day
- Check the expiration in the DB (correct: ~current_time + 86400).
- Increment the value with:
cache.incr("key")
- Check the expiration again: it is reset to the default instead of remaining unchanged.
Expected behavior
The incr() and decr() operations should not modify the expiration date of an existing key. They should preserve the previously defined timeout.
Proposed changes
- Introduced a get_many_rows() method to isolate and directly test expiry handling.
- Added a no_timeout flag in _base_set to distinguish cases where no new timeout should be set.
- Updated the UPDATE logic so that incr/decr does not overwrite the expires field.
- Added tests to ensure incr() and decr() maintain the original expiry
Affected files
- django/core/cache/backends/db.py