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 9.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. #-*- coding: utf-8 -*-
  2. import copy
  3. import re
  4. import warnings
  5. import EditorialModel.classtypes
  6. import EditorialModel.fieldtypes.leo as ft_leo
  7. from . import lecrud
  8. from . import leobject
  9. from . import lefactory
  10. ## @brief Main class for relations
  11. class _LeRelation(lecrud._LeCrud):
  12. _superior_field_name = None
  13. _subordinate_field_name = None
  14. ## @brief Stores the list of fieldtypes that are common to all relations
  15. _rel_fieldtypes = dict()
  16. def __init__(self, id_relation, **kwargs):
  17. super().__init__(id_relation, **kwargs)
  18. ## @brief Forge a filter to match the superior
  19. @classmethod
  20. def sup_filter(self, leo):
  21. if isinstance(leo, leobject._LeObject):
  22. return (self._superior_field_name, '=', leo)
  23. ## @brief Forge a filter to match the superior
  24. @classmethod
  25. def sub_filter(self, leo):
  26. if isinstance(leo, leobject._LeObject):
  27. return (self._subordinate_field_name, '=', leo)
  28. ## @return a dict with field name as key and fieldtype instance as value
  29. @classmethod
  30. def fieldtypes(cls):
  31. rel_ft = dict()
  32. rel_ft.update(cls._uid_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 [cls._superior_field_name, cls._subordinate_field_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. raise NotImplemented("Abtract method")
  91. ## @brief Implements set_rank
  92. def _set_rank(self, new_rank, **get_max_rank_args):
  93. max_rank = self.get_max_rank(**get_max_rank_args)
  94. try:
  95. new_rank = int(new_rank)
  96. except ValueError:
  97. if new_rank == 'first':
  98. new_rank = 1
  99. elif new_rank == 'last':
  100. new_rank = max_rank
  101. else:
  102. raise ValueError("The new rank can be an integer > 1 or strings 'first' or 'last', but %s given"%new_rank)
  103. if self.rank == new_rank:
  104. return True
  105. if new_rank < 1:
  106. if strict:
  107. raise ValueError("Rank must be >= 1, but %d given"%rank)
  108. new_rank = 1
  109. elif new_rank > max_rank:
  110. if strict:
  111. raise ValueError("Rank is too big (max_rank = %d), but %d given"%(max_rank,rank))
  112. new_rank = max_rank
  113. self._datasource.update_rank(self, new_rank)
  114. ## @returns The maximum assignable rank for this relation
  115. # @todo implementation
  116. def get_max_rank(self):
  117. raise NotImplemented("Abstract method")
  118. ## @brief Abstract class to handle hierarchy relations
  119. class _LeHierarch(_LeRelation):
  120. ## @brief Delete current instance from DB
  121. def delete(self):
  122. lecrud._LeCrud._delete(self)
  123. ## @brief modify a LeHierarch rank
  124. # @param new_rank int|str : The new rank can be an integer > 1 or strings 'first' or 'last'
  125. # @return True in case of success, False in case of failure
  126. # @throw ValueError if step is not castable into an integer
  127. def set_rank(self, new_rank):
  128. return self._set_rank(
  129. new_rank,
  130. id_superior=getattr(self, self.uidname()),
  131. nature=self.nature
  132. )
  133. @classmethod
  134. def insert(cls, datas):
  135. # Checks if the relation exists
  136. res = cls.get(
  137. [(cls._subordinate_field_name, '=', datas['subordinate']), ('nature', '=', datas['nature'])],
  138. [ cls.uidname() ]
  139. )
  140. if not(res is None) and len(res) > 0:
  141. return False
  142. return super().insert(datas, 'LeHierarch')
  143. ## @brief Get maximum assignable rank given a superior id and a nature
  144. # @return an integer > 1
  145. @classmethod
  146. def get_max_rank(cls, id_superior, nature):
  147. if nature not in EditorialModel.classtypes.EmNature.getall():
  148. raise ValueError("Unknow relation nature '%s'" % nature)
  149. sql_res = cls.get(
  150. query_filters=[
  151. ('nature','=', nature),
  152. (cls._superior_field_name, '=', id_superior),
  153. ],
  154. field_list=['rank'],
  155. order=[('rank', 'DESC')],
  156. limit=1,
  157. instanciate=False
  158. )
  159. return sql_res[0]['rank']+1 if not(sql_res is None) and len(sql_res) > 0 else 1
  160. ## @brief instanciate the relevant lodel object using a dict of datas
  161. @classmethod
  162. def object_from_data(cls, datas):
  163. return cls.name2class('LeHierarch')(**datas)
  164. ## @brief Abstract class to handle rel2type relations
  165. class _LeRel2Type(_LeRelation):
  166. ## @brief Stores the list of fieldtypes handling relations attributes
  167. _rel_attr_fieldtypes = dict()
  168. ## @brief Stores the LeClass child class used as superior
  169. _superior_cls = None
  170. ## @biref Stores the LeType child class used as subordinate
  171. _subordinate_cls = None
  172. ## @brief Delete current instance from DB
  173. def delete(self):
  174. lecrud._LeCrud._delete(self)
  175. ## @brief modify a LeRel2Type rank
  176. # @param new_rank int|str : The new rank can be an integer > 1 or strings 'first' or 'last'
  177. # @return True in case of success, False in case of failure
  178. # @throw ValueError if step is not castable into an integer
  179. def set_rank(self, new_rank):
  180. return self._set_rank(
  181. new_rank,
  182. id_superior=getattr(self, self.uidname()),
  183. type_em_id=self._subordinate_cls._type_id
  184. )
  185. @classmethod
  186. def get_max_rank(cls, id_superior, type_em_id):
  187. # SELECT rank FROM relation JOIN object ON object.lodel_id = id_subordinate WHERE object.type_id = <type_em_id>
  188. warnings.warn("LeRel2Type.get_max_rank() is not implemented yet and will always return 0")
  189. return 0
  190. ## @brief Implements insert for rel2type
  191. # @todo checks when autodetecing the rel2type class
  192. @classmethod
  193. def insert(cls, datas, classname = None):
  194. #Set the nature
  195. if 'nature' not in datas:
  196. datas['nature'] = None
  197. if cls == cls.name2class('LeRel2Type') and classname is None:
  198. # autodetect the rel2type child class
  199. classname = relname(datas[self._superior_field_name], datas[self._subordinate_field_name])
  200. return super().insert(datas, classname)
  201. ## @brief Given a superior and a subordinate, returns the classname of the give rel2type
  202. # @param lesupclass LeClass : LeClass child class (not an instance) (can be a LeType or a LeClass child)
  203. # @param lesubclass LeType : A LeType child class (not an instance)
  204. # @return a name as string
  205. @staticmethod
  206. def relname(lesupclass, lesubclass):
  207. supname = lesupclass._leclass.__name__ if lesupclass.implements_letype() else lesupclass.__name__
  208. subname = lesubclass.__name__
  209. return "Rel_%s2%s" % (supname, subname)
  210. ## @brief instanciate the relevant lodel object using a dict of datas
  211. @classmethod
  212. def object_from_data(cls, datas):
  213. le_object = cls.name2class('LeObject')
  214. class_name = le_object._me_uid[datas['class_id']].__name__
  215. type_name = le_object._me_uid[datas['type_id']].__name__
  216. relation_classname = lecrud._LeCrud.name2rel2type(class_name, type_name)
  217. del(datas['class_id'], datas['type_id'])
  218. return cls.name2class(relation_classname)(**datas)