chia-blockchain/chia/wallet/key_val_store.py

65 lines
1.9 KiB
Python
Raw Normal View History

2020-07-02 15:44:40 +03:00
from typing import Any
2020-06-04 02:21:47 +03:00
import aiosqlite
2020-07-02 15:44:40 +03:00
from chia.util.byte_types import hexstr_to_bytes
from chia.util.db_wrapper import DBWrapper
from chia.util.streamable import Streamable
2020-06-04 02:21:47 +03:00
class KeyValStore:
"""
2020-06-04 05:32:33 +03:00
Multipurpose persistent key-value store
2020-06-04 02:21:47 +03:00
"""
db_connection: aiosqlite.Connection
db_wrapper: DBWrapper
2020-06-04 02:21:47 +03:00
@classmethod
async def create(cls, db_wrapper: DBWrapper):
2020-06-04 02:21:47 +03:00
self = cls()
self.db_wrapper = db_wrapper
self.db_connection = db_wrapper.db
2021-04-06 09:35:05 +03:00
await self.db_connection.execute("pragma journal_mode=wal")
await self.db_connection.execute("pragma synchronous=2")
2020-06-04 02:21:47 +03:00
await self.db_connection.execute(
2020-12-11 10:27:03 +03:00
("CREATE TABLE IF NOT EXISTS key_val_store(" " key text PRIMARY KEY," " value text)")
2020-06-04 02:21:47 +03:00
)
2020-12-11 10:27:03 +03:00
await self.db_connection.execute("CREATE INDEX IF NOT EXISTS name on key_val_store(key)")
2020-06-04 02:21:47 +03:00
await self.db_connection.commit()
return self
async def _clear_database(self):
cursor = await self.db_connection.execute("DELETE FROM key_val_store")
await cursor.close()
await self.db_connection.commit()
2020-07-02 15:44:40 +03:00
async def get_object(self, key: str, type: Any) -> Any:
2020-06-04 02:21:47 +03:00
"""
Return bytes representation of stored object
"""
2020-12-11 10:27:03 +03:00
cursor = await self.db_connection.execute("SELECT * from key_val_store WHERE key=?", (key,))
2020-06-04 02:21:47 +03:00
row = await cursor.fetchone()
await cursor.close()
if row is None:
return None
2020-07-02 15:44:40 +03:00
return type.from_bytes(hexstr_to_bytes(row[1]))
2020-06-04 02:21:47 +03:00
2020-07-02 15:44:40 +03:00
async def set_object(self, key: str, obj: Streamable):
2020-06-04 02:21:47 +03:00
"""
Adds object to key val store
"""
async with self.db_wrapper.lock:
cursor = await self.db_connection.execute(
"INSERT OR REPLACE INTO key_val_store VALUES(?, ?)",
(key, bytes(obj).hex()),
)
await cursor.close()
await self.db_connection.commit()