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.

leobject.py 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. #-*- coding: utf-8 -*-
  2. ## @package leobject API to access lodel datas
  3. #
  4. # This package contains abstract classes leapi.leclass.LeClass , leapi.letype.LeType, leapi.leapi._LeObject.
  5. # Those abstract classes are designed to be mother classes of dynamically generated classes ( see leapi.lefactory.LeFactory )
  6. ## @package leapi.leobject
  7. # @brief Abstract class designed to be implemented by LeObject
  8. #
  9. # @note LeObject will be generated by leapi.lefactory.LeFactory
  10. import re
  11. import copy
  12. import warnings
  13. import leapi
  14. from leapi.lecrud import _LeCrud
  15. from leapi.lefactory import LeFactory
  16. import EditorialModel
  17. from EditorialModel.types import EmType
  18. REL_SUP = 0
  19. REL_SUB = 1
  20. ## @brief Main class to handle objects defined by the types of an Editorial Model
  21. class _LeObject(_LeCrud):
  22. ## @brief maps em uid with LeType or LeClass keys are uid values are LeObject childs classes
  23. # @todo check if this attribute shouldn't be in _LeCrud
  24. _me_uid = dict()
  25. ## @brief Stores the fields name associated with fieldtype of the fields that are common to every LeObject
  26. _leo_fieldtypes = dict()
  27. ## @brief Instantiate with a Model and a DataSource
  28. # @param **kwargs dict : datas usefull to instanciate a _LeObject
  29. def __init__(self, **kwargs):
  30. raise NotImplementedError("Abstract constructor")
  31. ## @brief Given a ME uid return the corresponding LeClass or LeType class
  32. # @return a LeType or LeClass child class
  33. # @throw KeyError if no corresponding child classes
  34. # @todo check if this method shouldn't be in _LeCrud
  35. @classmethod
  36. def uid2leobj(cls, uid):
  37. uid = int(uid)
  38. if uid not in cls._me_uid:
  39. raise KeyError("No LeType or LeClass child classes with uid '%d'"%uid)
  40. return cls._me_uid[uid]
  41. @classmethod
  42. def fieldtypes(cls):
  43. if cls._fieldtypes_all is None:
  44. cls._fieldtypes_all = dict()
  45. cls._fieldtypes_all.update(cls._uid_fieldtype)
  46. cls._fieldtypes_all.update(cls._leo_fieldtypes)
  47. return cls._fieldtypes_all
  48. @classmethod
  49. def typefilter(cls):
  50. if hasattr(cls, '_type_id'):
  51. return ('type_id','=', cls._type_id)
  52. elif hasattr(cls, '_class_id'):
  53. return ('class_id', '=', cls._class_id)
  54. else:
  55. raise ValueError("Cannot generate a typefilter with %s class"%cls.__name__)
  56. ## @brief Delete LeObjects from db given filters and a classname
  57. # @note if no classname given, take the caller class
  58. # @param filters list :
  59. # @param classname None|str : the classname or None
  60. # @return number of deleted LeObjects
  61. # @see leapi.lecrud._LeCrud.delete()
  62. @classmethod
  63. def delete(cls, filters, classname = None):
  64. ccls = cls if classname is None else cls.name2class(classname)
  65. new_filters = copy.copy(filters)
  66. new_filters.append(ccls.typefilter())
  67. return _LeCrud.delete(ccls, new_filters)
  68. ## @brief Check that a relational field is valid
  69. # @param field str : a relational field
  70. # @return a nature
  71. @staticmethod
  72. def _prepare_relational_field(field):
  73. spl = field.split('.')
  74. if len(spl) != 2:
  75. return ValueError("The relationalfield '%s' is not valid"%field)
  76. nature = spl[-1]
  77. if nature not in EditorialModel.classtypes.EmNature.getall():
  78. return ValueError("'%s' is not a valid nature in the field %s"%(nature, field))
  79. if spl[0] == 'superior':
  80. return (REL_SUP, nature)
  81. elif spl[0] == 'subordinate':
  82. return (REL_SUB, nature)
  83. else:
  84. return ValueError("Invalid preffix for relationnal field : '%s'"%spl[0])
  85. ## @brief Check if a LeType is a hierarchy root
  86. @staticmethod
  87. def ___is_root(leo):
  88. if isinstance(leo, leapi.letype.LeType):
  89. return False
  90. elif isinstance(leo, LeRoot):
  91. return True
  92. raise ValueError("Invalid value for a LeType : %s"%leo)
  93. ## @brief Return a LeRoot instance
  94. @staticmethod
  95. def ___get_root():
  96. return LeRoot()
  97. ## @brief Link two leobject together using a rel2type field
  98. # @param lesup LeType : LeType child class instance linked as superior
  99. # @param lesub LeType : LeType child class instance linked as subordinate
  100. # @param **rel_attr : Relation attributes
  101. # @return True if linked without problems
  102. # @throw LeObjectError if the link is not valid
  103. # @throw LeObkectError if the link already exists
  104. # @throw AttributeError if an non existing relation attribute is given as argument
  105. # @throw ValueError if the relation attrivute value check fails
  106. #
  107. # @todo Code factorisation on relation check
  108. # @todo unit tests
  109. @classmethod
  110. def ___link_together(cls, lesup, lesub, rank = 'last', **rel_attr):
  111. if lesub.__class__ not in lesup._linked_types.keys():
  112. raise LeObjectError("Relation error : %s cannot be linked with %s"%(lesup.__class__.__name__, lesub.__class__.__name__))
  113. for attr_name in rel_attr.keys():
  114. if attr_name not in [ f for f,g in lesup._linked_types[lesub.__class__] ]:
  115. raise AttributeError("A rel2type between a %s and a %s doesn't have an attribute %s"%(lesup.__class__.__name__, lesub.__class__.__name__))
  116. if not sup._linked_types[lesub.__class__][1].check(rel_attr[attr_name]):
  117. raise ValueError("Wrong value '%s' for attribute %s"%(rel_attr[attr_name], attr_name))
  118. #Checks that attributes are uniq for this relation
  119. rels_attr = [ attrs for lesup, lesub, attrs in cls.links_get(lesup) if lesup == lesup ]
  120. for e_attrs in rels_attrs:
  121. if rel_attr == e_attrs:
  122. raise LeObjectError("Relation error : a relation with the same attributes already exists")
  123. return cls._datasource.add_related(lesup, lesub, rank, **rel_attr)
  124. ## @brief Get related objects
  125. # @param leo LeType(instance) : LeType child class instance
  126. # @param letype LeType(class) : the wanted LeType child class (not instance)
  127. # @param leo_is_superior bool : if True leo is the superior in the relation
  128. # @return A dict with LeType child class instance as key and dict {rel_attr_name:rel_attr_value, ...}
  129. # @throw LeObjectError if the relation is not possible
  130. #
  131. # @todo Code factorisation on relation check
  132. # @todo unit tests
  133. @classmethod
  134. def ___linked_together(cls, leo, letype, leo_is_superior = True):
  135. valid_link = letype in leo._linked_types.keys() if leo_is_superior else leo.__class__ in letype._linked_types.keys()
  136. if not valid_link:
  137. raise LeObjectError("Relation error : %s have no links with %s"%(
  138. leo.__class__ if leo_is_superior else letype,
  139. letype if leo_is_superior else leo.__class__
  140. ))
  141. return cls._datasource.get_related(leo, letype, leo_is_superior)
  142. ## @brief Fetch a relation and its attributes
  143. # @param id_relation int : the relation identifier
  144. # @return a tuple(lesup, lesub, dict_attr) or False if no relation exists with this id
  145. # @throw Exception if the relation is not a rel2type relation
  146. @classmethod
  147. def ___link_get(cls, id_relation):
  148. return cls._datasource.get_relation(id_relation)
  149. ## @brief Fetch all relations for an objects
  150. # @param leo LeType : LeType child class instance
  151. # @return a list of tuple (lesup, lesub, dict_attr)
  152. def ___links_get(cls, leo):
  153. return cls._datasource.get_relations(leo)
  154. ## @brief Remove a link (and attributes) between two LeObject
  155. # @param id_relation int : Relation identifier
  156. # @return True if a link has been deleted
  157. # @throw LeObjectError if the relation is not a rel2type
  158. #
  159. # @todo Code factorisation on relation check
  160. # @todo unit tests
  161. @classmethod
  162. def ___link_remove(cls, id_relation):
  163. if lesub.__class__ not in lesup._linked_types.keys():
  164. raise LeObjectError("Relation errorr : %s cannot be linked with %s"%(lesup.__class__.__name__, lesub.__class__.__name__))
  165. return cls._datasource.del_related(lesup, lesub)
  166. ## @brief Add a hierarchy relation between two LeObject
  167. # @param lesup LeType|LeRoot : LeType child class instance
  168. # @param lesub LeType : LeType child class instance
  169. # @param nature str : The nature of the relation @ref EditorialModel.classtypes
  170. # @param rank str|int : The relation rank. Can be 'last', 'first' or an integer
  171. # @param replace_if_exists bool : if True delete the old superior and set the new one. If False and there is a superior raise an LeObjectQueryError
  172. # @return The relation ID or False if fails
  173. # @throw LeObjectQueryError replace_if_exists == False and there is a superior
  174. @classmethod
  175. def ___hierarchy_add(cls, lesup, lesub, nature, rank = 'last', replace_if_exists = False):
  176. #Arguments check
  177. if nature not in EditorialModel.classtypes.EmClassType.natures(lesub._classtype):
  178. raise ValueError("Invalid nature '%s' for %s"%(nature, lesup.__class__.__name__))
  179. if not cls.leo_is_root(lesup):
  180. if nature not in EditorialModel.classtypes.EmClassType.natures(lesup._classtype):
  181. raise ValueError("Invalid nature '%s' for %s"%(nature, lesup.__class__.__name__))
  182. if lesup.__class__ not in lesub._superiors[nature]:
  183. raise ValueError("%s is not a valid superior for %s"%(lesup.__class__, lesub.__class__))
  184. #else:
  185. # lesup is not a LeType but a hierarchy root
  186. if rank not in ['first', 'last'] and not isinstance(rank, int):
  187. raise ValueError("Allowed values for rank are integers and 'first' or 'last' but '%s' found"%rank)
  188. superiors = cls.hierarchy_get(lesub, nature, leo_is_sup = False)
  189. if lesup in len(superiors) > 0:
  190. if not replace_if_exists:
  191. raise LeObjectQueryError("The subordinate allready has a superior")
  192. #remove existig superior
  193. if not cls.hierarchy_del(superiors[0], lesub, nature):
  194. raise RuntimeError("Unable to delete the previous superior")
  195. return self._datasource.add_superior(lesup, lesub, nature, rank)
  196. ## @brief Delete a hierarchy link between two LeObject
  197. # @param lesup LeType | LeRoot : LeType child class or hierarchy root
  198. # @param lesub LeType : LeType child class
  199. # @param nature str : The nature of the relation @ref EditorialModel.classtypes
  200. # @return True if deletion done successfully
  201. # @throw ValueError when bad arguments given
  202. @classmethod
  203. def ___hierarchy_del(cls, lesup, lesub, nature):
  204. if nature not in EditorialModel.classtypes.EmClassType.natures(lesub._classtype):
  205. raise ValueError("Invalid nature '%s' for %s"%(nature, lesup.__class__.__name__))
  206. if not cls.leo_is_root(lesup):
  207. if nature not in EditorialModel.classtypes.EmClassType.natures(lesup._classtype):
  208. raise ValueError("Invalid nature '%s' for %s"%(nature, lesup.__class__.__name__))
  209. if lesup.__class__ not in lesub._superiors[nature]:
  210. raise ValueError("%s is not a valid superior for %s"%(lesup.__class__, lesub.__class__))
  211. superiors = cls.hierarchy_get(lesub, nature, leo_is_sup = False)
  212. res = True
  213. for _lesup in superiors:
  214. if not cls._datasource.del_superior(_lesup, lesub, nature):
  215. #How to handler this ?
  216. res = False
  217. return res
  218. ## @brief Fetch neighbour in hierarchy relation
  219. # @param leo LeType | LeRoot : We want the neighbour of this LeObject (can be the root)
  220. # @param nature str : @ref EditorialModel.classtypes
  221. # @param leo_is_sup bool : if True leo is the superior and we want to fetch the subordinates else its the oposite
  222. # @return A list of LeObject ordered by depth if leo_is_sup, else a list of subordinates
  223. @classmethod
  224. def ___hierarchy_get(cls, leo, nature, leo_is_sup = True):
  225. #Checking arguments
  226. if not (nature is None) and not cls.is_root(leo):
  227. if nature not in EditorialModel.classtypes.EmClassType.natures(leo._classtype):
  228. raise ValueError("Invalid nature '%s' for %s"%(nature, lesup.__class__.__name__))
  229. if leo_is_sup:
  230. return cls._datasource.get_subordinates(leo, nature)
  231. else:
  232. return cls._datasource.get_superiors(leo, nature)
  233. ## @brief Preparing letype and leclass arguments
  234. #
  235. # This function will do multiple things :
  236. # - Convert string to LeType or LeClass child instances
  237. # - If both letype and leclass given, check that letype inherit from leclass
  238. #  - If only a letype is given, fetch the parent leclass
  239. # @note If we give only a leclass as argument returned letype will be None
  240. # @note Its possible to give letype=None and leclass=None. In this case the method will return tuple(None,None)
  241. # @param letype LeType|str|None : LeType child instant or its name
  242. # @param leclass LeClass|str|None : LeClass child instant or its name
  243. # @return a tuple with 2 python classes (LeTypeChild, LeClassChild)
  244. @classmethod
  245. def ___prepare_targets(cls, letype = None , leclass = None):
  246. warnings.warn("_LeObject._prepare_targets is deprecated", DeprecationWarning)
  247. raise ValueError()
  248. if not(leclass is None):
  249. if isinstance(leclass, str):
  250. leclass = LeFactory.leobj_from_name(leclass)
  251. if not isinstance(leclass, type) or not (leapi.leclass.LeClass in leclass.__bases__) or leclass.__class__ == leapi.leclass.LeClass:
  252. raise ValueError("None | str | LeType child class excpected, but got : '%s' %s"%(leclass,type(leclass)))
  253. if not(letype is None):
  254. if isinstance(letype, str):
  255. letype = LeFactory.leobj_from_name(letype)
  256. if not isinstance(letype, type) or not leapi.letype.LeType in letype.__bases__ or letype.__class__ == leapi.letype.LeType:
  257. raise ValueError("None | str | LeType child class excpected, but got : %s"%type(letype))
  258. if leclass is None:
  259. leclass = letype._leclass
  260. elif leclass != letype._leclass:
  261. raise ValueError("LeType child class %s does'nt inherite from LeClass %s"%(letype.__name__, leclass.__name__))
  262. return (letype, leclass)
  263. ## @brief Class designed to represent the hierarchy roots
  264. # @see _LeObject.get_root() _LeObject.is_root()
  265. class LeRoot(object):
  266. pass
  267. class LeObjectError(Exception):
  268. pass
  269. class LeObjectQueryError(LeObjectError):
  270. pass
  271. ## @page leobject_filters LeObject query filters
  272. # The LeObject API provide methods that accept filters allowing the user
  273. # to query the database and fetch LodelEditorialObjects.
  274. #
  275. # The LeObject API translate those filters for the datasource.
  276. #
  277. # @section api_user_side API user side filters
  278. # Filters are string expressing a condition. The string composition
  279. # is as follow : "<FIELD> <OPERATOR> <VALUE>"
  280. # @subsection fpart FIELD
  281. # @subsubsection standart fields
  282. # Standart fields, represents a value of the LeObject for example "title", "lodel_id" etc.
  283. # @subsubsection rfields relationnal fields
  284. # relationnal fields, represents a relation with the object hierarchy. Those fields are composed as follow :
  285. # "<RELATION>.<NATURE>".
  286. #
  287. # - Relation can takes two values : superiors or subordinates
  288. # - Nature is a relation nature ( see EditorialModel.classtypes )
  289. # Examples : "superiors.parent", "subordinates.translation" etc.
  290. # @note The field_list arguement of leapi.leapi._LeObject.get() use the same syntax than the FIELD filter part
  291. # @subsection oppart OPERATOR
  292. # The OPERATOR part of a filter is a comparison operator. There is
  293. # - standart comparison operators : = , <, > , <=, >=, !=
  294. # - list operators : 'in' and 'not in'
  295. # The list of allowed operators is sotred at leapi.leapi._LeObject._query_operators .
  296. # @subsection valpart VALUE
  297. # The VALUE part of a filter is... just a value...
  298. #
  299. # @section datasource_side Datasource side filters
  300. # As said above the API "translate" filters before forwarding them to the datasource.
  301. #
  302. # The translation process transform filters in tuple composed of 3 elements
  303. # ( @ref fpart , @ref oppart , @ref valpart ). Each element is a string.
  304. #
  305. # There is a special case for @ref rfields : the field element is a tuple composed with two elements
  306. # ( RELATION, NATURE ) where NATURE is a string ( see EditorialModel.classtypes ) and RELATION is one of
  307. # the defined constant :
  308. #
  309. # - leapi.leapi.REL_SUB for "subordinates"
  310. # - leapi.leapi.REL_SUP for "superiors"
  311. #
  312. # @note The filters translation process also check if given field are valids compared to the concerned letype and/or the leclass