home · contact · privacy
Refactor models' .by_id().
[plomtask] / plomtask / conditions.py
index 9fab77fc118d81bb650116ec307150fc390532ba..80fc13e4f0a68a9784cc1ec510311f76c0e44320 100644 (file)
@@ -1,5 +1,6 @@
 """Non-doable elements of ProcessStep/Todo chains."""
 from __future__ import annotations
+from typing import Any
 from sqlite3 import Row
 from plomtask.db import DatabaseConnection, BaseModel
 from plomtask.misc import VersionedAttribute
@@ -20,7 +21,7 @@ class Condition(BaseModel):
 
     @classmethod
     def from_table_row(cls, db_conn: DatabaseConnection,
-                       row: Row) -> Condition:
+                       row: Row | list[Any]) -> Condition:
         """Build condition from row, including VersionedAttributes."""
         condition = super().from_table_row(db_conn, row)
         assert isinstance(condition, Condition)
@@ -52,17 +53,14 @@ class Condition(BaseModel):
               create: bool = False) -> Condition:
         """Collect (or create) Condition and its VersionedAttributes."""
         condition = None
-        if id_ in db_conn.cached_conditions.keys():
-            condition = db_conn.cached_conditions[id_]
-        else:
-            for row in db_conn.exec('SELECT * FROM conditions WHERE id = ?',
-                                    (id_,)):
-                condition = cls.from_table_row(db_conn, row)
-                break
+        if id_:
+            condition, _ = super()._by_id(db_conn, id_)
         if not condition:
             if not create:
                 raise NotFoundException(f'Condition not found of id: {id_}')
             condition = cls(id_, False)
+            condition.save(db_conn)
+        assert isinstance(condition, Condition)
         return condition
 
     def save(self, db_conn: DatabaseConnection) -> None: