1 """Non-doable elements of ProcessStep/Todo chains."""
2 from __future__ import annotations
3 from sqlite3 import Row
4 from plomtask.db import DatabaseConnection, BaseModel
5 from plomtask.misc import VersionedAttribute
6 from plomtask.exceptions import NotFoundException
9 class Condition(BaseModel):
10 """Non Process-dependency for ProcessSteps and Todos."""
11 table_name = 'conditions'
12 to_save = ['is_active']
14 def __init__(self, id_: int | None, is_active: bool = False) -> None:
16 self.is_active = is_active
17 self.title = VersionedAttribute(self, 'condition_titles', 'UNNAMED')
18 self.description = VersionedAttribute(self, 'condition_descriptions',
22 def from_table_row(cls, db_conn: DatabaseConnection,
23 row: Row) -> Condition:
24 """Build condition from row, including VersionedAttributes."""
25 condition = super().from_table_row(db_conn, row)
26 assert isinstance(condition, Condition)
27 for title_row in db_conn.exec('SELECT * FROM condition_titles '
28 'WHERE parent_id = ?', (row[0],)):
29 condition.title.history[title_row[1]]\
30 = title_row[2] # pylint: disable=no-member
31 for desc_row in db_conn.exec('SELECT * FROM condition_descriptions '
32 'WHERE parent_id = ?', (row[0],)):
33 condition.description.history[desc_row[1]]\
34 = desc_row[2] # pylint: disable=no-member
38 def all(cls, db_conn: DatabaseConnection) -> list[Condition]:
39 """Collect all Conditions and their VersionedAttributes."""
41 for id_, condition in db_conn.cached_conditions.items():
42 conditions[id_] = condition
43 already_recorded = conditions.keys()
44 for row in db_conn.exec('SELECT id FROM conditions'):
45 if row[0] not in already_recorded:
46 condition = cls.by_id(db_conn, row[0])
47 conditions[condition.id_] = condition
48 return list(conditions.values())
51 def by_id(cls, db_conn: DatabaseConnection, id_: int | None,
52 create: bool = False) -> Condition:
53 """Collect (or create) Condition and its VersionedAttributes."""
55 if id_ in db_conn.cached_conditions.keys():
56 condition = db_conn.cached_conditions[id_]
58 for row in db_conn.exec('SELECT * FROM conditions WHERE id = ?',
60 condition = cls.from_table_row(db_conn, row)
64 raise NotFoundException(f'Condition not found of id: {id_}')
65 condition = cls(id_, False)
68 def save(self, db_conn: DatabaseConnection) -> None:
69 """Save self and its VersionedAttributes to DB and cache."""
70 self.save_core(db_conn)
71 self.title.save(db_conn)
72 self.description.save(db_conn)
73 assert isinstance(self.id_, int)
74 db_conn.cached_conditions[self.id_] = self