-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_db.py
More file actions
51 lines (44 loc) · 1.76 KB
/
simple_db.py
File metadata and controls
51 lines (44 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import sqlite3
import threading
from typing import Any, Optional
class SimpleDB:
"""Thread-safe simple sqlite wrapper for small frequent reads/writes.
Uses a single connection per process with a lock. Designed for low-latency local access.
"""
def __init__(self, path: str = ':memory:'):
self._path = path
self._conn = sqlite3.connect(self._path, check_same_thread=False)
self._conn.execute('PRAGMA journal_mode=WAL')
self._conn.execute('PRAGMA synchronous=NORMAL')
self._lock = threading.Lock()
self._ensure_tables()
def _ensure_tables(self):
with self._lock:
cur = self._conn.cursor()
cur.execute('''
CREATE TABLE IF NOT EXISTS kv (
k TEXT PRIMARY KEY,
v TEXT
)''')
self._conn.commit()
def get(self, key: str) -> Optional[str]:
with self._lock:
cur = self._conn.cursor()
cur.execute('SELECT v FROM kv WHERE k=?', (key,))
r = cur.fetchone()
return r[0] if r else None
def set(self, key: str, value: Any) -> None:
with self._lock:
cur = self._conn.cursor()
cur.execute('REPLACE INTO kv(k,v) VALUES(?,?)', (key, str(value)))
self._conn.commit()
def incr(self, key: str, delta: int = 1) -> int:
with self._lock:
cur = self._conn.cursor()
cur.execute('SELECT v FROM kv WHERE k=?', (key,))
r = cur.fetchone()
val = int(r[0]) if r and r[0].isdigit() else 0
val += delta
cur.execute('REPLACE INTO kv(k,v) VALUES(?,?)', (key, str(val)))
self._conn.commit()
return val