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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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 The name of the uniq id field
  29. @classmethod
  30. def uidname(cls):
  31. return EditorialModel.classtypes.relation_uid
  32. ## @return a dict with field name as key and fieldtype instance as value
  33. @classmethod
  34. def fieldtypes(cls):
  35. rel_ft = dict()
  36. rel_ft.update(cls._uid_fieldtype)
  37. rel_ft.update(cls._rel_fieldtypes)
  38. return rel_ft
  39. @classmethod
  40. def _prepare_relational_fields(cls, field):
  41. return lecrud.LeApiQueryError("Relational field '%s' given but %s doesn't is not a LeObject" % (field,
  42. cls.__name__))
  43. ## @brief Prepare filters before sending them to the datasource
  44. # @param cls : Concerned class
  45. # @param filters_l list : List of filters
  46. # @return prepared and checked filters
  47. @classmethod
  48. def _prepare_filters(cls, filters_l):
  49. filters, rel_filters = super()._prepare_filters(filters_l)
  50. res_filters = list()
  51. for field, op, value in filters:
  52. if field in [cls._superior_field_name, cls._subordinate_field_name]:
  53. if isinstance(value, str):
  54. try:
  55. value = int(value)
  56. except ValueError as e:
  57. raise LeApiDataCheckError("Wrong value given for '%s'"%field)
  58. if isinstance(value, int):
  59. value = cls.name2class('LeObject')(value)
  60. res_filters.append( (field, op, value) )
  61. return res_filters, rel_filters
  62. ## @brief move to the first rank
  63. # @return True in case of success, False in case of failure
  64. def move_first(self):
  65. return self.set_rank('first')
  66. ## @brief move to the last rank
  67. # @return True in case of success, False in case of failure
  68. def move_last(self):
  69. return self.set_rank('last')
  70. ## @brief move to the given rank defined by a shift step
  71. # @param step int : The step
  72. # @return True in case of success, False in case of failure
  73. # @throw ValueError if step is not castable into an integer
  74. def shift_rank(self, step):
  75. step = int(step)
  76. return self.set_rank(self.rank + step)
  77. ## @brief modify a relation rank
  78. # @param new_rank int|str : The new rank can be an integer > 1 or strings 'first' or 'last'
  79. # @return True in case of success, False in case of failure
  80. # @throw ValueError if step is not castable into an integer
  81. def set_rank(self, new_rank):
  82. raise NotImplemented("Abtract method")
  83. ## @brief Implements set_rank
  84. def _set_rank(self, new_rank, **get_max_rank_args):
  85. max_rank = self.get_max_rank(**get_max_rank_args)
  86. try:
  87. new_rank = int(new_rank)
  88. except ValueError:
  89. if new_rank == 'first':
  90. new_rank = 1
  91. elif new_rank == 'last':
  92. new_rank = max_rank
  93. else:
  94. raise ValueError("The new rank can be an integer > 1 or strings 'first' or 'last', but %s given"%new_rank)
  95. if self.rank == new_rank:
  96. return True
  97. if new_rank < 1:
  98. if strict:
  99. raise ValueError("Rank must be >= 1, but %d given"%rank)
  100. new_rank = 1
  101. elif new_rank > max_rank:
  102. if strict:
  103. raise ValueError("Rank is too big (max_rank = %d), but %d given"%(max_rank,rank))
  104. new_rank = max_rank
  105. self._datasource.update_rank(self, new_rank)
  106. ## @returns The maximum assignable rank for this relation
  107. # @todo implementation
  108. def get_max_rank(self):
  109. raise NotImplemented("Abstract method")
  110. ## @brief Abstract class to handle hierarchy relations
  111. class _LeHierarch(_LeRelation):
  112. ## @brief modify a LeHierarch rank
  113. # @param new_rank int|str : The new rank can be an integer > 1 or strings 'first' or 'last'
  114. # @return True in case of success, False in case of failure
  115. # @throw ValueError if step is not castable into an integer
  116. def set_rank(self, new_rank):
  117. return self._set_rank(
  118. new_rank,
  119. id_superior=getattr(self, self.uidname()),
  120. nature=self.nature
  121. )
  122. @classmethod
  123. def insert(cls, datas):
  124. # Checks if the relation exists
  125. datas[EditorialModel.classtypes.relation_name] = None
  126. res = cls.get(
  127. [(cls._subordinate_field_name, '=', datas['subordinate']), ('nature', '=', datas['nature'])],
  128. [ cls.uidname() ]
  129. )
  130. if not(res is None) and len(res) > 0:
  131. return False
  132. return super().insert(datas, 'LeHierarch')
  133. ## @brief Get maximum assignable rank given a superior id and a nature
  134. # @return an integer > 1
  135. @classmethod
  136. def get_max_rank(cls, id_superior, nature):
  137. if nature not in EditorialModel.classtypes.EmNature.getall():
  138. raise ValueError("Unknow relation nature '%s'" % nature)
  139. sql_res = cls.get(
  140. query_filters=[
  141. ('nature','=', nature),
  142. (cls._superior_field_name, '=', id_superior),
  143. ],
  144. field_list=['rank'],
  145. order=[('rank', 'DESC')],
  146. limit=1,
  147. instanciate=False
  148. )
  149. return sql_res[0]['rank']+1 if not(sql_res is None) and len(sql_res) > 0 else 1
  150. ## @brief instanciate the relevant lodel object using a dict of datas
  151. @classmethod
  152. def object_from_data(cls, datas):
  153. return cls.name2class('LeHierarch')(**datas)
  154. ## @warning Abastract method
  155. def update(self):
  156. raise NotImplementedError("Abstract method")
  157. ## @brief Abstract class to handle rel2type relations
  158. class _LeRel2Type(_LeRelation):
  159. ## @brief Stores the list of fieldtypes handling relations attributes
  160. _rel_attr_fieldtypes = dict()
  161. ## @brief Stores the LeClass child class used as superior
  162. _superior_cls = None
  163. ## @brief Stores the LeType child class used as subordinate
  164. _subordinate_cls = None
  165. ## @brief Stores the relation name for a rel2type
  166. _relation_name = None
  167. ## @brief modify a LeRel2Type rank
  168. # @param new_rank int|str : The new rank can be an integer > 1 or strings 'first' or 'last'
  169. # @return True in case of success, False in case of failure
  170. # @throw ValueError if step is not castable into an integer
  171. def set_rank(self, new_rank):
  172. if self._relation_name is None:
  173. raise NotImplementedError("Abstract method")
  174. return self._set_rank(new_rank, superior = self.superior, relation_name = self._relation_name)
  175. @classmethod
  176. def fieldtypes(cls, complete = True):
  177. ret = dict()
  178. if complete:
  179. ret.update(super().fieldtypes())
  180. ret.update(cls._rel_attr_fieldtypes)
  181. return ret
  182. @classmethod
  183. def get_max_rank(cls, superior, relation_name):
  184. # SELECT rank FROM relation JOIN object ON object.lodel_id = id_subordinate WHERE object.type_id = <type_em_id>
  185. ret = cls.get(
  186. query_filters = [
  187. (EditorialModel.classtypes.relation_name, '=', relation_name),
  188. (EditorialModel.classtypes.relation_superior, '=', superior),
  189. ],
  190. field_list = ['rank'],
  191. order = [('rank', 'DESC')],
  192. limit = 1,
  193. instanciate = False
  194. )
  195. return 1 if not ret else ret[0]['rank']
  196. ## @brief Implements insert for rel2type
  197. # @todo checks when autodetecing the rel2type class
  198. @classmethod
  199. def insert(cls, datas, classname = None):
  200. #Set the nature
  201. if 'nature' not in datas:
  202. datas['nature'] = None
  203. if cls.__name__ == 'LeRel2Type' and classname is None:
  204. if EditorialModel.classtypes.relation_name not in datas:
  205. raise RuntimeError("Unable to autodetect rel2type. No relation_name given")
  206. # autodetect the rel2type child class (BROKEN)
  207. classname = relname(datas[self._superior_field_name], datas[self._subordinate_field_name], datas[EditorialModel.classtypes.relation_name])
  208. else:
  209. if classname != None:
  210. ccls = cls.name2class(classname)
  211. if ccls == False:
  212. raise lecrud.LeApiErrors("Bad classname given")
  213. relation_name = ccls._relation_name
  214. else:
  215. relation_name = cls._relation_name
  216. datas[EditorialModel.classtypes.relation_name] = relation_name
  217. return super().insert(datas, classname)
  218. ## @brief Given a superior and a subordinate, returns the classname of the give rel2type
  219. # @param lesupclass LeClass : LeClass child class (not an instance) (can be a LeType or a LeClass child)
  220. # @param lesubclass LeType : A LeType child class (not an instance)
  221. # @param relation_name str : Name of the relation (rel2type field name in LeClass)
  222. # @param cls
  223. # @return a name as string
  224. @classmethod
  225. def relname(cls, lesupclass, lesubclass, relation_name):
  226. supname = lesupclass._leclass.__name__ if lesupclass.implements_letype() else lesupclass.__name__
  227. subname = lesubclass.__name__
  228. return cls.name2rel2type(supname, subname, relation_name)
  229. ## @brief instanciate the relevant lodel object using a dict of datas
  230. @classmethod
  231. def object_from_data(cls, datas):
  232. le_object = cls.name2class('LeObject')
  233. class_name = le_object._me_uid[datas['class_id']].__name__
  234. type_name = le_object._me_uid[datas['type_id']].__name__
  235. relation_classname = lecrud._LeCrud.name2rel2type(class_name, type_name, datas[EditorialModel.classtypes.relation_name])
  236. del(datas['class_id'], datas['type_id'])
  237. return cls.name2class(relation_classname)(**datas)