Opened 9 hours ago

Last modified 9 hours ago

#36610 assigned Bug

[Cache] DatabaseCache resets expiration date on incr/decr — at Version 1

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 Simone Macri)

[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

  1. Configure a DatabaseCache.
  2. Save a key with an explicit timeout:

cache.set("key", 1, timeout=86400) # 1 day

  1. Check the expiration in the DB (correct: ~current_time + 86400).
  2. Increment the value with:

cache.incr("key")

  1. 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

Change History (1)

comment:1 by Simone Macri, 9 hours ago

Description: modified (diff)
Note: See TracTickets for help on using tickets.
Back to Top