|
| 1 | +import time |
| 2 | +from typing import Optional, Tuple |
| 3 | + |
| 4 | +import libsql_client |
| 5 | +from libsql_client import ResultSet |
| 6 | + |
| 7 | +from fastapi_cache.types import Backend |
| 8 | + |
| 9 | +EmptyResultSet = ResultSet( |
| 10 | + columns=(), |
| 11 | + rows=[], |
| 12 | + rows_affected=0, |
| 13 | + last_insert_rowid=0) |
| 14 | + |
| 15 | +class LibsqlBackend(Backend): |
| 16 | + """ |
| 17 | + libsql backend provider |
| 18 | +
|
| 19 | + This backend requires a table name to be passed during initialization. The table |
| 20 | + will be created if it does not exist. If the table does exists, it will be emptied during init |
| 21 | + |
| 22 | + Note that this backend does not fully support TTL. It will only delete outdated objects on get. |
| 23 | +
|
| 24 | + Usage: |
| 25 | + >> libsql_url = "file:local.db" |
| 26 | + >> cache = LibsqlBackend(libsql_url=libsql_url, table_name="your-cache") |
| 27 | + >> cache.create_and_flush() |
| 28 | + >> FastAPICache.init(cache) |
| 29 | + """ |
| 30 | + |
| 31 | + # client: libsql_client.Client |
| 32 | + table_name: str |
| 33 | + libsql_url: str |
| 34 | + |
| 35 | + def __init__(self, libsql_url: str, table_name: str): |
| 36 | + self.libsql_url = libsql_url |
| 37 | + self.table_name = table_name |
| 38 | + |
| 39 | + @property |
| 40 | + def now(self) -> int: |
| 41 | + return int(time.time()) |
| 42 | + |
| 43 | + async def _make_request(self, request: str) -> ResultSet: |
| 44 | + # TODO: Exception handling. Return EmptyResultSet on error? |
| 45 | + async with libsql_client.create_client(self.libsql_url) as client: |
| 46 | + return await client.execute(request) |
| 47 | + |
| 48 | + |
| 49 | + async def create_and_flush(self) -> None: |
| 50 | + await self._make_request("CREATE TABLE IF NOT EXISTS `{}` " |
| 51 | + "(key STRING PRIMARY KEY, value BLOB, expire INTEGER);" |
| 52 | + .format(self.table_name)) |
| 53 | + await self._make_request("DELETE FROM `{}`;".format(self.table_name)) |
| 54 | + |
| 55 | + return None |
| 56 | + |
| 57 | + async def _get(self, key: str) -> Tuple[int, Optional[bytes]]: |
| 58 | + result_set = await self._make_request("SELECT * from `{}` WHERE key = \"{}\"" |
| 59 | + .format(self.table_name,key)) |
| 60 | + if len(result_set.rows) == 0: |
| 61 | + return (0,None) |
| 62 | + |
| 63 | + value = result_set.rows[0]["value"] |
| 64 | + ttl_ts = result_set.rows[0]["expire"] |
| 65 | + |
| 66 | + if not value: |
| 67 | + return (0,None) |
| 68 | + if ttl_ts < self.now: |
| 69 | + await self._make_request("DELETE FROM `{}` WHERE key = \"{}\"" |
| 70 | + .format(self.table_name, key)) |
| 71 | + return (0, None) |
| 72 | + |
| 73 | + return(ttl_ts, value) # type: ignore[union-attr,no-any-return] |
| 74 | + |
| 75 | + async def get_with_ttl(self, key: str) -> Tuple[int, Optional[bytes]]: |
| 76 | + return await self._get(key) |
| 77 | + |
| 78 | + async def get(self, key: str) -> Optional[bytes]: |
| 79 | + _, value = await self._get(key) |
| 80 | + return value |
| 81 | + |
| 82 | + async def set(self, key: str, value: bytes, expire: Optional[int] = None) -> None: |
| 83 | + ttl = self.now + expire if expire else 0 |
| 84 | + await self._make_request("INSERT OR REPLACE INTO `{}`(\"key\", \"value\", \"expire\") " |
| 85 | + "VALUES('{}','{}',{});" |
| 86 | + .format(self.table_name, key, value.decode("utf-8"), ttl)) |
| 87 | + return None |
| 88 | + |
| 89 | + async def clear(self, namespace: Optional[str] = None, key: Optional[str] = None) -> int: |
| 90 | + |
| 91 | + if namespace: |
| 92 | + result_set = await self._make_request("DELETE FROM `{}` WHERE key = \"{}%\"" |
| 93 | + .format(self.table_name, namespace)) |
| 94 | + return result_set.rowcount # type: ignore |
| 95 | + elif key: |
| 96 | + result_set = await self._make_request("DELETE FROM `{}` WHERE key = \"{}\"" |
| 97 | + .format(self.table_name, key)) |
| 98 | + return result_set.rowcount # type: ignore |
| 99 | + return 0 |
0 commit comments