-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.py
71 lines (60 loc) · 2.69 KB
/
db.py
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import logging
from contextlib import contextmanager
from os.path import exists
from sqlite3 import connect, Cursor
from constants import NUM_CAMERAS, NUM_BUTTONS, DB_FILE
LOG = logging.getLogger("db")
class Database:
def __init__(self):
if not exists(DB_FILE):
LOG.info("Initialize sqlite database...")
with self.cursor() as cur:
cur.execute("CREATE TABLE positions ("
"cam INTEGER NOT NULL, "
"pos INTEGER NOT NULL, "
"name VARCHAR NOT NULL DEFAULT '', "
"btn_class VARCHAR NOT NULL DEFAULT 'btn-secondary', "
"focus INTEGER NOT NULL DEFAULT -1, "
"PRIMARY KEY (cam, pos))")
for cam in range(NUM_CAMERAS):
for pos in range(NUM_BUTTONS):
cur.execute("INSERT INTO positions (cam, pos) VALUES (?, ?)", (cam, pos))
LOG.info("Initialization complete")
@contextmanager
def dict_cursor(self) -> Cursor:
connection = None
try:
connection = connect(DB_FILE)
connection.row_factory = lambda cursor, row: {c[0]: row[i] for i, c in enumerate(cursor.description)}
yield connection.cursor()
connection.commit()
finally:
if connection is not None:
connection.close()
@contextmanager
def cursor(self) -> Cursor:
connection = None
try:
connection = connect(DB_FILE)
yield connection.cursor()
connection.commit()
finally:
if connection is not None:
connection.close()
def set_button(self, cam: int, pos: int, name: str, btn_class: str):
with self.cursor() as cur:
cur.execute("UPDATE positions SET name = ?, btn_class = ? WHERE cam = ? AND pos = ?",
(name, btn_class, cam, pos))
def set_focus(self, cam: int, pos: int, focus: int):
with self.cursor() as cur:
cur.execute("UPDATE positions SET focus = ? WHERE cam = ? AND pos = ?", (focus, cam, pos))
def get_focus(self, cam: int, pos: int) -> int:
with self.cursor() as cur:
cur.execute("SELECT focus FROM positions WHERE cam = ? AND pos = ?", (cam, pos))
return cur.fetchone()[0]
def get_data(self) -> list:
with self.dict_cursor() as cur:
return list(cur.execute("SELECT cam, pos, name, btn_class FROM positions ORDER BY cam, pos"))
def clear_buttons(self):
with self.cursor() as cur:
cur.execute("UPDATE positions SET name = '', btn_class = 'btn-secondary'")