| 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | # All rights reserved. |
| 3 | # |
| 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | # the root directory of this source tree. |
| 6 | |
| 7 | import os |
| 8 | |
| 9 | from datetime import datetime |
| 10 | from typing import List, Optional |
| 11 | |
| 12 | import aiosqlite |
| 13 | |
| 14 | from ..api import * # noqa: F403 |
| 15 | from ..config import SqliteKVStoreConfig |
| 16 | |
| 17 | |
| 18 | class SqliteKVStoreImpl(KVStore): |
| 19 | def __init__(self, config: SqliteKVStoreConfig): |
| 20 | self.db_path = config.db_path |
| 21 | self.table_name = "kvstore" |
| 22 | |
| 23 | async def initialize(self): |
| 24 | os.makedirs(os.path.dirname(self.db_path), exist_ok=True) |
| 25 | async with aiosqlite.connect(self.db_path) as db: |
| 26 | await db.execute( |
| 27 | f""" |
| 28 | CREATE TABLE IF NOT EXISTS {self.table_name} ( |
| 29 | key TEXT PRIMARY KEY, |
| 30 | value TEXT, |
| 31 | expiration TIMESTAMP |
| 32 | ) |
| 33 | """ |
| 34 | ) |
| 35 | await db.commit() |
| 36 | |
| 37 | async def set( |
| 38 | self, key: str, value: str, expiration: Optional[datetime] = None |
| 39 | ) -> None: |
| 40 | async with aiosqlite.connect(self.db_path) as db: |
| 41 | await db.execute( |
| 42 | f"INSERT OR REPLACE INTO {self.table_name} (key, value, expiration) VALUES (?, ?, ?)", |
| 43 | (key, value, expiration), |
| 44 | ) |
| 45 | await db.commit() |
| 46 | |
| 47 | async def get(self, key: str) -> Optional[str]: |
| 48 | async with aiosqlite.connect(self.db_path) as db: |
| 49 | async with db.execute( |
| 50 | f"SELECT value, expiration FROM {self.table_name} WHERE key = ?", (key,) |
| 51 | ) as cursor: |
| 52 | row = await cursor.fetchone() |
| 53 | if row is None: |
| 54 | return None |
| 55 | value, expiration = row |
| 56 | return value |
| 57 | |
| 58 | async def delete(self, key: str) -> None: |
| 59 | async with aiosqlite.connect(self.db_path) as db: |
| 60 | await db.execute(f"DELETE FROM {self.table_name} WHERE key = ?", (key,)) |
| 61 | await db.commit() |
| 62 | |
| 63 | async def range(self, start_key: str, end_key: str) -> List[str]: |
| 64 | async with aiosqlite.connect(self.db_path) as db: |
| 65 | async with db.execute( |
| 66 | f"SELECT key, value, expiration FROM {self.table_name} WHERE key >= ? AND key <= ?", |
| 67 | (start_key, end_key), |
| 68 | ) as cursor: |
| 69 | result = [] |
| 70 | async for row in cursor: |
| 71 | _, value, _ = row |
| 72 | result.append(value) |
| 73 | return result |