-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdb.py
348 lines (315 loc) · 12.1 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
from typing import Any, Dict, List, Tuple
import pyrqlite.dbapi2 as dbapi2
from find_violations import Violation
class RqliteDB:
def __init__(self, host: str = "localhost", port: int = 4001):
self.conn = dbapi2.connect(
host=host,
port=port,
)
self._enable_foreign_keys()
self._init_db()
def _enable_foreign_keys(self):
"""Enable foreign key constraints for SQLite"""
with self.conn.cursor() as cursor:
cursor.execute("PRAGMA foreign_keys = ON")
def _init_db(self):
"""Initialize database schema"""
queries = [
"""CREATE TABLE IF NOT EXISTS chats (
chat_id INTEGER PRIMARY KEY,
net TEXT NOT NULL DEFAULT 'main',
timeout INTEGER DEFAULT 10
)""",
"""CREATE TABLE IF NOT EXISTS nodes (
node_id INTEGER,
network TEXT,
status TEXT,
updated_at REAL,
power_state TEXT,
power_target TEXT,
farmerbot BOOLEAN DEFAULT FALSE,
PRIMARY KEY (node_id, network)
)""",
"""CREATE TABLE IF NOT EXISTS subscriptions (
chat_id INTEGER,
network TEXT,
node_id INTEGER,
PRIMARY KEY (chat_id, network, node_id),
FOREIGN KEY (chat_id) REFERENCES chats(chat_id),
FOREIGN KEY (node_id, network) REFERENCES nodes(node_id, network)
)""",
"""CREATE TABLE IF NOT EXISTS violations (
node_id INTEGER,
network TEXT,
boot_requested REAL,
booted_at REAL,
end_time REAL,
finalized BOOLEAN,
PRIMARY KEY (node_id, network, boot_requested),
FOREIGN KEY (node_id, network) REFERENCES nodes(node_id, network)
)""",
"""CREATE TABLE IF NOT EXISTS metadata (
key TEXT PRIMARY KEY,
value TEXT
)""",
]
with self.conn.cursor() as cursor:
for query in queries:
cursor.execute(query)
def create_chat(self, chat_id: int) -> None:
"""Create a new chat with default settings if it doesn't exist"""
with self.conn.cursor() as cursor:
cursor.execute(
"""
INSERT OR IGNORE INTO chats (chat_id) VALUES (?)
""",
(chat_id,),
)
def get_subscribed_nodes(self, chat_id: int, network: str) -> List[int]:
"""Get list of node IDs that a chat is subscribed to for a specific network"""
with self.conn.cursor() as cursor:
cursor.execute(
"""
SELECT s.node_id
FROM subscriptions s
WHERE s.chat_id = ? AND s.network = ?
""",
(chat_id, network),
)
return [row[0] for row in cursor.fetchall() if row[0] is not None]
def update_chat_network(self, chat_id: int, network: str):
with self.conn.cursor() as cursor:
cursor.execute(
"""
UPDATE chats SET net = ? WHERE chat_id = ?
""",
(network, chat_id),
)
def add_subscription(self, chat_id: int, network: str, node_id: int):
"""Add a single subscription (kept for backward compatibility)"""
self.add_subscriptions(chat_id, network, [node_id])
def add_subscriptions(self, chat_id: int, network: str, node_ids: List[int]):
"""Add multiple subscriptions in a single request"""
with self.conn.cursor() as cursor:
cursor.executemany(
"""
INSERT OR IGNORE INTO subscriptions (chat_id, network, node_id)
VALUES (?, ?, ?)
""",
[(chat_id, network, node_id) for node_id in node_ids],
)
def remove_subscription(self, chat_id: int, network: str, node_id: int):
"""Remove a single subscription (kept for backward compatibility)"""
self.remove_subscriptions(chat_id, network, [node_id])
def remove_subscriptions(self, chat_id: int, network: str, node_ids: List[int]):
"""Remove multiple subscriptions in a single request"""
with self.conn.cursor() as cursor:
cursor.executemany(
"""
DELETE FROM subscriptions
WHERE chat_id = ? AND network = ? AND node_id = ?
""",
[(chat_id, network, node_id) for node_id in node_ids],
)
def get_node(self, node_id: int, network: str) -> Dict[str, Any]:
with self.conn.cursor() as cursor:
cursor.execute(
"""
SELECT node_id, network, status, updated_at,
power_state, power_target, farmerbot
FROM nodes
WHERE node_id = ? AND network = ?
""",
(node_id, network),
)
row = cursor.fetchone()
if row:
return {
"nodeId": row[0],
"status": row[2],
"updatedAt": row[3],
"power": {"state": row[4], "target": row[5]},
"farmerbot": bool(row[6]),
"violations": self.get_node_violations(node_id, network),
}
return None
def get_nodes(self, network: str) -> List[Dict[str, Any]]:
with self.conn.cursor() as cursor:
cursor.execute(
"""
SELECT node_id, network, status, updated_at,
power_state, power_target, farmerbot
FROM nodes
WHERE network = ?
""",
(network,),
)
nodes = []
for row in cursor.fetchall():
nodes.append(
{
"nodeId": row[0],
"status": row[2],
"updatedAt": row[3],
"power": {"state": row[4], "target": row[5]},
"farmerbot": bool(row[6]),
"violations": self.get_node_violations(row[0], network),
}
)
return nodes
def create_node(self, node, network: str):
with self.conn.cursor() as cursor:
cursor.execute(
"""
INSERT OR IGNORE INTO nodes
(node_id, network, status, updated_at,
power_state, power_target, farmerbot)
VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(
node.nodeId,
network,
node.status,
node.updatedAt,
node.power["state"],
node.power["target"],
getattr(node, "farmerbot", False),
),
)
def update_node(self, node, network: str):
with self.conn.cursor() as cursor:
cursor.execute(
"""
INSERT OR REPLACE INTO nodes
(node_id, network, status, updated_at,
power_state, power_target, farmerbot)
VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(
node.nodeId,
network,
node.status,
node.updatedAt,
node.power["state"],
node.power["target"],
getattr(node, "farmerbot", False),
),
)
def get_node_violations(self, node_id: int, network: str) -> Dict[float, Violation]:
"""Get all violations for a node as a dict of Violation objects keyed by boot_requested timestamp"""
with self.conn.cursor() as cursor:
cursor.execute(
"""
SELECT boot_requested, booted_at, end_time, finalized
FROM violations
WHERE node_id = ? AND network = ?
""",
(node_id, network),
)
return {
row[0]: Violation(
boot_requested=row[0],
booted_at=row[1],
end_time=row[2],
finalized=bool(row[3]),
)
for row in cursor.fetchall()
}
def add_violation(self, node_id: int, network: str, violation):
"""Add a single violation (kept for backward compatibility)"""
self.add_violations(node_id, network, [violation])
def add_violations(self, node_id: int, network: str, violations: List[Violation]):
"""Add multiple Violation objects in a single request"""
with self.conn.cursor() as cursor:
cursor.executemany(
"""
INSERT OR REPLACE INTO violations
(node_id, network, boot_requested, booted_at, end_time, finalized)
VALUES (?, ?, ?, ?, ?, ?)
""",
[
(
node_id,
network,
v.boot_requested,
v.booted_at,
v.end_time,
v.finalized,
)
for v in violations
],
)
def get_all_subscribed_nodes(self) -> List[Tuple[int, List[int]]]:
"""Get list of all nodes with active subscriptions
Returns:
List of tuples where each tuple contains:
- node_id: int
- chat_ids: List[int] of chat IDs subscribed to this node
"""
with self.conn.cursor() as cursor:
cursor.execute(
"""
SELECT n.node_id, GROUP_CONCAT(s.chat_id)
FROM nodes n
JOIN subscriptions s ON n.node_id = s.node_id AND n.network = s.network
GROUP BY n.node_id
"""
)
# Convert the comma-separated chat_ids string to a list of integers
return [
(row[0], [int(chat_id) for chat_id in row[1].split(",")])
for row in cursor.fetchall()
]
def get_chat_network(self, chat_id: int) -> str:
"""Get the selected network for a chat"""
with self.conn.cursor() as cursor:
cursor.execute(
"""
SELECT net FROM chats WHERE chat_id = ?
""",
(chat_id,),
)
row = cursor.fetchone()
return row[0] if row else "main"
def get_metadata(self, key: str) -> str:
"""Get metadata value by key"""
with self.conn.cursor() as cursor:
cursor.execute(
"""
SELECT value FROM metadata WHERE key = ?
""",
(key,),
)
row = cursor.fetchone()
return row[0] if row else None
def set_metadata(self, key: str, value: str) -> None:
"""Set metadata value by key"""
with self.conn.cursor() as cursor:
cursor.execute(
"""
INSERT OR REPLACE INTO metadata (key, value)
VALUES (?, ?)
""",
(key, value),
)
def get_chat_timeout(self, chat_id: int) -> int:
"""Get the timeout setting for a chat"""
with self.conn.cursor() as cursor:
cursor.execute(
"""
SELECT timeout FROM chats WHERE chat_id = ?
""",
(chat_id,),
)
row = cursor.fetchone()
return row[0] if row else 10
def set_chat_timeout(self, chat_id: int, timeout: int) -> None:
"""Set the timeout setting for a chat"""
with self.conn.cursor() as cursor:
cursor.execute(
"""
UPDATE chats SET timeout = ? WHERE chat_id = ?
""",
(timeout, chat_id),
)