-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
249 lines (221 loc) · 8.03 KB
/
database.py
File metadata and controls
249 lines (221 loc) · 8.03 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
from __future__ import annotations
import sqlite3
from datetime import date, datetime
from pathlib import Path
from typing import Optional
DATETIME_FMT = "%Y-%m-%d %H:%M:%S"
class TimeTrackerDB:
def __init__(self, db_path: Path) -> None:
self.db_path = db_path
self.db_path.parent.mkdir(parents=True, exist_ok=True)
self.conn = sqlite3.connect(self.db_path)
self.conn.row_factory = sqlite3.Row
self.conn.execute("PRAGMA foreign_keys = ON;")
self._init_schema()
self._ensure_default_project()
def _init_schema(self) -> None:
self.conn.executescript(
"""
CREATE TABLE IF NOT EXISTS projects (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE RESTRICT,
description TEXT NOT NULL DEFAULT '',
start_time TEXT NOT NULL,
end_time TEXT NOT NULL,
duration_seconds INTEGER NOT NULL CHECK (duration_seconds >= 0),
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_entries_start_time ON entries(start_time);
CREATE INDEX IF NOT EXISTS idx_entries_project_id ON entries(project_id);
CREATE TABLE IF NOT EXISTS active_session (
id INTEGER PRIMARY KEY CHECK (id = 1),
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
description TEXT NOT NULL DEFAULT '',
start_time TEXT NOT NULL
);
"""
)
self.conn.commit()
def _ensure_default_project(self) -> None:
count = self.conn.execute("SELECT COUNT(*) AS cnt FROM projects").fetchone()["cnt"]
if count == 0:
now = datetime.now().strftime(DATETIME_FMT)
self.conn.execute(
"INSERT INTO projects(name, created_at) VALUES(?, ?)",
("General", now),
)
self.conn.commit()
def close(self) -> None:
self.conn.close()
def list_projects(self) -> list[sqlite3.Row]:
rows = self.conn.execute(
"SELECT id, name FROM projects ORDER BY lower(name) ASC"
).fetchall()
return list(rows)
def add_project(self, name: str) -> None:
clean = name.strip()
if not clean:
raise ValueError("Project name cannot be empty.")
now = datetime.now().strftime(DATETIME_FMT)
self.conn.execute(
"INSERT INTO projects(name, created_at) VALUES(?, ?)",
(clean, now),
)
self.conn.commit()
def delete_project(self, project_id: int) -> None:
has_entries = self.conn.execute(
"SELECT COUNT(*) AS cnt FROM entries WHERE project_id = ?",
(project_id,),
).fetchone()["cnt"]
if has_entries:
raise ValueError("Project cannot be deleted because it has time entries.")
self.conn.execute("DELETE FROM active_session WHERE project_id = ?", (project_id,))
cur = self.conn.execute("DELETE FROM projects WHERE id = ?", (project_id,))
self.conn.commit()
if cur.rowcount == 0:
raise ValueError("Project not found.")
def create_entry(
self,
project_id: int,
description: str,
start_dt: datetime,
end_dt: datetime,
) -> None:
duration = int((end_dt - start_dt).total_seconds())
if duration <= 0:
raise ValueError("End time must be later than start time.")
now = datetime.now().strftime(DATETIME_FMT)
self.conn.execute(
"""
INSERT INTO entries(project_id, description, start_time, end_time, duration_seconds, created_at)
VALUES(?, ?, ?, ?, ?, ?)
""",
(
project_id,
description.strip(),
start_dt.strftime(DATETIME_FMT),
end_dt.strftime(DATETIME_FMT),
duration,
now,
),
)
self.conn.commit()
def list_entries(
self,
from_date: Optional[date] = None,
to_date: Optional[date] = None,
) -> list[sqlite3.Row]:
query = """
SELECT
e.id,
e.project_id,
p.name AS project_name,
e.description,
e.start_time,
e.end_time,
e.duration_seconds
FROM entries e
JOIN projects p ON p.id = e.project_id
"""
params: list[str] = []
conditions = []
if from_date is not None:
conditions.append("date(e.start_time) >= ?")
params.append(from_date.isoformat())
if to_date is not None:
conditions.append("date(e.start_time) <= ?")
params.append(to_date.isoformat())
if conditions:
query += " WHERE " + " AND ".join(conditions)
query += " ORDER BY e.start_time DESC"
rows = self.conn.execute(query, params).fetchall()
return list(rows)
def delete_entry(self, entry_id: int) -> None:
cur = self.conn.execute("DELETE FROM entries WHERE id = ?", (entry_id,))
self.conn.commit()
if cur.rowcount == 0:
raise ValueError("Entry not found.")
def update_entry(
self,
entry_id: int,
project_id: int,
description: str,
start_dt: datetime,
end_dt: datetime,
) -> None:
duration = int((end_dt - start_dt).total_seconds())
if duration <= 0:
raise ValueError("End time must be later than start time.")
cur = self.conn.execute(
"""
UPDATE entries
SET
project_id = ?,
description = ?,
start_time = ?,
end_time = ?,
duration_seconds = ?
WHERE id = ?
""",
(
project_id,
description.strip(),
start_dt.strftime(DATETIME_FMT),
end_dt.strftime(DATETIME_FMT),
duration,
entry_id,
),
)
self.conn.commit()
if cur.rowcount == 0:
raise ValueError("Entry not found.")
def set_active_session(
self,
project_id: int,
description: str,
start_dt: datetime,
) -> None:
self.conn.execute(
"""
INSERT INTO active_session(id, project_id, description, start_time)
VALUES(1, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
project_id = excluded.project_id,
description = excluded.description,
start_time = excluded.start_time
""",
(project_id, description.strip(), start_dt.strftime(DATETIME_FMT)),
)
self.conn.commit()
def clear_active_session(self) -> None:
self.conn.execute("DELETE FROM active_session WHERE id = 1")
self.conn.commit()
def get_active_session(self) -> Optional[sqlite3.Row]:
row = self.conn.execute(
"""
SELECT
s.project_id,
p.name AS project_name,
s.description,
s.start_time
FROM active_session s
JOIN projects p ON p.id = s.project_id
WHERE s.id = 1
"""
).fetchone()
return row
def total_seconds_between(self, start_dt: datetime, end_dt: datetime) -> int:
row = self.conn.execute(
"""
SELECT COALESCE(SUM(duration_seconds), 0) AS total
FROM entries
WHERE start_time >= ? AND start_time < ?
""",
(start_dt.strftime(DATETIME_FMT), end_dt.strftime(DATETIME_FMT)),
).fetchone()
return int(row["total"])