-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.py
73 lines (58 loc) · 1.48 KB
/
db.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
import sqlite3 as sql
from collections import namedtuple
# natively supported SQLite types
T = "TEXT"
I = "INTEGER"
F = "FLOAT"
R = 'REAL'
B = 'BLOB'
N = 'NULL'
class Database:
def __init__(self, dbfile, **kwargs):
# Start a connection to the database
self.connection = sql.connect(dbfile, **kwargs)
self.cursor = self.connection.cursor()
def revert(self):
self.connection.rollback()
Quote = namedtuple('Quote', 'id, author, quote')
class QuotesDB(Database):
def __init__(self, file):
super().__init__(file, check_same_thread=False)
def add_quote(self, **params):
with self.connection:
self.cursor.execute(
"INSERT INTO quotes (id, author, quote) VALUES (?, ?, ?)",
(params['id'], params['author'], params['quote'])
)
def delete_quote(self, id_):
try:
with self.connection:
self.cursor.execute(
"DELETE FROM quotes WHERE id=?",
(id_, )
)
return True
except sql.IntegrityError as error:
print(error)
return False
def exists(self, id_):
with self.connection:
self.cursor.execute(
"SELECT author FROM quotes WHERE id=?",
(id_)
)
return bool(self.fetchone())
def update_quote(self, id_, **params):
pass
def get_all_quotes(self, by=None):
with self.connection:
if by:
self.cursor.execute(
"SELECT id, author, quote FROM quotes WHERE author=?",
(by, )
)
else:
self.cursor.execute(
"SELECT id, author, quote FROM quotes",
)
return map(Quote._make, self.cursor.fetchall())