Label.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. from __future__ import annotations
  2. import typing as T
  3. from datetime import datetime
  4. from pycs import db
  5. from pycs.database.base import NamedBaseModel
  6. from pycs.database.util import commit_on_return
  7. def compare_children(start_label: Label, identifier: int) -> bool:
  8. """ check for cyclic relationships """
  9. labels_to_check = [start_label]
  10. while labels_to_check:
  11. label = labels_to_check.pop(0)
  12. if label.id == identifier:
  13. return False
  14. labels_to_check.extend(label.children)
  15. return True
  16. def _label_id():
  17. return Label.id
  18. class Label(NamedBaseModel):
  19. """ DB Model for labels """
  20. id = db.Column(db.Integer, primary_key=True)
  21. project_id = db.Column(
  22. db.Integer,
  23. db.ForeignKey("project.id", ondelete="CASCADE"),
  24. nullable=False)
  25. parent_id = db.Column(
  26. db.Integer,
  27. db.ForeignKey("label.id", ondelete="SET NULL"))
  28. created = db.Column(db.DateTime, default=datetime.utcnow,
  29. index=True, nullable=False)
  30. reference = db.Column(db.String)
  31. # contraints
  32. __table_args__ = (
  33. db.UniqueConstraint('project_id', 'reference'),
  34. )
  35. # relationships to other models
  36. parent = db.relationship("Label",
  37. backref="children",
  38. remote_side=_label_id)
  39. results = db.relationship("Result",
  40. backref="label",
  41. passive_deletes=True,
  42. lazy="dynamic",
  43. )
  44. serialize_only = NamedBaseModel.serialize_only + (
  45. "project_id",
  46. "parent_id",
  47. "reference",
  48. "children",
  49. )
  50. @commit_on_return
  51. def set_parent(self, parent: T.Optional[T.Union[int, str, Label]] = None) -> None:
  52. """
  53. set this labels parent
  54. :param parent: parent label. Can be a reference, an id or a Label instance
  55. :return:
  56. """
  57. parent_id = None
  58. if parent is not None:
  59. if isinstance(parent, Label):
  60. parent_id = parent.id
  61. elif isinstance(parent, str):
  62. parent_id = Label.query.filter(Label.reference == parent).one().id
  63. elif isinstance(parent, int):
  64. parent_id = parent
  65. if not compare_children(self, parent_id):
  66. raise ValueError('Cyclic relationship detected!')
  67. self.parent_id = parent_id