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, BadFormatException,
12 """Individual actionable."""
14 def __init__(self, id_: int | None, process: Process,
15 is_done: bool, day: Day) -> None:
17 self.process = process
18 self.is_done = is_done
20 self.children: list[Todo] = []
23 def from_table_row(cls, db_conn: DatabaseConnection, row: Row) -> Todo:
24 """Make Todo from database row, write to DB cache."""
25 todo = cls(id_=row[0],
26 process=Process.by_id(db_conn, row[1]),
28 day=Day.by_date(db_conn, row[3]))
29 assert todo.id_ is not None
30 db_conn.cached_todos[todo.id_] = todo
34 def by_id(cls, db_conn: DatabaseConnection, id_: int | None) -> Todo:
35 """Get Todo of .id_=id_ and children (from DB cache if possible)."""
36 if id_ in db_conn.cached_todos.keys():
37 todo = db_conn.cached_todos[id_]
40 for row in db_conn.exec('SELECT * FROM todos WHERE id = ?',
42 todo = cls.from_table_row(db_conn, row)
45 raise NotFoundException(f'Todo of ID not found: {id_}')
46 for row in db_conn.exec('SELECT child FROM todo_children '
47 'WHERE parent = ?', (id_,)):
48 todo.children += [cls.by_id(db_conn, row[0])]
49 assert isinstance(todo, Todo)
53 def by_date(cls, db_conn: DatabaseConnection, date: str) -> list[Todo]:
54 """Collect all Todos for Day of date."""
56 for row in db_conn.exec('SELECT id FROM todos WHERE day = ?', (date,)):
57 todos += [cls.by_id(db_conn, row[0])]
60 def add_child(self, child: Todo) -> None:
61 """Add child to self.children, guard against recursion"""
62 def walk_steps(node: Todo) -> None:
63 if node.id_ == self.id_:
64 raise BadFormatException('bad child choice causes recursion')
65 for child in node.children:
68 raise HandledException('Can only add children to saved Todos.')
70 raise HandledException('Can only add saved children to Todos.')
71 if child in self.children:
72 raise BadFormatException('cannot adopt same child twice')
74 self.children += [child]
76 def save(self, db_conn: DatabaseConnection) -> None:
77 """Write self and children to DB and its cache."""
78 if self.process.id_ is None:
79 raise NotFoundException('Process of Todo without ID (not saved?)')
80 cursor = db_conn.exec('REPLACE INTO todos VALUES (?,?,?,?)',
81 (self.id_, self.process.id_,
82 self.is_done, self.day.date))
83 self.id_ = cursor.lastrowid
84 assert self.id_ is not None
85 db_conn.cached_todos[self.id_] = self
86 db_conn.exec('DELETE FROM todo_children WHERE parent = ?',
88 for child in self.children:
89 db_conn.exec('INSERT INTO todo_children VALUES (?, ?)',
90 (self.id_, child.id_))