-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
277 lines (242 loc) · 10 KB
/
database.py
File metadata and controls
277 lines (242 loc) · 10 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
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
import sqlite3
from datetime import datetime
from contextlib import contextmanager
from typing import Optional
from dataclasses import dataclass
from enum import Enum
import os
from config import DATABASE_PATH
class QueuePhase(Enum):
REGISTRATION = "registration"
ACTIVE = "active"
ADDITIONAL_REGISTRATION = "additional"
CLOSED = "closed"
class ParticipantStatus(Enum):
PENDING = "pending"
MAIN = "main"
RESERVE = "reserve"
WAITING = "waiting"
DECLINED = "declined"
PROMOTED = "promoted"
@dataclass
class Queue:
id: str
name: str
chat_id: int
message_id: Optional[int]
main_slots: int
reserve_slots: int
phase: QueuePhase
created_at: datetime
closes_at: datetime
@dataclass
class Participant:
id: int
queue_id: str
user_id: int
username: Optional[str]
full_name: str
position: Optional[int]
status: ParticipantStatus
joined_at: datetime
class Database:
def __init__(self, db_path: str = DATABASE_PATH):
os.makedirs(os.path.dirname(db_path), exist_ok=True)
self.db_path = db_path
self._init_db()
@contextmanager
def _get_conn(self):
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
try:
yield conn
conn.commit()
finally:
conn.close()
def _init_db(self):
with self._get_conn() as conn:
conn.executescript("""
CREATE TABLE IF NOT EXISTS queues (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
chat_id INTEGER NOT NULL,
message_id INTEGER,
main_slots INTEGER NOT NULL,
reserve_slots INTEGER NOT NULL,
phase TEXT NOT NULL DEFAULT 'registration',
created_at TEXT NOT NULL,
closes_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS participants (
id INTEGER PRIMARY KEY AUTOINCREMENT,
queue_id TEXT NOT NULL,
user_id INTEGER NOT NULL,
username TEXT,
full_name TEXT NOT NULL,
position INTEGER,
status TEXT NOT NULL DEFAULT 'pending',
joined_at TEXT NOT NULL,
FOREIGN KEY (queue_id) REFERENCES queues(id),
UNIQUE(queue_id, user_id)
);
CREATE INDEX IF NOT EXISTS idx_queue_chat ON queues(chat_id);
CREATE INDEX IF NOT EXISTS idx_participant_queue ON participants(queue_id);
""")
def create_queue(self, queue: Queue) -> None:
with self._get_conn() as conn:
conn.execute("""
INSERT INTO queues (id, name, chat_id, message_id, main_slots, reserve_slots,
phase, created_at, closes_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
queue.id, queue.name, queue.chat_id, queue.message_id,
queue.main_slots, queue.reserve_slots, queue.phase.value,
queue.created_at.isoformat(), queue.closes_at.isoformat()
))
def get_queue(self, queue_id: str) -> Optional[Queue]:
with self._get_conn() as conn:
row = conn.execute("SELECT * FROM queues WHERE id = ?", (queue_id,)).fetchone()
if row:
return self._row_to_queue(row)
return None
def get_active_queues(self, chat_id: int) -> list[Queue]:
with self._get_conn() as conn:
rows = conn.execute(
"SELECT * FROM queues WHERE chat_id = ? AND phase != 'closed'",
(chat_id,)
).fetchall()
return [self._row_to_queue(r) for r in rows]
def get_registration_queues(self) -> list[Queue]:
with self._get_conn() as conn:
rows = conn.execute(
"SELECT * FROM queues WHERE phase IN ('registration', 'additional')"
).fetchall()
return [self._row_to_queue(r) for r in rows]
def update_queue(self, queue: Queue) -> None:
with self._get_conn() as conn:
conn.execute("""
UPDATE queues SET message_id = ?, phase = ?, closes_at = ?
WHERE id = ?
""", (queue.message_id, queue.phase.value, queue.closes_at.isoformat(), queue.id))
def find_queue_by_name(self, chat_id: int, name: str) -> Optional[Queue]:
with self._get_conn() as conn:
row = conn.execute(
"SELECT * FROM queues WHERE chat_id = ? AND LOWER(name) = LOWER(?) AND phase != 'closed'",
(chat_id, name)
).fetchone()
if row:
return self._row_to_queue(row)
return None
def _row_to_queue(self, row) -> Queue:
return Queue(
id=row["id"],
name=row["name"],
chat_id=row["chat_id"],
message_id=row["message_id"],
main_slots=row["main_slots"],
reserve_slots=row["reserve_slots"],
phase=QueuePhase(row["phase"]),
created_at=datetime.fromisoformat(row["created_at"]),
closes_at=datetime.fromisoformat(row["closes_at"])
)
def add_participant(self, p: Participant) -> None:
with self._get_conn() as conn:
conn.execute("""
INSERT OR REPLACE INTO participants
(queue_id, user_id, username, full_name, position, status, joined_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
""", (
p.queue_id, p.user_id, p.username, p.full_name,
p.position, p.status.value, p.joined_at.isoformat()
))
def remove_participant(self, queue_id: str, user_id: int) -> bool:
with self._get_conn() as conn:
cursor = conn.execute(
"DELETE FROM participants WHERE queue_id = ? AND user_id = ?",
(queue_id, user_id)
)
return cursor.rowcount > 0
def get_participant(self, queue_id: str, user_id: int) -> Optional[Participant]:
with self._get_conn() as conn:
row = conn.execute(
"SELECT * FROM participants WHERE queue_id = ? AND user_id = ?",
(queue_id, user_id)
).fetchone()
if row:
return self._row_to_participant(row)
return None
def get_participants(self, queue_id: str, status: Optional[ParticipantStatus] = None) -> list[Participant]:
with self._get_conn() as conn:
if status:
rows = conn.execute(
"SELECT * FROM participants WHERE queue_id = ? AND status = ? ORDER BY position",
(queue_id, status.value)
).fetchall()
else:
rows = conn.execute(
"SELECT * FROM participants WHERE queue_id = ? ORDER BY position, joined_at",
(queue_id,)
).fetchall()
return [self._row_to_participant(r) for r in rows]
def get_pending_participants(self, queue_id: str) -> list[Participant]:
return self.get_participants(queue_id, ParticipantStatus.PENDING)
def get_main_participants(self, queue_id: str) -> list[Participant]:
with self._get_conn() as conn:
rows = conn.execute(
"""SELECT * FROM participants
WHERE queue_id = ? AND status IN ('main', 'promoted')
ORDER BY position""",
(queue_id,)
).fetchall()
return [self._row_to_participant(r) for r in rows]
def get_reserve_participants(self, queue_id: str) -> list[Participant]:
return self.get_participants(queue_id, ParticipantStatus.RESERVE)
def update_participant_status(self, queue_id: str, user_id: int,
status: ParticipantStatus, position: Optional[int] = None) -> None:
with self._get_conn() as conn:
if position is not None:
conn.execute(
"UPDATE participants SET status = ?, position = ? WHERE queue_id = ? AND user_id = ?",
(status.value, position, queue_id, user_id)
)
else:
conn.execute(
"UPDATE participants SET status = ? WHERE queue_id = ? AND user_id = ?",
(status.value, queue_id, user_id)
)
def count_participants(self, queue_id: str, exclude_declined: bool = True) -> int:
with self._get_conn() as conn:
if exclude_declined:
row = conn.execute(
"SELECT COUNT(*) as cnt FROM participants WHERE queue_id = ? AND status != 'declined'",
(queue_id,)
).fetchone()
else:
row = conn.execute(
"SELECT COUNT(*) as cnt FROM participants WHERE queue_id = ?",
(queue_id,)
).fetchone()
return row["cnt"]
def get_first_reserve(self, queue_id: str) -> Optional[Participant]:
with self._get_conn() as conn:
row = conn.execute(
"""SELECT * FROM participants
WHERE queue_id = ? AND status = 'reserve'
ORDER BY position LIMIT 1""",
(queue_id,)
).fetchone()
if row:
return self._row_to_participant(row)
return None
def _row_to_participant(self, row) -> Participant:
return Participant(
id=row["id"],
queue_id=row["queue_id"],
user_id=row["user_id"],
username=row["username"],
full_name=row["full_name"],
position=row["position"],
status=ParticipantStatus(row["status"]),
joined_at=datetime.fromisoformat(row["joined_at"])
)
db = Database()