-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.py
76 lines (64 loc) · 2.96 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
import sqlite3
import datetime
from typing import List, Dict
class Database:
def __init__(self, db_location: str):
self.connection = sqlite3.connect(db_location)
self.connection.row_factory = sqlite3.Row # return row as dict
self._create()
def _create(self):
with self.connection as conn:
conn.execute("""CREATE TABLE IF NOT EXISTS planned_tasks (
name VARCHAR,
latitude FLOAT,
longitude FLOAT,
zoom FLOAT,
interval INT,
start_datetime DATETIME,
end_datetime DATETIME)""")
def delete_row(self, row: Dict):
"""Delete a row"""
if type(row['start_datetime']) == List:
row['start_datetime'] = row['start_datetime'][0]
row['end_datetime'] = row['end_datetime'][0]
print(f'{row = }')
with self.connection as conn:
conn.execute("""DELETE FROM planned_tasks WHERE (
name = :name AND
latitude = :latitude AND
longitude = :longitude AND
zoom = :zoom AND
interval = :interval AND
start_datetime = :start_datetime AND
end_datetime = :end_datetime)""",
row
)
def get_rows(self):
"""Returns raw list with rows as dicts"""
with self.connection as conn:
rows = [dict(row) for row in conn.execute('SELECT * from planned_tasks')]
return rows
def get_rows_generator(self):
"""Load all the data from the database"""
# Change datetime string to datetime object in a list
for row in self.get_rows():
row['start_datetime'] = [datetime.datetime.fromisoformat(row['start_datetime'])]
row['end_datetime'] = [datetime.datetime.fromisoformat(row['end_datetime'])]
yield row
def store(self, **kwargs):
"""Store new data in the database"""
with self.connection as conn:
for start_datetime, end_datetime in zip(kwargs['start_datetime'], kwargs['end_datetime']):
conn.execute("""INSERT INTO planned_tasks VALUES (?, ?, ?, ?, ?, ?, ?)""",
(kwargs['name'],
kwargs['latitude'],
kwargs['longitude'],
kwargs['zoom'],
kwargs['interval'],
start_datetime,
end_datetime)
)
def remove_old_rows(self):
"""Remove all rows where end time is in the past"""
with self.connection as conn:
conn.execute("""DELETE FROM planned_tasks WHERE end_datetime < DATETIME('NOW', 'LOCALTIME')""")