home · contact · privacy
Add Process.children and improve Params/Postvars parsing and testing.
[plomtask] / plomtask / processes.py
index 8b5ff4221ea292b1c8bcffb787671b44129f0a66..bebd39456a804de397b6357919a0ceb0f245be3d 100644 (file)
@@ -3,17 +3,20 @@ from __future__ import annotations
 from sqlite3 import Row
 from datetime import datetime
 from plomtask.db import DatabaseConnection
-from plomtask.exceptions import NotFoundException
+from plomtask.exceptions import NotFoundException, BadFormatException
 
 
 class Process:
     """Template for, and metadata for, Todos, and their arrangements."""
 
     def __init__(self, id_: int | None) -> None:
-        self.id_ = id_ if id_ != 0 else None  # to avoid DB-confusing rowid=0
+        if (id_ is not None) and id_ < 1:
+            raise BadFormatException(f'illegal Process ID, must be >=1: {id_}')
+        self.id_ = id_
         self.title = VersionedAttribute(self, 'title', 'UNNAMED')
         self.description = VersionedAttribute(self, 'description', '')
         self.effort = VersionedAttribute(self, 'effort', 1.0)
+        self.child_ids: list[int] = []
 
     @classmethod
     def from_table_row(cls, row: Row) -> Process:
@@ -58,8 +61,15 @@ class Process:
             for row in db_conn.exec('SELECT * FROM process_efforts '
                                     'WHERE process_id = ?', (process.id_,)):
                 process.effort.history[row[1]] = row[2]
+            for row in db_conn.exec('SELECT * FROM process_children '
+                                    'WHERE parent_id = ?', (process.id_,)):
+                process.child_ids += [row[1]]
         return process
 
+    def children(self, db_conn: DatabaseConnection) -> list[Process]:
+        """Return child Processes as determined by self.child_ids."""
+        return [self.__class__.by_id(db_conn, id_) for id_ in self.child_ids]
+
     def save(self, db_conn: DatabaseConnection) -> None:
         """Add (or re-write) self and connected VersionedAttributes to DB."""
         cursor = db_conn.exec('REPLACE INTO processes VALUES (?)', (self.id_,))
@@ -67,6 +77,11 @@ class Process:
         self.title.save(db_conn)
         self.description.save(db_conn)
         self.effort.save(db_conn)
+        db_conn.exec('DELETE FROM process_children WHERE parent_id = ?',
+                     (self.id_,))
+        for child_id in self.child_ids:
+            db_conn.exec('INSERT INTO process_children VALUES (?, ?)',
+                         (self.id_, child_id))
 
 
 class VersionedAttribute: