No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

lerelation.py 6.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. #-*- coding: utf-8 -*-
  2. import copy
  3. import re
  4. import EditorialModel.fieldtypes.leo as ft_leo
  5. from . import lecrud
  6. from . import leobject
  7. from . import lefactory
  8. ## @brief Main class for relations
  9. class _LeRelation(lecrud._LeCrud):
  10. _lesup_name = None
  11. _lesub_name = None
  12. ## @brief Stores the list of fieldtypes that are common to all relations
  13. _rel_fieldtypes = dict()
  14. def __init__(self, rel_id, **kwargs):
  15. self.id_relation = rel_id
  16. ## @brief Forge a filter to match the superior
  17. @classmethod
  18. def sup_filter(self, leo):
  19. if isinstance(leo, leobject._LeObject):
  20. return (self._lesup_name, '=', leo)
  21. ## @brief Forge a filter to match the superior
  22. @classmethod
  23. def sub_filter(self, leo):
  24. if isinstance(leo, leobject._LeObject):
  25. return (self._lesub_name, '=', leo)
  26. ## @return a dict with field name as key and fieldtype instance as value
  27. @classmethod
  28. def fieldtypes(cls):
  29. rel_ft = dict()
  30. rel_ft.update(cls._uid_fieldtype)
  31. rel_ft.update(cls._lesup_fieldtype)
  32. rel_ft.update(cls._lesub_fieldtype)
  33. rel_ft.update(cls._rel_fieldtypes)
  34. if cls.implements_lerel2type():
  35. rel_ft.update(cls._rel_attr_fieldtypes)
  36. return rel_ft
  37. @classmethod
  38. def _prepare_relational_fields(cls, field):
  39. return lecrud.LeApiQueryError("Relational field '%s' given but %s doesn't is not a LeObject" % (field,
  40. cls.__name__))
  41. ## @brief Prepare filters before sending them to the datasource
  42. # @param cls : Concerned class
  43. # @param filters_l list : List of filters
  44. # @return prepared and checked filters
  45. @classmethod
  46. def _prepare_filters(cls, filters_l):
  47. filters, rel_filters = super()._prepare_filters(filters_l)
  48. res_filters = list()
  49. for field, op, value in filters:
  50. if field in [self._lesup_name, self._lesub_name]:
  51. if isinstance(value, str):
  52. try:
  53. value = int(value)
  54. except ValueError as e:
  55. raise LeApiDataCheckError("Wrong value given for '%s'"%field)
  56. if isinstance(value, int):
  57. value = cls.name2class('LeObject')(value)
  58. res_filters.append( (field, op, value) )
  59. return res_filters, rel_filters
  60. @classmethod
  61. ## @brief deletes a relation between two objects
  62. # @param filters_list list
  63. # @param target_class str
  64. def delete(cls, filters_list, target_class):
  65. filters, rel_filters = cls._prepare_filters(filters_list)
  66. if isinstance(target_class, str):
  67. target_class = cls.name2class(target_class)
  68. ret = cls._datasource.delete(target_class, filters)
  69. return True if ret == 1 else False
  70. ## @brief move to the first rank
  71. # @return True in case of success, False in case of failure
  72. def move_first(self):
  73. return self.set_rank('first')
  74. ## @brief move to the last rank
  75. # @return True in case of success, False in case of failure
  76. def move_last(self):
  77. return self.set_rank('last')
  78. ## @brief move to the given rank defined by a shift step
  79. # @param step int : The step
  80. # @return True in case of success, False in case of failure
  81. # @throw ValueError if step is not castable into an integer
  82. def shift_rank(self, step):
  83. step = int(step)
  84. return self.set_rank(self.rank + step)
  85. ## @brief modify a relation rank
  86. # @param new_rank int|str : The new rank can be an integer > 1 or strings 'first' or 'last'
  87. # @return True in case of success, False in case of failure
  88. # @throw ValueError if step is not castable into an integer
  89. def set_rank(self, new_rank):
  90. max_rank = self.get_max_rank()
  91. try:
  92. new_rank = int(new_rank)
  93. except ValueError:
  94. if new_rank == 'first':
  95. new_rank = 1
  96. elif new_rank == 'last':
  97. new_rank = max_rank
  98. else:
  99. raise ValueError("The new rank can be an integer > 1 or strings 'first' or 'last', but %s given"%new_rank)
  100. if self.rank == new_rank:
  101. return True
  102. if new_rank < 1:
  103. if strict:
  104. raise ValueError("Rank must be >= 1, but %d given"%rank)
  105. new_rank = 1
  106. elif new_rank > max_rank:
  107. if strict:
  108. raise ValueError("Rank is too big (max_rank = %d), but %d given"%(max_rank,rank))
  109. new_rank = max_rank
  110. self._datasource.update_rank(self, new_rank)
  111. ## @returns The maximum assignable rank for this relation
  112. # @todo implementation
  113. def get_max_rank(self):
  114. max_rank_result = self.__class__.get(field_list=['rank'], order=[('rank', 'DESC')], limit=1)
  115. max_rank = int(max_rank_result[0].rank)
  116. return max_rank+1
  117. ## @brief Abstract class to handle hierarchy relations
  118. class _LeHierarch(_LeRelation):
  119. ## @brief Delete current instance from DB
  120. def delete(self):
  121. lecrud._LeCrud._delete(self)
  122. ## @brief Abstract class to handle rel2type relations
  123. class _LeRel2Type(_LeRelation):
  124. ## @brief Stores the list of fieldtypes handling relations attributes
  125. _rel_attr_fieldtypes = dict()
  126. ## @brief Delete current instance from DB
  127. def delete(self):
  128. lecrud._LeCrud._delete(self)
  129. ## @brief Implements insert for rel2type
  130. # @todo checks when autodetecing the rel2type class
  131. @classmethod
  132. def insert(cls, datas, classname = None):
  133. #Set the nature
  134. if 'nature' not in datas:
  135. datas['nature'] = None
  136. if cls == cls.name2class('LeRel2Type') and classname is None:
  137. # autodetect the rel2type child class
  138. classname = relname(datas[self._lesup_name], datas[self._lesub_name])
  139. return super().insert(datas, classname)
  140. ## @brief Given a superior and a subordinate, returns the classname of the give rel2type
  141. # @param lesupclass LeClass : LeClass child class (not an instance) (can be a LeType or a LeClass child)
  142. # @param lesubclass LeType : A LeType child class (not an instance)
  143. # @return a name as string
  144. @staticmethod
  145. def relname(lesupclass, lesubclass):
  146. supname = lesupclass._leclass.__name__ if lesupclass.implements_letype() else lesupclass.__name__
  147. subname = lesubclass.__name__
  148. return "Rel_%s2%s" % (supname, subname)