forked from Kurzhalsgiraffe/Jeopardy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase_access.py
More file actions
289 lines (256 loc) · 10.8 KB
/
Copy pathdatabase_access.py
File metadata and controls
289 lines (256 loc) · 10.8 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
278
279
280
281
282
283
284
285
286
287
288
289
# database_setup.py
import sqlite3
import traceback
def error_handler(err,trace):
"""Print Errors that can occurr in the DB Methods"""
print(f"SQLite error: {err.args}")
print("Exception class is: ", err.__class__)
print("SQLite traceback: ")
print(trace)
class Dao:
"""Provides all the needed Methods to interact with the SQLite Database"""
def __init__(self, dbfile:str) -> None:
try:
sqlite3.threadsafety = 1
self.dbfile = dbfile
self.create_tables()
except sqlite3.Error as err:
error_handler(err,traceback.format_exc())
def get_db_connection(self) -> tuple[sqlite3.Connection, sqlite3.Cursor]:
"""Get a connection to the database"""
try:
conn = sqlite3.connect(self.dbfile, check_same_thread=False)
cursor = conn.cursor()
cursor.row_factory = sqlite3.Row
return conn, cursor
except sqlite3.Error as err:
error_handler(err,traceback.format_exc())
def vacuum(self) -> None:
"""Run a vacuum on the Database"""
try:
conn, cursor = self.get_db_connection()
sql = """VACUUM"""
cursor.execute(sql)
conn.close()
except sqlite3.Error as err:
error_handler(err,traceback.format_exc())
def create_tables(self) -> None:
"""Create the database tables if they dont already exist"""
try:
conn, cursor = self.get_db_connection()
sql = """CREATE TABLE IF NOT EXISTS teams (
team_id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
score INTEGER DEFAULT 0,
buzzer_id INTEGER,
is_active INTEGER,
buzzer_sound TEXT
)"""
cursor.execute(sql)
sql = """CREATE TABLE IF NOT EXISTS questions (
question_id INTEGER PRIMARY KEY AUTOINCREMENT,
question TEXT NOT NULL,
answer TEXT NOT NULL,
category TEXT,
type TEXT,
points INTEGER
)"""
cursor.execute(sql)
sql = """CREATE TABLE IF NOT EXISTS sessions (
session_id INTEGER,
round_number INTEGER,
question_id INTEGER,
team_id INTEGER,
points INTEGER,
attempt_time DATETIME DEFAULT (strftime('%Y-%m-%d %H:%M:%f', 'now')),
PRIMARY KEY (session_id, round_number, question_id, team_id, attempt_time),
FOREIGN KEY(question_id) REFERENCES questions(question_id),
FOREIGN KEY(team_id) REFERENCES teams(team_id)
)"""
cursor.execute(sql)
conn.close()
except sqlite3.Error as err:
error_handler(err,traceback.format_exc())
def get_questions_by_category(self, category) -> list:
try:
conn, cursor = self.get_db_connection()
sql = """SELECT *
FROM questions
WHERE category = ?"""
questions = cursor.execute(sql, (category,)).fetchall()
conn.close()
return questions
except sqlite3.Error as err:
error_handler(err, traceback.format_exc())
def get_question_by_id(self, question_id) -> sqlite3.Row:
try:
conn, cursor = self.get_db_connection()
question = cursor.execute('SELECT * FROM questions WHERE question_id = ?', (question_id,)).fetchone()
conn.close()
if question:
return question
else:
return None
except sqlite3.Error as err:
error_handler(err,traceback.format_exc())
def get_multiple_questions_by_ids(self, question_ids):
try:
conn, cursor = self.get_db_connection()
# Create a placeholder for each question ID
placeholders = ','.join('?' for _ in question_ids)
query = f'SELECT * FROM questions WHERE question_id IN ({placeholders}) ORDER BY points ASC'
questions = cursor.execute(query, question_ids).fetchall()
conn.close()
return questions
except sqlite3.Error as err:
error_handler(err, traceback.format_exc())
def get_teams(self) -> list:
try:
conn, cursor = self.get_db_connection()
teams = cursor.execute('SELECT * FROM teams').fetchall()
conn.close()
return teams
except sqlite3.Error as err:
error_handler(err,traceback.format_exc())
def get_team_score_by_id(self, team_id) -> int:
try:
conn, cursor = self.get_db_connection()
score_row = cursor.execute('SELECT score FROM teams WHERE team_id = ?', (team_id,)).fetchone()
conn.close()
if score_row is None:
return None
return score_row['score']
except sqlite3.Error as err:
error_handler(err,traceback.format_exc())
def add_team(self, team_name) -> None:
try:
conn, cursor = self.get_db_connection()
cursor.execute('INSERT INTO teams (name) VALUES (?)', (team_name,))
conn.commit()
conn.close()
except sqlite3.Error as err:
error_handler(err,traceback.format_exc())
def remove_team(self, team_id) -> None:
try:
conn, cursor = self.get_db_connection()
cursor.execute('DELETE FROM teams WHERE team_id = ?', (team_id,))
conn.commit()
conn.close()
except sqlite3.Error as err:
error_handler(err,traceback.format_exc())
def toggle_team_activation(self, team_id, is_active) -> None:
try:
conn, cursor = self.get_db_connection()
cursor.execute('UPDATE teams SET is_active = ? WHERE team_id = ?', (is_active, team_id))
conn.commit()
conn.close()
except sqlite3.Error as err:
error_handler(err,traceback.format_exc())
def update_buzzer_id(self, team_id, buzzer_id) -> None:
try:
conn, cursor = self.get_db_connection()
cursor.execute('UPDATE teams SET buzzer_id = ? WHERE team_id = ?', (buzzer_id, team_id))
conn.commit()
conn.close()
except sqlite3.Error as err:
error_handler(err,traceback.format_exc())
def get_buzzer_id_for_team(self, team_id):
try:
conn, cursor = self.get_db_connection()
result = cursor.execute('SELECT buzzer_id FROM teams WHERE team_id = ?', (team_id,)).fetchone()
conn.close()
if result:
return result[0]
return None
except sqlite3.Error as err:
error_handler(err, traceback.format_exc())
return None
def get_assigned_buzzer_ids(self):
try:
conn, cursor = self.get_db_connection()
result = cursor.execute('SELECT buzzer_id FROM teams').fetchall()
conn.close()
if result:
return [r["buzzer_id"] for r in result]
return None
except sqlite3.Error as err:
error_handler(err, traceback.format_exc())
return None
def get_team_id_for_buzzer_id(self, buzzer_id):
try:
conn, cursor = self.get_db_connection()
result = cursor.execute('SELECT team_id FROM teams WHERE buzzer_id = ?', (buzzer_id,)).fetchone()
conn.close()
if result:
return result[0]
return None
except sqlite3.Error as err:
error_handler(err, traceback.format_exc())
return None
def get_team_name_by_id(self, team_id):
try:
conn, cursor = self.get_db_connection()
result = cursor.execute('SELECT name FROM teams WHERE team_id = ?', (team_id,)).fetchone()
conn.close()
if result:
return result[0]
return None
except sqlite3.Error as err:
error_handler(err, traceback.format_exc())
return None
def update_team_buzzer_sound(self, team_id, buzzer_sound):
try:
conn, cursor = self.get_db_connection()
cursor.execute('UPDATE teams SET buzzer_sound = ? WHERE team_id = ?', (buzzer_sound, team_id))
conn.commit()
conn.close()
except sqlite3.Error as err:
error_handler(err,traceback.format_exc())
def get_team_buzzer_sound_by_team_id(self, team_id):
try:
conn, cursor = self.get_db_connection()
result = cursor.execute('SELECT buzzer_sound FROM teams WHERE team_id = ?', (team_id,)).fetchone()
conn.close()
if result:
return result[0]
return None
except sqlite3.Error as err:
error_handler(err, traceback.format_exc())
return None
def update_score(self, team_id, new_score) -> None:
try:
conn, cursor = self.get_db_connection()
cursor.execute('UPDATE teams SET score = ? WHERE team_id = ?', (new_score, team_id))
conn.commit()
conn.close()
except sqlite3.Error as err:
error_handler(err,traceback.format_exc())
def add_answer_to_session(self, session_id, round_number, question_id, team_id, points) -> None:
try:
conn, cursor = self.get_db_connection()
cursor.execute('INSERT INTO sessions (session_id, round_number, question_id, team_id, points) VALUES (?, ?, ?, ?, ?)', (session_id, round_number, question_id, team_id, points))
conn.commit()
conn.close()
except sqlite3.Error as err:
error_handler(err,traceback.format_exc())
def get_answered_questions_of_round(self, session_id, round_number) -> list:
try:
conn, cursor = self.get_db_connection()
result = cursor.execute('SELECT question_id, team_id FROM sessions WHERE session_id = ? AND round_number = ? AND points >= 0', (session_id, round_number)).fetchall()
conn.close()
return [(r["question_id"], r["team_id"]) for r in result]
except sqlite3.Error as err:
self.error_handler(err, traceback.format_exc())
return None
def get_next_session_id(self) -> int:
try:
conn, cursor = self.get_db_connection()
result = cursor.execute('SELECT MAX(session_id) FROM sessions').fetchone()
conn.close()
if result[0] is None:
return 1
else:
return result[0] + 1
except sqlite3.Error as err:
self.error_handler(err, traceback.format_exc())
return None