| 21 | |
| 22 | |
| 23 | class TreeNode(MappedAsDataclass, Base): |
| 24 | __tablename__ = "tree" |
| 25 | |
| 26 | id: Mapped[int] = mapped_column(primary_key=True, init=False) |
| 27 | parent_id: Mapped[Optional[int]] = mapped_column( |
| 28 | ForeignKey("tree.id"), init=False |
| 29 | ) |
| 30 | name: Mapped[str] |
| 31 | |
| 32 | children: Mapped[Dict[str, TreeNode]] = relationship( |
| 33 | cascade="all, delete-orphan", |
| 34 | back_populates="parent", |
| 35 | collection_class=attribute_keyed_dict("name"), |
| 36 | init=False, |
| 37 | repr=False, |
| 38 | ) |
| 39 | |
| 40 | parent: Mapped[Optional[TreeNode]] = relationship( |
| 41 | back_populates="children", remote_side=id, default=None |
| 42 | ) |
| 43 | |
| 44 | def dump(self, _indent: int = 0) -> str: |
| 45 | return ( |
| 46 | " " * _indent |
| 47 | + repr(self) |
| 48 | + "\n" |
| 49 | + "".join([c.dump(_indent + 1) for c in self.children.values()]) |
| 50 | ) |
| 51 | |
| 52 | |
| 53 | if __name__ == "__main__": |
no test coverage detected