6
0

Label.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. from contextlib import closing
  2. class Label:
  3. """
  4. database class for labels
  5. """
  6. def __init__(self, database, row):
  7. self.database = database
  8. self.identifier = row[0]
  9. self.project_id = row[1]
  10. self.parent_id = row[2]
  11. self.created = row[3]
  12. self.reference = row[4]
  13. self.name = row[5]
  14. self.hierarchy_level = row[6]
  15. def project(self):
  16. """
  17. get the project this label is associated with
  18. :return: project
  19. """
  20. return self.database.project(self.project_id)
  21. def set_name(self, name: str):
  22. """
  23. set this labels name
  24. :param name: new name
  25. :return:
  26. """
  27. with closing(self.database.con.cursor()) as cursor:
  28. cursor.execute('UPDATE labels SET name = ? WHERE id = ?', (name, self.identifier))
  29. self.name = name
  30. def set_parent(self, parent_id: int):
  31. """
  32. set this labels parent
  33. :param parent_id: parent's id
  34. :return:
  35. """
  36. # check for cyclic relationships
  37. def compare_children(label, identifier):
  38. if label.identifier == identifier:
  39. return False
  40. for child in label.children():
  41. if not compare_children(child, identifier):
  42. return False
  43. return True
  44. if not compare_children(self, parent_id):
  45. raise ValueError('parent_id')
  46. # insert parent id
  47. with closing(self.database.con.cursor()) as cursor:
  48. cursor.execute('UPDATE labels SET parent = ? WHERE id = ?',
  49. (parent_id, self.identifier))
  50. self.parent_id = parent_id
  51. def remove(self):
  52. """
  53. remove this label from the database
  54. :return:
  55. """
  56. with closing(self.database.con.cursor()) as cursor:
  57. cursor.execute('DELETE FROM labels WHERE id = ?', [self.identifier])
  58. def parent(self):
  59. """
  60. get this labels parent from the database
  61. :return: parent or None
  62. """
  63. if self.parent_id is None:
  64. return None
  65. with closing(self.database.con.cursor()) as cursor:
  66. cursor.execute('SELECT * FROM labels WHERE id = ? AND project = ?',
  67. (self.parent_id, self.project_id))
  68. row = cursor.fetchone()
  69. if row is not None:
  70. return Label(self.database, row)
  71. return None
  72. def children(self):
  73. """
  74. get this labels children from the database
  75. :return: list of children
  76. """
  77. with closing(self.database.con.cursor()) as cursor:
  78. cursor.execute('SELECT * FROM labels WHERE parent = ? AND project = ?',
  79. (self.identifier, self.project_id))
  80. return list(map(
  81. lambda row: Label(self.database, row),
  82. cursor.fetchall()
  83. ))