-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdatabase.py
More file actions
106 lines (86 loc) · 2.5 KB
/
database.py
File metadata and controls
106 lines (86 loc) · 2.5 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
from sqlite3 import connect, OperationalError
from dataclasses import astuple
class Database:
def __init__(self, path: str):
self.connection = None
self.open(path)
#
#
# Open the database, creating the file if it doesn't exist
#
#
def open(self, path: str):
# Close existing database
if self.connection != None:
self.connection.close()
self.connection = None
# Establish connection with database
self.connection = connect(path)
self.cursor = self.connection.cursor()
# Create table for breaks
try:
self.cursor.execute(self.TABLE_SCHEMA)
except OperationalError:
# Table already exists
pass
#
#
# Add an entry to the database
#
#
def add(self, info):
values = astuple(info)
command = f"INSERT INTO {self.TABLE_NAME} VALUES {values}"
self.cursor.execute(command)
self.connection.commit()
#
#
# Remove database entries.
#
# Returns:
# Number of entries removed
#
#
def remove(self, where: str) -> int:
assert not where.isspace() and len(where) > 0, "This will delete the entire table!"
command = f"DELETE FROM {self.TABLE_NAME} WHERE {where}"
self.cursor.execute(command)
self.connection.commit()
return self.cursor.rowcount
#
#
# Filter database entries.
#
# Returns:
# Search results copied from the DB
#
#
def filter(self, where: str, args: tuple = ()) -> list:
command = f"SELECT * FROM {self.TABLE_NAME} WHERE {where}"
self.cursor.execute(command, (*args,))
return self.cursor.fetchall()
#
#
# Get top database entries fulfulling a certain condition.
#
# Returns:
# Search results copied from the DB
#
#
def top(self, count: int, where: str, args: tuple = ()) -> list:
command = f"SELECT * FROM {self.TABLE_NAME} WHERE {where} LIMIT {count}"
self.cursor.execute(command, (*args,))
return self.cursor.fetchall()
#
#
# Count database entries fulfilling a certain condition.
#
# Returns:
# Number of search results
#
#
def count(self, where: str, args: tuple = ()) -> int:
command = f"SELECT COUNT (*) FROM {self.TABLE_NAME} WHERE {where}"
self.cursor.execute(command, (*args,))
result = self.cursor.fetchone()
return 0 if not result else result[0]