- def set_int_id(self, id_: int | None) -> None:
- """Set id_ if >= 1 or None, else fail."""
- if (id_ is not None) and id_ < 1:
- msg = f'illegal {self.__class__.__name__} ID, must be >=1: {id_}'
- raise HandledException(msg)
- self.id_ = id_ # type: ignore[assignment]
+ @classmethod
+ def by_id(cls, db_conn: DatabaseConnection,
+ id_: BaseModelId | None,
+ # pylint: disable=unused-argument
+ create: bool = False) -> Self:
+ """Retrieve by id_, on failure throw NotFoundException."""
+ obj = None
+ if id_ is not None:
+ obj = cls._by_id(db_conn, id_)
+ if obj:
+ return obj
+ if create:
+ obj = cls(id_)
+ return obj
+ raise NotFoundException(f'found no object of ID {id_}')
+
+ @classmethod
+ def all(cls: type[BaseModelInstance],
+ db_conn: DatabaseConnection) -> list[BaseModelInstance]:
+ """Collect all objects of class."""
+ items: dict[BaseModelId, BaseModelInstance] = {}
+ for k, v in cls.get_cache().items():
+ assert isinstance(v, cls)
+ items[k] = v
+ already_recorded = items.keys()
+ for id_ in db_conn.column_all(cls.table_name, 'id'):
+ if id_ not in already_recorded:
+ item = cls.by_id(db_conn, id_)
+ assert item.id_ is not None
+ items[item.id_] = item
+ return list(items.values())