-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdatabase.py
396 lines (334 loc) · 12.4 KB
/
database.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
import os
import psycopg2
from models.user import User
user = os.environ["POSTGRES_USER"]
password = os.environ["POSTGRES_PASSWORD"]
host = os.environ["POSTGRES_HOST"]
port = os.environ["POSTGRES_PORT"]
database = os.environ["POSTGRES_DB"]
def get_connection():
conn = psycopg2.connect(
user=user,
password=password,
host=host,
port=port,
database=database
)
return conn
conn = get_connection()
cur = conn.cursor()
# IMPORTANT: executing a query is expensive, so we would rather write more functions than write more execute queries.
# # DO NOT EVER EXECUTE THIS FUNCTION BRUH
# def dropDatabase():
# query = f"""
# SELECT 'DROP TABLE IF EXISTS "' || tablename || '" CASCADE;'
# from
# pg_tables WHERE schemaname = 'advent';
# """
# cur.execute(query)
# conn.commit()
# IMPORTANT: executing a query is expensive, so we would rather write more functions than write more execute queries.
# Get all the information about a question given its day number
# Returns all information in the form of a dictionary
# You might want to use this function to find the total number of parts in a question, and then use getPartInfo
def getQuestionInfo(compName, dayNum):
query = f"""
select * from Questions q
join Competitions c on q.cid = c.cid
where q.dayNum = {dayNum} and c.name = '{compName}';
"""
cur.execute(query)
# only one entry should be returned since day number is unique
t = cur.fetchone()
return t
# Get all the parts given a day number of a question
# Returns all information in the form of a list of dictionaries
def getQuestionParts(compName, dayNum):
query = f"""
select * from Parts p
join Questions q on p.qid = q.qid
join Competitions c on q.cid = c.cid
where q.dayNum = {dayNum} and c.name = '{compName}';
"""
cur.execute(query)
partsList = []
for t in cur.fetchall():
partsList.append(t)
# sort the list based off the part number
sortedList = sorted(partsList, key=lambda x: x['partNum'])
return sortedList
# Get all the information about a part of a question (e.g. day 1 part 2) given the day number and part number
# Same as above but more specific
# Returns all information in the form of a dictionary
def getPartInfo(compName, dayNum, partNum):
query = f"""
select * from Parts p
join Questions q on p.qid = q.qid
join Competitions c on q.cid = c.cid
where q.dayNum = {dayNum} and p.partNum = {partNum} and c.name = '{compName}';
"""
cur.execute(query)
# only one entry should be returned since day number is unique
t = cur.fetchone()
return t
# Get all the questions that pertain to a certain competition, by name
# Returns None if the competition does not exist
def getCompetitionQuestions(compName):
query = f"""
select * from Parts p
join Questions q on p.qid = q.qid
join Competitions c on q.cid = c.cid
where c.name = '{compName}';
"""
cur.execute(query)
# only one entry should be returned since day number is unique
return cur.fetchall()
# Gets a competition
def getCompetition(compName):
query = f"""
select * from Competitions c
where c.name = '{compName}';
"""
cur.execute(query)
# only one entry should be returned since day number is unique
return cur.fetchall()
# Unfinished function.
# Dynamically generates a new input for a user and day number
def generateInput(dayNum, uid):
pass
# Gets the input for a day number and user, if it exists
# Returns the input string, else returns None
def getInput(compName, dayNum, uid):
query = f"""
select i.input from Inputs i
join Questions q on i.qid = q.qid
join Competitions c on q.cid = c.cid
where q.dayNum = {dayNum} and i.uid = {uid} and c.name = '{compName}';
"""
cur.execute(query)
t = cur.fetchone()
return t['input'] if t is not None else t
# Gets the input for a day number and user, if it exists
# Returns a tuple:
# the tuple is None if the value does not exist
# the first entry of the tuple is True if the solution is correct (and exists), False otherwise
# the second entry of the tuple is a string outlining the reason if the solution was incorrect
# not sure what to put here so just leaving as empty string for now
def checkInput(compName, dayNum, uid, solution):
query = f"""
select i.input, i.solution from Inputs i
join Questions q on i.qid = q.qid
join Competitions c on q.cid = c.cid
where q.dayNum = {dayNum} and i.uid = {uid} and c.name = '{compName}';
"""
cur.execute(query)
t = cur.fetchone()
if t is None:
return None
elif t['solution'].lower() == solution.strip().lower():
# can change this later, but iirc advent of code is also not case sensitive
return (True, "")
else:
return (False, "")
# note: for more advanced processing, we might consider having a timeout if a user tries too many things too quickly
# but idk how to implement this too well
# Get all the information about a user's stats in a certain competition
# Returns all information in the form of a list of 'solved objects'
def getUserStatsPerComp(compName, uid):
# A right outer join returns all the results from the parts table, even if there is no solves
# Best to look up examples :D
# Use this information to deduce whether a user has solved a part or not
query = f"""
select u.username, u.github, q.dayNum, p.partNum, s.points, s.solveTime from Users u
join Solves s on s.uid = u.uid
right outer join Parts p on s.pid = p.pid
join Questions q on p.qid = q.qid
join Competitions c on q.cid = c.cid
where s.uid = {uid} and c.name = '{compName}';
"""
cur.execute(query)
return cur.fetchall()
# Get only the number of stars and points for a user.
# Returns extremely simple info
def getBasicUserStatsPerComp(compName, uid):
# A right outer join returns all the results from the parts table, even if there is no solves
# Best to look up examples :D
# Use this information to deduce whether a user has solved a part or not
query = f"""
select u.username, u.github, s.numStars, s.score from Stats s
right outer join Users u
where s.uid = {uid} and c.name = '{compName}';
join Questions q on p.qid = q.qid
join Competitions c on q.cid = c.cid
where i.uid = {uid} and c.name = {compName};
"""
cur.execute(query)
return cur.fetchall()
# Could be very large
def getAllUsers():
query = f"""
select * from Users;
"""
cur.execute(query)
return cur.fetchall()
# Could be very large
def getAllCompetitions():
query = f"""
select * from Competitions;
"""
cur.execute(query)
return cur.fetchall()
# Pre conditions assume we have already checked that noone has that username
# TODO: No idea whether this works lol never done something like this before
def updateUsername(username, uid):
query = f"""
update Users
set username = {username}
where uid = {uid};
"""
cur.execute(query)
conn.commit()
# Finds top N of a leaderboard, where N is a positive integer
# Assumes comp name is legit
# TODO: fix tiebreakers in rankings
def getNLeaderboard(compName, n):
query = f"""
select u.github, u.username, s.numStars, s.score from Users u
join Stats s on s.uid = u.uid
join Competitions c on s.cid = c.cid
where c.name = '{compName}'
order by s.score DESC
limit {n};
"""
cur.execute(query)
return cur.fetchall()
# Finds top N of a leaderboard of all users who begin with prefix
# Assumes comp name is legit
# TODO: left outer join may not work! Needs to be tested on people with no puzzle input.
def searchLeaderboard(compName, prefix, n):
query = f"""
select u.github, u.username, s.numStars, s.score from Users u
left outer join Stats s on s.uid = u.uid
join Competitions c on s.cid = c.cid
where c.name = '{compName}' and (u.username like '{prefix}%' or u.github like '{prefix}%')
order by s.score DESC
limit {n};
"""
cur.execute(query)
return cur.fetchall()
# Finds your ranking in a certain competition
# TODO: not sure if this even works
def getRankLeaderboard(compName, uid):
query = f"""
select position
from (
select u.uid as bigUid, *, row_number() over(
order by s.score DESC
)
as position
from Users u
left outer join Stats s on s.uid = u.uid
join Competitions c on s.cid = c.cid
where c.name = '{compName}'
) result where bigUid = {uid};
"""
cur.execute(query)
return cur.fetchall()
def addCompetition(compName):
query = f"""
insert into Competitions
values (1, '{compName}', 0, 0);
"""
cur.execute(query)
conn.commit()
def addSolve(uid, pid, timeSolved, pointsGained):
query = f"""
insert into Solves
values ({uid}, {pid}, {timeSolved}, {pointsGained});
"""
cur.execute(query)
conn.commit()
def addUser(uid, username, email, githubLink, password):
query = f"""
INSERT INTO Users VALUES ({uid}, '{email}', '{githubLink}', '{username}', '{password}');
"""
cur.execute(query)
conn.commit()
def addReplica(compName, questionName, dayNum, partDescription, username, email, githubLink, password):
query = f"""
INSERT INTO Users VALUES (42, '{email}', '{githubLink}', '{username}', '{password}');
"""
cur.execute(query)
conn.commit()
query = f"""
insert into Competitions
values (1, '{compName}', 0, 0);
"""
cur.execute(query)
conn.commit()
query = f"""
insert into Questions
values (1, 1, 0, '{questionName}', '.-.', {dayNum});
"""
cur.execute(query)
conn.commit()
query = f"""
insert into Parts
values (1, 1, '{partDescription}', 1, 0, '2008-11-11 13:23:44');
"""
cur.execute(query)
conn.commit()
query = f"""
insert into Solves
values (42, 1, 100, 100);
"""
cur.execute(query)
conn.commit()
# Check if they've solved
def checkSolve(compName, dayNum, partNum, uid):
query = f"""
select * from Solves s
join Parts p on p.pid = s.pid
join Questions q on p.qid = q.qid
join Competitions c on q.cid = c.cid
where c.name = '{compName}' and s.uid = {uid} and p.partNum = {partNum} and q.dayNum = {dayNum};
"""
cur.execute(query)
return (len(cur.fetchall()) == 1)
# Create a solve.
# This requires you to know the part id, solve time and number of points
def createSolve(uid, pid, solveTime, points):
query = f"""
insert into Solves s
values ({uid}, {pid}, {solveTime}, {points});
"""
cur.execute(query)
conn.commit()
# Gets the pid given compName, dayNum, partNum
def findPid(compName, dayNum, partNum):
query = f"""
select p.pid from Parts p
join Questions q on p.qid = q.qid
join Competitions c on q.cid = c.cid
where c.name = '{compName}' and p.partNum = {partNum} and q.dayNum = {dayNum};
"""
cur.execute(query)
return cur.fetchall()
# Get number of people who have already solved
def getNumSolved(compName, dayNum, partNum, uid):
query = f"""
select count(*) from Solves s
join Parts p on p.pid = s.pid
join Questions q on p.qid = q.qid
join Competitions c on q.cid = c.cid
where c.name = '{compName}' and s.uid = {uid} and p.partNum = {partNum} and q.dayNum = {dayNum};
"""
cur.execute(query)
return cur.fetchall()
def add_user_with_uid(uid, email, username, password):
"""Adds a user to the database, returning their ID."""
query = f"""
INSERT INTO Users VALUES ({uid}, '{email}', 'blah', '{username}', '{User.hash_password(password)}');
"""
cur.execute(query)
conn.commit()