storage: add LazyCacheStorage for lazy cache creation
- ID
b0506ed- date
2026-11-21 14:34:32+00:00- author
Alex Chan <alex@alexwlchan.net>- parent
c5b8ece- message
storage: add LazyCacheStorage for lazy cache creation I'm using an SQLite cache to detect video codecs in chives, and not all of my projects work with videos, but they're still creating an empty database. Let's not create empty, pointless files.- changed files
6 files, 198 additions, 13 deletions
Changed files
CHANGELOG.md (734 → 1023)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5074da0..2fc4c53 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,11 @@
# CHANGELOG
+## v1.0.5 - 2026-11-21
+
+Change the behaviour of an SQLite-backed cache so the SQLite database is only created when it's actually used.
+
+This means that if you import a library that has an SQLite-cached function, but you never interact with that function, you don't get an empty database.
+
## v1.0.4 - 2026-11-15
Tweak how function arguments are encoded as strings to further improve performance.
src/funkycache/manager.py (21889 → 21965)
diff --git a/src/funkycache/manager.py b/src/funkycache/manager.py
index 06b4f5b..979fcb0 100644
--- a/src/funkycache/manager.py
+++ b/src/funkycache/manager.py
@@ -30,6 +30,7 @@ import xxhash
from .storage import (
CacheStorage,
+ LazyCacheStorage,
MemoryCacheStorage,
SQLiteCacheStorage,
CannotOverwriteValueException,
@@ -322,13 +323,16 @@ class FunkyCache:
# similar-looking caches which are presumably stale.
# TODO: Check if the cache was accessed recently, which
# might indicate another process still using it.
- self._root.mkdir(exist_ok=True, parents=True)
db_path = self._root / f"{identifier}.{input_sig}.db"
- storage = SQLiteCacheStorage[R](db_path, data_type=data_type)
for f in self._root.glob(f"{identifier}.*.db*"):
if f != db_path:
f.unlink()
- return storage
+
+ return LazyCacheStorage(
+ create_underlying=lambda: SQLiteCacheStorage[R](
+ db_path, data_type=data_type
+ )
+ )
case _: # pragma: no cover
raise TypeError(f"unrecognised storage: {self._storage!r}")
@@ -379,8 +383,10 @@ class FunkyCache:
continue
# This cache depends on a path that changed! Create a new cache.
- if isinstance(known_cache.storage, SQLiteCacheStorage):
- known_cache.storage.close()
+ try:
+ known_cache.storage.close() # type: ignore
+ except AttributeError:
+ pass
known_cache.storage = self._create_storage(
func_name=known_cache.func_name,
src/funkycache/storage.py (12874 → 14516)
diff --git a/src/funkycache/storage.py b/src/funkycache/storage.py
index 7aef38c..07267fd 100644
--- a/src/funkycache/storage.py
+++ b/src/funkycache/storage.py
@@ -6,6 +6,7 @@ a collection of arguments to the return value.
"""
from abc import ABC, abstractmethod
+from collections.abc import Callable
import dataclasses
from datetime import datetime, timezone
import functools
@@ -152,6 +153,9 @@ class SQLiteCacheStorage[V](TypedCacheStorage[V]):
con: sqlite3.Connection
def __init__(self, database: str | Path, *, data_type: Any):
+ if database != ":memory:":
+ Path(database).parent.mkdir(exist_ok=True, parents=True)
+
self.con = sqlite3.connect(database)
self.con.execute("PRAGMA journal_mode = WAL;")
self.con.execute("PRAGMA synchronous = NORMAL;")
@@ -299,6 +303,51 @@ class SQLiteCacheStorage[V](TypedCacheStorage[V]):
raise KeyError(key)
+class LazyCacheStorage[V](CacheStorage[V]):
+ """
+ LazyCacheStorage is a lazy wrapper around an underlying CacheStorage
+ instance, and doesn't instantiate it until somebody interacts with
+ the cache.
+ """
+
+ _create_underlying: Callable[[], CacheStorage[V]]
+ _underlying: CacheStorage[V] | None
+
+ def __init__(self, create_underlying: Callable[[], CacheStorage[V]]):
+ self._create_underlying = create_underlying
+ self._underlying = None
+
+ def __getattr__(self, name: str) -> Any:
+ """
+ When looking up any property or method, forward to the underlying
+ cache storage, ensuring it exists first.
+ """
+ if self._underlying is None:
+ self._underlying = self._create_underlying()
+ return getattr(self._underlying, name)
+
+ def set(self, key: dict[str, Any], value: V) -> None:
+ """
+ Save a key-value pair in the cache.
+
+ Throws an exception if you overwrite an existing key with
+ a different value.
+ """
+ if self._underlying is None:
+ self._underlying = self._create_underlying()
+ return self._underlying.set(key, value)
+
+ def get(self, key: dict[str, Any]) -> V:
+ """
+ Look up the value of a key in the cache.
+
+ Throws a KeyError if you look up a key which isn't in the cache.
+ """
+ if self._underlying is None:
+ self._underlying = self._create_underlying()
+ return self._underlying.get(key)
+
+
def _encode_key_as_json(key: dict[str, Any]) -> str:
"""
Encode a set of arguments to a Python function as a JSON string.
src/funkycache/version.py (55 → 55)
diff --git a/src/funkycache/version.py b/src/funkycache/version.py
index dbbda4d..97635e8 100644
--- a/src/funkycache/version.py
+++ b/src/funkycache/version.py
@@ -2,4 +2,4 @@
The FunkyCache version.
"""
-__version__ = "1.0.4"
+__version__ = "1.0.5"
tests/test_manager.py (31639 → 32580)
diff --git a/tests/test_manager.py b/tests/test_manager.py
index b809238..adff752 100644
--- a/tests/test_manager.py
+++ b/tests/test_manager.py
@@ -778,11 +778,16 @@ class TestSQLiteFunkyCache(FunkyCacheTestSuite):
root = tmp_path / ".cache"
c = FunkyCache(storage="sqlite", root=root)
- @c.register(files=[tmp_path / "greeting.txt"])
- def double(n: int) -> int:
- return n * 2
+ p = tmp_path / "greeting.txt"
+ greeting1 = "bonjour monde"
+ greeting2 = "hello world"
- assert double(5) == 10
+ @c.register(files=[p])
+ def get_size() -> int:
+ return Path(p).stat().st_size
+
+ p.write_text(greeting1)
+ assert get_size() == len(greeting1)
# After populating the cache, there's a single set of SQLite files
# in the .cache directory
@@ -790,11 +795,12 @@ class TestSQLiteFunkyCache(FunkyCacheTestSuite):
assert len(stem1) == 1
# Invalidate the cache
- p = tmp_path / "greeting.txt"
- p.write_text("hello world")
+ p.write_text(greeting2)
c.notify_path_change(p)
- # There should be a new set of SQLite files in the .cache directory
+ # After we call the function again, it creates a different SQLite db
+ # in the .cache directory
+ assert get_size() == len(greeting2)
stem2 = {p.stem for p in root.iterdir()}
assert len(stem2) == 1
assert stem1 != stem2
@@ -926,6 +932,28 @@ class TestSQLiteFunkyCache(FunkyCacheTestSuite):
def double(n: int) -> int: # pragma: no cover
return n * 2
+ def test_db_is_lazy(self, tmp_path: Path) -> None:
+ """
+ The underlying SQLite database is only created when you interact
+ with it for the first time; empty caches are never created.
+ """
+ cache_root = tmp_path / ".funkycache/tests"
+
+ # Creating a FunkyCache instance doesn't create the db
+ cache = FunkyCache(storage="sqlite", root=cache_root)
+ assert not cache_root.exists()
+
+ # Registering a function doesn't create the db
+ @cache.register
+ def greet(name: str) -> str:
+ return f"Hello {name}!"
+
+ assert not cache_root.exists()
+
+ # Creating a cache entry creates the db
+ assert greet("Alex") == "Hello Alex!"
+ assert cache_root.exists()
+
def test_canonical_name_varies_by_path(tmp_path: Path) -> None:
"""
tests/test_storage.py (10271 → 13197)
diff --git a/tests/test_storage.py b/tests/test_storage.py
index 3f10c9e..bcf9c5a 100644
--- a/tests/test_storage.py
+++ b/tests/test_storage.py
@@ -19,6 +19,7 @@ from _pytest.mark.structures import ParameterSet
from funkycache.storage import (
CacheStorage,
MemoryCacheStorage,
+ LazyCacheStorage,
SQLiteCacheStorage,
CannotOverwriteValueException,
_encode_key_as_json,
@@ -247,6 +248,101 @@ class TestSQLiteCacheStorage(CacheStorageTestSuite):
with pytest.raises(sqlite3.OperationalError, match="no such column: key"):
SQLiteCacheStorage[int](db_path, data_type="int")
+ def test_creates_parent_dir(self, tmp_path: Path) -> None:
+ """
+ Creating the storage creates the parent directory for the
+ database file.
+ """
+ db_path = tmp_path / "a/b/c/cache.db"
+
+ with SQLiteCacheStorage[int](db_path, data_type=int):
+ pass
+
+ assert db_path.exists()
+
+
+class LazyCacheStorageTestSuite(CacheStorageTestSuite):
+ """
+ Tests for LazyCacheStorage.
+ """
+
+ def test_storage_is_lazy(self, tmp_path: Path) -> None:
+ """
+ The underlying storage isn't created until you interact with
+ the storage.
+ """
+ with self.create_storage(tmp_path, data_type=str) as storage:
+ assert isinstance(storage, LazyCacheStorage)
+ assert storage._underlying is None
+
+ with pytest.raises(KeyError):
+ storage.get({"one": 1})
+
+ assert storage._underlying is not None
+
+ def test_unknown_getattr_is_forwarded_to_underlying(self, tmp_path: Path) -> None:
+ """
+ Looking up an unknown attribute with __getattr__ is forwarded
+ to the underlying storage.
+ """
+ with self.create_storage(tmp_path, data_type=str) as storage:
+ assert isinstance(storage, LazyCacheStorage)
+ assert storage._underlying is None
+
+ with pytest.raises(AttributeError):
+ getattr(storage, "does_not_exist")
+
+ assert storage._underlying is not None
+
+
+class TestLazyMemoryCacheStorage(LazyCacheStorageTestSuite, TestMemoryCacheStorage):
+ """
+ Tests for MemoryCacheStorage wrapped in LazyCacheStorage.
+ """
+
+ @contextmanager
+ def create_storage[V](
+ self, tmp_path: Path, data_type: Any
+ ) -> Generator[CacheStorage[V]]:
+ """
+ Create a lazy cache storage backend.
+ """
+ yield LazyCacheStorage(create_underlying=lambda: MemoryCacheStorage())
+
+
+class TestLazySQLiteCacheStorage(LazyCacheStorageTestSuite, TestSQLiteCacheStorage):
+ """
+ Tests for SQLiteCacheStorage wrapped in LazyCacheStorage.
+ """
+
+ @contextmanager
+ def create_storage[V](
+ self, tmp_path: Path, data_type: Any
+ ) -> Generator[CacheStorage[V]]:
+ """
+ Create a lazy cache storage backend.
+ """
+ storage = LazyCacheStorage(
+ create_underlying=lambda: SQLiteCacheStorage(
+ ":memory:", data_type=data_type
+ )
+ )
+ yield storage
+ storage.close()
+
+ def test_db_file_not_created_if_unused(self, tmp_path: Path) -> None:
+ """
+ If you never interact with the cache, neither the database
+ nor the enclosing folder are created.
+ """
+ db_path = tmp_path / "a/b/c/example.db"
+
+ with self.create_storage(db_path, data_type=str):
+ pass
+
+ assert not db_path.exists()
+ assert not db_path.parent.exists()
+
class Shape(BaseModel):
"""A basic model that uses Pydantic."""