|
| 1 | +"""SQLite-backed store for single-instance production deployments. |
| 2 | +
|
| 3 | +Uses ``aiosqlite`` for async access to Python's built-in ``sqlite3``. |
| 4 | +Install with:: |
| 5 | +
|
| 6 | + pip install pympp[sqlite] |
| 7 | +
|
| 8 | +Example:: |
| 9 | +
|
| 10 | + from mpp.stores import SQLiteStore |
| 11 | +
|
| 12 | + store = await SQLiteStore.create("mpp.db") |
| 13 | +""" |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import time |
| 18 | +from typing import Any |
| 19 | + |
| 20 | +NO_TTL_EXPIRES_AT = 253402300799.0 |
| 21 | + |
| 22 | + |
| 23 | +class SQLiteStore: |
| 24 | + """Async key-value store backed by a local SQLite file. |
| 25 | +
|
| 26 | + Keys are stored in a ``kv`` table with optional TTL. Expired rows |
| 27 | + are pruned globally on writes so one-shot replay keys do not |
| 28 | + accumulate forever. |
| 29 | +
|
| 30 | + ``put_if_absent`` uses ``INSERT OR IGNORE`` — a single atomic SQL |
| 31 | + statement with no TOCTOU race. |
| 32 | + """ |
| 33 | + |
| 34 | + def __init__( |
| 35 | + self, |
| 36 | + db: Any, |
| 37 | + *, |
| 38 | + ttl_seconds: int | None = None, |
| 39 | + ) -> None: |
| 40 | + self._db = db |
| 41 | + self._ttl = ttl_seconds |
| 42 | + |
| 43 | + @classmethod |
| 44 | + async def create( |
| 45 | + cls, |
| 46 | + path: str = "mpp.db", |
| 47 | + *, |
| 48 | + ttl_seconds: int | None = None, |
| 49 | + ) -> SQLiteStore: |
| 50 | + """Open (or create) a SQLite database and initialize the schema. |
| 51 | +
|
| 52 | + Args: |
| 53 | + path: Filesystem path for the database file. |
| 54 | + Use ``":memory:"`` for an ephemeral in-memory database. |
| 55 | + ttl_seconds: Optional key TTL in seconds. Defaults to no expiry. |
| 56 | + """ |
| 57 | + import aiosqlite |
| 58 | + |
| 59 | + db = await aiosqlite.connect(path) |
| 60 | + await db.execute( |
| 61 | + "CREATE TABLE IF NOT EXISTS kv (" |
| 62 | + " key TEXT PRIMARY KEY," |
| 63 | + " value TEXT NOT NULL," |
| 64 | + " expires_at REAL NOT NULL" |
| 65 | + ")" |
| 66 | + ) |
| 67 | + await db.commit() |
| 68 | + return cls(db, ttl_seconds=ttl_seconds) |
| 69 | + |
| 70 | + async def close(self) -> None: |
| 71 | + """Close the underlying database connection.""" |
| 72 | + await self._db.close() |
| 73 | + |
| 74 | + async def __aenter__(self) -> SQLiteStore: |
| 75 | + return self |
| 76 | + |
| 77 | + async def __aexit__(self, *args: Any) -> None: |
| 78 | + await self.close() |
| 79 | + |
| 80 | + def _expires_at(self) -> float: |
| 81 | + if self._ttl is None: |
| 82 | + return NO_TTL_EXPIRES_AT |
| 83 | + return time.time() + self._ttl |
| 84 | + |
| 85 | + async def _prune_expired(self, now: float) -> None: |
| 86 | + await self._db.execute("DELETE FROM kv WHERE expires_at <= ?", (now,)) |
| 87 | + |
| 88 | + async def get(self, key: str) -> Any | None: |
| 89 | + now = time.time() |
| 90 | + cursor = await self._db.execute( |
| 91 | + "SELECT value FROM kv WHERE key = ? AND expires_at > ?", |
| 92 | + (key, now), |
| 93 | + ) |
| 94 | + row = await cursor.fetchone() |
| 95 | + return row[0] if row else None |
| 96 | + |
| 97 | + async def put(self, key: str, value: Any) -> None: |
| 98 | + await self._prune_expired(time.time()) |
| 99 | + await self._db.execute( |
| 100 | + "INSERT INTO kv (key, value, expires_at) VALUES (?, ?, ?)" |
| 101 | + " ON CONFLICT(key) DO UPDATE SET value = excluded.value," |
| 102 | + " expires_at = excluded.expires_at", |
| 103 | + (key, value, self._expires_at()), |
| 104 | + ) |
| 105 | + await self._db.commit() |
| 106 | + |
| 107 | + async def delete(self, key: str) -> None: |
| 108 | + await self._db.execute("DELETE FROM kv WHERE key = ?", (key,)) |
| 109 | + await self._db.commit() |
| 110 | + |
| 111 | + async def put_if_absent(self, key: str, value: Any) -> bool: |
| 112 | + """Atomic conditional insert. |
| 113 | +
|
| 114 | + Prunes expired rows first, then uses ``INSERT OR IGNORE`` so the |
| 115 | + write only succeeds when the key does not already exist. |
| 116 | +
|
| 117 | + Returns ``True`` if the key was new, ``False`` if it existed. |
| 118 | + """ |
| 119 | + now = time.time() |
| 120 | + await self._prune_expired(now) |
| 121 | + cursor = await self._db.execute( |
| 122 | + "INSERT OR IGNORE INTO kv (key, value, expires_at) VALUES (?, ?, ?)", |
| 123 | + (key, value, self._expires_at()), |
| 124 | + ) |
| 125 | + await self._db.commit() |
| 126 | + return cursor.rowcount > 0 |
0 commit comments