-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdb_handler.py
More file actions
77 lines (59 loc) · 2.04 KB
/
db_handler.py
File metadata and controls
77 lines (59 loc) · 2.04 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
import sqlite3
import logging
class DbHandler:
def __init__(self):
self.conn = sqlite3.connect("favs.db", check_same_thread=False)
self.cursor = self.conn.cursor()
self.cursor.execute("""CREATE TABLE IF NOT EXISTS favs(
userId integer,
station integer,
name text,
PRIMARY KEY(userId, station)
);""")
self.cursor.execute("""CREATE TABLE IF NOT EXISTS users(
userId integer,
PRIMARY KEY(userId)
);""")
def addUserFav(self, user, station, name):
self.cursor.execute("""INSERT INTO favs
VALUES (?,?,?);
""", (user, station, name))
self.conn.commit()
def addUser(self, user):
self.cursor.execute("""INSERT INTO users
VALUES (?);
""", (user,))
self.conn.commit()
def deleteUserFav(self, user, station):
self.cursor.execute("""DELETE FROM favs
WHERE userId=? AND station=?;""", (user,station))
self.conn.commit()
def getUserFavs(self, user):
self.cursor.execute("""SELECT * FROM favs
WHERE userId=?;""",(user,))
rows = self.cursor.fetchall()
stations = []
for row in rows:
_, station, name = tuple(row)
stations.append((str(station), name))
return stations
def getAllUsers(self):
self.cursor.execute("""SELECT * FROM users;""")
rows = self.cursor.fetchall()
users = []
for row in rows:
user = row[0]
users.append(user)
return users
def check_duplicate(self, user, station):
self.cursor.execute("""SELECT * FROM favs
WHERE userId=? AND station=?;""",(user, station))
return len(self.cursor.fetchall()) > 0
def check_duplicate_user(self, user):
self.cursor.execute("""SELECT * FROM users
WHERE userId=?;""",(user,))
return len(self.cursor.fetchall()) > 0
def save(self):
self.conn.commit()
self.conn.close()
logging.info(msg="Saving database")