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

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