Skip to content

Commit

Permalink
add delete option to expire_cache_entries (#127)
Browse files Browse the repository at this point in the history
  • Loading branch information
malmans2 authored Aug 2, 2024
1 parent aef86d2 commit 0d84145
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
6 changes: 5 additions & 1 deletion cacholote/clean.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,7 @@ def expire_cache_entries(
tags: list[str] | None = None,
before: datetime.datetime | None = None,
after: datetime.date | None = None,
delete: bool = False,
) -> int:
now = utils.utcnow()

Expand All @@ -384,6 +385,9 @@ def expire_cache_entries(
sa.select(database.CacheEntry).filter(*filters)
):
count += 1
cache_entry.expiration = now
if delete:
session.delete(cache_entry)
else:
cache_entry.expiration = now
database._commit_or_rollback(session)
return count
16 changes: 14 additions & 2 deletions tests/test_60_clean.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,21 +326,33 @@ def test_clean_multiple_files(tmp_path: pathlib.Path) -> None:
(["foo"], TOMORROW, YESTERDAY),
],
)
@pytest.mark.parametrize("delete,n_entries", [(True, 0), (False, 1)])
def test_expire_cache_entries(
tags: None | list[str],
before: None | datetime.datetime,
after: None | datetime.datetime,
delete: bool,
n_entries: int,
) -> None:
con = config.get().engine.raw_connection()
cur = con.cursor()

with config.set(tag="foo"):
now = cached_now()

# Do not expire
count = clean.expire_cache_entries(tags=["bar"], before=YESTERDAY, after=TOMORROW)
count = clean.expire_cache_entries(
tags=["bar"], before=YESTERDAY, after=TOMORROW, delete=delete
)
assert count == 0
assert now == cached_now()

# Expire
count = clean.expire_cache_entries(tags=tags, before=before, after=after)
count = clean.expire_cache_entries(
tags=tags, before=before, after=after, delete=delete
)
cur.execute("SELECT COUNT(*) FROM cache_entries", ())
assert cur.fetchone() == (n_entries,)
assert count == 1
assert now != cached_now()

Expand Down

0 comments on commit 0d84145

Please sign in to comment.