6
0

Label.py 2.9 KB

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