1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- from __future__ import annotations
- from contextlib import closing
- from datetime import datetime
- from pycs import db
- from pycs.database.base import NamedBaseModel
- def compare_children(start_label: Label, id: int):
- """ check for cyclic relationships """
- labels_to_check = [start_label]
- while id is not None and labels_to_check:
- label = labels_to_check.pop(0)
- if label.id == id:
- return False
- labels_to_check.extend(label.children)
- return True
- def _Label_id():
- return Label.id
- class Label(NamedBaseModel):
- project_id = db.Column(
- db.Integer,
- db.ForeignKey("project.id", ondelete="CASCADE"),
- nullable=False)
- parent_id = db.Column(
- db.Integer,
- db.ForeignKey("label.id", ondelete="SET NULL"))
- created = db.Column(db.DateTime, default=datetime.utcnow,
- index=True, nullable=False)
- reference = db.Column(db.String)
- hierarchy_level = db.Column(db.String)
- # contraints
- __table_args__ = (
- db.UniqueConstraint('project_id', 'reference'),
- )
- # relationships to other models
- parent = db.relationship("Label",
- backref="children",
- remote_side=_Label_id,
- )
- results = db.relationship("Result",
- backref="label",
- passive_deletes=True,
- lazy="dynamic",
- )
- serialize_only = (
- "id",
- "name",
- "project_id",
- "parent_id",
- "reference",
- "children",
- )
- def set_parent(self, parent_id: int, commit: bool = True):
- """
- set this labels parent
- :param parent_id: parent's id
- :return:
- """
- if not compare_children(self, parent_id):
- raise ValueError('Cyclic relationship detected!')
- self.parent_id = parent_id
- if commit:
- self.commit()
|