Skip to content

Commit e33a0eb

Browse files
committed
PR comments
1 parent ec82546 commit e33a0eb

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

async_substrate_interface/utils/cache.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,43 +27,49 @@
2727
class AsyncSqliteDB:
2828
_instances: dict[str, "AsyncSqliteDB"] = {}
2929
_db: Optional[aiosqlite.Connection] = None
30+
_lock: Optional[asyncio.Lock] = None
3031

3132
def __new__(cls, chain_endpoint: str):
3233
try:
3334
return cls._instances[chain_endpoint]
3435
except KeyError:
3536
instance = super().__new__(cls)
37+
instance._lock = asyncio.Lock()
3638
cls._instances[chain_endpoint] = instance
3739
return instance
3840

3941
async def __call__(self, chain, other_self, func, args, kwargs) -> Optional[Any]:
40-
if not self._db:
41-
_ensure_dir()
42-
self._db = await aiosqlite.connect(CACHE_LOCATION)
42+
async with self._lock:
43+
if not self._db:
44+
_ensure_dir()
45+
self._db = await aiosqlite.connect(CACHE_LOCATION)
4346
table_name = _get_table_name(func)
4447
key = None
4548
if not (local_chain := _check_if_local(chain)) or not USE_CACHE:
4649
await self._db.execute(
47-
f"""CREATE TABLE IF NOT EXISTS {table_name}
50+
f"""
51+
CREATE TABLE IF NOT EXISTS {table_name}
4852
(
4953
rowid INTEGER PRIMARY KEY AUTOINCREMENT,
5054
key BLOB,
5155
value BLOB,
5256
chain TEXT,
5357
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
5458
);
55-
"""
59+
"""
5660
)
5761
await self._db.execute(
58-
f"""CREATE TRIGGER IF NOT EXISTS prune_rows_trigger AFTER INSERT ON {table_name}
62+
f"""
63+
CREATE TRIGGER IF NOT EXISTS prune_rows_trigger_{table_name} AFTER INSERT ON {table_name}
5964
BEGIN
6065
DELETE FROM {table_name}
6166
WHERE rowid IN (
6267
SELECT rowid FROM {table_name}
6368
ORDER BY created_at DESC
6469
LIMIT -1 OFFSET 500
6570
);
66-
END;"""
71+
END;
72+
"""
6773
)
6874
await self._db.commit()
6975
key = pickle.dumps((args, kwargs or None))

0 commit comments

Comments
 (0)