2 from __future__ import annotations
3 from sqlite3 import Row
4 from plomtask.db import DatabaseConnection
5 from plomtask.days import Day
6 from plomtask.processes import Process
7 from plomtask.exceptions import NotFoundException
11 """Individual actionable."""
13 def __init__(self, id_: int | None, process: Process,
14 is_done: bool, day: Day) -> None:
16 self.process = process
17 self.is_done = is_done
21 def from_table_row(cls, db_conn: DatabaseConnection, row: Row) -> Todo:
22 """Make Todo from database row, write to DB cache."""
23 todo = cls(id_=row[0],
24 process=Process.by_id(db_conn, row[1]),
26 day=Day.by_date(db_conn, row[3]))
27 assert todo.id_ is not None
28 db_conn.cached_todos[todo.id_] = todo
32 def by_id(cls, db_conn: DatabaseConnection, id_: int) -> Todo:
33 """Get Todo of .id_=id_ – from DB cache if possible."""
34 if id_ in db_conn.cached_todos.keys():
35 todo = db_conn.cached_todos[id_]
36 assert isinstance(todo, Todo)
38 for row in db_conn.exec('SELECT * FROM todos WHERE id = ?', (id_,)):
39 return cls.from_table_row(db_conn, row)
40 raise NotFoundException(f'Todo of ID not found: {id_}')
43 def by_date(cls, db_conn: DatabaseConnection, date: str) -> list[Todo]:
44 """Collect all Todos for Day of date."""
46 for row in db_conn.exec('SELECT id FROM todos WHERE day = ?', (date,)):
47 todos += [cls.by_id(db_conn, row[0])]
50 def save(self, db_conn: DatabaseConnection) -> None:
51 """Write self to DB and its cache."""
52 if self.process.id_ is None:
53 raise NotFoundException('Process of Todo without ID (not saved?)')
54 cursor = db_conn.exec('REPLACE INTO todos VALUES (?,?,?,?)',
55 (self.id_, self.process.id_,
56 self.is_done, self.day.date))
57 self.id_ = cursor.lastrowid
58 assert self.id_ is not None
59 db_conn.cached_todos[self.id_] = self