home · contact · privacy
Cache DB objects to ensure we do not accidentally edit clones.
[plomtask] / plomtask / todos.py
index 7150f0d702c44ec89e170e5381b20c8e61ea42ae..f1d98ad3a0719c3027bc55620b5f6a97be2ab628 100644 (file)
@@ -17,37 +17,43 @@ class Todo:
         self.is_done = is_done
         self.day = day
 
-    def __eq__(self, other: object) -> bool:
-        return isinstance(other, self.__class__) and self.id_ == other.id_
-
     @classmethod
-    def from_table_row(cls, row: Row, db_conn: DatabaseConnection) -> Todo:
-        """Make Todo from database row."""
-        return cls(id_=row[0],
+    def from_table_row(cls, db_conn: DatabaseConnection, row: Row) -> Todo:
+        """Make Todo from database row, write to DB cache."""
+        todo = cls(id_=row[0],
                    process=Process.by_id(db_conn, row[1]),
                    is_done=row[2],
                    day=Day.by_date(db_conn, row[3]))
+        assert todo.id_ is not None
+        db_conn.cached_todos[todo.id_] = todo
+        return todo
 
     @classmethod
     def by_id(cls, db_conn: DatabaseConnection, id_: int) -> Todo:
-        """Get Todo of .id_=id_."""
+        """Get Todo of .id_=id_ – from DB cache if possible."""
+        if id_ in db_conn.cached_todos.keys():
+            todo = db_conn.cached_todos[id_]
+            assert isinstance(todo, Todo)
+            return todo
         for row in db_conn.exec('SELECT * FROM todos WHERE id = ?', (id_,)):
-            return cls.from_table_row(row, db_conn)
+            return cls.from_table_row(db_conn, row)
         raise NotFoundException(f'Todo of ID not found: {id_}')
 
     @classmethod
     def by_date(cls, db_conn: DatabaseConnection, date: str) -> list[Todo]:
         """Collect all Todos for Day of date."""
         todos = []
-        for row in db_conn.exec('SELECT * FROM todos WHERE day = ?', (date,)):
-            todos += [cls.from_table_row(row, db_conn)]
+        for row in db_conn.exec('SELECT id FROM todos WHERE day = ?', (date,)):
+            todos += [cls.by_id(db_conn, row[0])]
         return todos
 
     def save(self, db_conn: DatabaseConnection) -> None:
-        """Write self to DB."""
+        """Write self to DB and its cache."""
         if self.process.id_ is None:
             raise NotFoundException('Process of Todo without ID (not saved?)')
         cursor = db_conn.exec('REPLACE INTO todos VALUES (?,?,?,?)',
                               (self.id_, self.process.id_,
                                self.is_done, self.day.date))
         self.id_ = cursor.lastrowid
+        assert self.id_ is not None
+        db_conn.cached_todos[self.id_] = self