-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.py
105 lines (91 loc) · 2.7 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
import sqlite3
from sqlite3 import Error
db_file = "songs.db"
def create_connection():
conn = None
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return conn
def new_song(song_id, plays = 0, db = create_connection()):
if(check_if_exists(song_id, db)):
return
if(song_id == None):
return
sql = ''' INSERT INTO songs(id,plays)VALUES(?,?) '''
try:
cur = db.cursor()
cur.execute(sql, [song_id, plays])
db.commit()
return cur.lastrowid
except Error as e:
print(e)
def get_song_plays(song_id, db = create_connection()):
if(not check_if_exists(song_id, db)):
return 0
sql = ' SELECT plays FROM songs WHERE id = "' + str(song_id) + '" '
try:
cur = db.cursor()
cur.execute(sql)
return cur.fetchall()[0][0]
except Error as e:
print(e)
def update_song(song_id, plays = 0, db = create_connection()):
if(not check_if_exists(song_id, db)):
new_song(song_id, plays, db)
return
if(song_id == None):
return
sql = ' UPDATE songs SET plays = "' + str(plays) + '" WHERE id = "' + str(song_id) + '" '
try:
cur = db.cursor()
cur.execute(sql)
db.commit()
return cur.lastrowid
except Error as e:
print(e)
def create_tables(db = create_connection()):
sql_create_tables = """ CREATE TABLE IF NOT EXISTS songs (
id TEXT PRIMARY KEY,
plays INTEGER
); """
try:
c = db.cursor()
c.execute(sql_create_tables)
except Error as e:
print(e)
def check_if_exists(song_id, db = create_connection()):
if(song_id == None):
return False
sql = 'SELECT EXISTS(SELECT 1 FROM songs WHERE id="' + str(song_id) + '");'
try:
c = db.cursor()
c.execute(sql)
i = c.fetchall()[0][0]
if(i > 0):
return True
return False
except Error as e:
print(e)
def get_top_song(count = 10, db = create_connection()):
sql = 'SELECT * FROM songs WHERE NOT id = "time_spent" ORDER BY plays DESC LIMIT ' + str(count)
try:
cur = db.cursor()
cur.execute(sql)
return cur.fetchall()
except Error as e:
print(e)
def get_stream_count(db = create_connection()):
sql = 'SELECT SUM(plays) FROM songs WHERE NOT id = "time_spent"'
try:
cur = db.cursor()
cur.execute(sql)
return cur.fetchall()[0][0]
except Error as e:
print(e)
return 0
def new_record(song_id, db = create_connection()):
update_song(song_id, get_song_plays(song_id, db) + 1, db)
create_tables()