Label.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. )
  40. results = db.relationship("Result",
  41. backref="label",
  42. passive_deletes=True,
  43. lazy="dynamic",
  44. )
  45. serialize_only = NamedBaseModel.serialize_only + (
  46. "project_id",
  47. "parent_id",
  48. "reference",
  49. "children",
  50. )
  51. @commit_on_return
  52. def set_parent(self, parent: T.Optional[T.Union[int, str, Label]] = None) -> None:
  53. """
  54. set this labels parent
  55. :param parent: parent label. Can be a reference, an id or a Label instance
  56. :return:
  57. """
  58. parent_id = None
  59. if parent is not None:
  60. if isinstance(parent, Label):
  61. parent_id = parent.id
  62. elif isinstance(parent, str):
  63. parent_id = Label.query.filter(Label.reference == parent).one().id
  64. elif isinstance(parent, int):
  65. parent_id = parent
  66. if not compare_children(self, parent_id):
  67. raise ValueError('Cyclic relationship detected!')
  68. self.parent_id = parent_id