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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. #-*- coding: utf-8 -*-
  2. ## @package leobject API to access lodel datas
  3. #
  4. # This package contains abstract classes leobject.leclass.LeClass , leobject.letype.LeType, leobject.leobject._LeObject.
  5. # Those abstract classes are designed to be mother classes of dynamically generated classes ( see leobject.lefactory.LeFactory )
  6. ## @package leobject.leobject
  7. # @brief Abstract class designed to be implemented by LeObject
  8. #
  9. # @note LeObject will be generated by leobject.lefactory.LeFactory
  10. import re
  11. import leobject
  12. import EditorialModel
  13. from EditorialModel.types import EmType
  14. REL_SUP = 0
  15. REL_SUB = 1
  16. ## @brief Main class to handle objects defined by the types of an Editorial Model
  17. class _LeObject(object):
  18. ## @brief The editorial model
  19. _model = None
  20. ## @brief The datasource
  21. _datasource = None
  22. ## @brief maps em uid with LeType or LeClass keys are uid values are LeObject childs classes
  23. _me_uid = dict()
  24. _query_re = None
  25. _query_operators = ['=', '<=', '>=', '!=', '<', '>', ' in ', ' not in ']
  26. ## @brief Instantiate with a Model and a DataSource
  27. # @param **kwargs dict : datas usefull to instanciate a _LeObject
  28. def __init__(self, **kwargs):
  29. raise NotImplementedError("Abstract constructor")
  30. ## @brief Given a ME uid return the corresponding LeClass or LeType class
  31. # @return a LeType or LeClass child class
  32. # @throw KeyError if no corresponding child classes
  33. @classmethod
  34. def uid2leobj(cls, uid):
  35. uid = int(uid)
  36. if uid not in cls._me_uid:
  37. raise KeyError("No LeType or LeClass child classes with uid '%d'"%uid)
  38. return cls._me_uid[uid]
  39. ## @brief Creates new entries in the datasource
  40. # @param datas list : A list a dict with fieldname as key
  41. # @param cls
  42. # @return a list of inserted lodel_id
  43. # @see leobject.datasources.dummy.DummyDatasource.insert(), leobject.letype.LeType.insert()
  44. @classmethod
  45. def insert(cls, letype, datas):
  46. if isinstance(datas, dict):
  47. datas = [datas]
  48. if cls == _LeObject:
  49. raise NotImplementedError("Abstract method")
  50. letype,leclass = cls._prepare_targets(letype)
  51. if letype is None:
  52. raise ValueError("letype argument cannot be None")
  53. for data in datas:
  54. letype.check_datas_or_raise(data, complete = True)
  55. return cls._datasource.insert(letype, leclass, datas)
  56. ## @brief Check if a LeType is a hierarchy root
  57. @staticmethod
  58. def is_root(leo):
  59. if isinstance(leo, leobject.letype.LeType):
  60. return False
  61. elif isinstance(leo, LeRoot):
  62. return True
  63. raise ValueError("Invalid value for a LeType : %s"%leo)
  64. ## @brief Return a LeRoot instance
  65. @staticmethod
  66. def get_root():
  67. return LeRoot()
  68. ## @brief Delete LeObjects given filters
  69. # @param cls
  70. # @param letype LeType|str : LeType child class or name
  71. # @param leclass LeClass|str : LeClass child class or name
  72. # @param filters list : list of filters (see @ref leobject_filters)
  73. # @return bool
  74. @classmethod
  75. def delete(cls, letype, filters):
  76. letype, leclass = cls._prepare_targets(letype)
  77. filters,relationnal_filters = leobject.leobject._LeObject._prepare_filters(filters, letype, leclass)
  78. return cls._datasource.delete(letype, leclass, filters, relationnal_filters)
  79. ## @brief Update LeObjects given filters and datas
  80. # @param cls
  81. # @param letype LeType|str : LeType child class or name
  82. # @param filters list : list of filters (see @ref leobject_filters)
  83. @classmethod
  84. def update(cls, letype, filters, datas):
  85. letype, leclass = cls._prepare_targets(letype)
  86. filters,relationnal_filters = leobject.leobject._LeObject._prepare_filters(filters, letype, leclass)
  87. if letype is None:
  88. raise ValueError("Argument letype cannot be None")
  89. letype.check_datas_or_raise(datas, False)
  90. return cls._datasource.update(letype, leclass, filters, relationnal_filters, datas)
  91. ## @brief make a search to retrieve a collection of LeObject
  92. # @param query_filters list : list of string of query filters (or tuple (FIELD, OPERATOR, VALUE) ) see @ref leobject_filters
  93. # @param field_list list|None : list of string representing fields see @ref leobject_filters
  94. # @param typename str : The name of the LeType we want
  95. # @param classname str : The name of the LeClass we want
  96. # @param cls
  97. # @return responses ({string:*}): a list of dict with field:value
  98. @classmethod
  99. def get(cls, query_filters, field_list = None, typename = None, classname = None):
  100. letype,leclass = cls._prepare_targets(typename, classname)
  101. #Checking field_list
  102. if field_list is None or len(field_list) == 0:
  103. #default field_list
  104. if not (letype is None):
  105. field_list = letype._fields
  106. elif not (leclass is None):
  107. field_list = leclass._fieldtypes.keys()
  108. else:
  109. field_list = list(EditorialModel.classtypes.common_fields.keys())
  110. #Fetching LeType
  111. if letype is None:
  112. if 'type_id' not in field_list:
  113. field_list.append('type_id')
  114. field_list = cls._prepare_field_list(field_list, letype, leclass)
  115. #preparing filters
  116. filters, relationnal_filters = cls._prepare_filters(query_filters, letype, leclass)
  117. #Fetching datas from datasource
  118. datas = cls._datasource.get(leclass, letype, field_list, filters, relationnal_filters)
  119. #Instanciating corresponding LeType child classes with datas
  120. result = list()
  121. for leobj_datas in datas:
  122. letype = self.uid2leobj(datas['type_id']) if letype is None else letype
  123. result.append(letype(datas))
  124. return result
  125. ## @brief Link two leobject together using a rel2type field
  126. # @param lesup LeType : LeType child class instance linked as superior
  127. # @param lesub LeType : LeType child class instance linked as subordinate
  128. # @param **rel_attr : Relation attributes
  129. # @return True if linked without problems
  130. # @throw LeObjectError if the link is not valid
  131. # @throw LeObkectError if the link already exists
  132. # @throw AttributeError if an non existing relation attribute is given as argument
  133. # @throw ValueError if the relation attrivute value check fails
  134. #
  135. # @todo Code factorisation on relation check
  136. # @todo unit tests
  137. @classmethod
  138. def link_together(cls, lesup, lesub, **rel_attr):
  139. if lesub.__class__ not in lesup._linked_types.keys():
  140. raise LeObjectError("Relation error : %s cannot be linked with %s"%(lesup.__class__.__name__, lesub.__class__.__name__))
  141. for attr_name in rel_attr.keys():
  142. if attr_name not in [ f for f,g in lesup._linked_types[lesub.__class__] ]:
  143. raise AttributeError("A rel2type between a %s and a %s doesn't have an attribute %s"%(lesup.__class__.__name__, lesub.__class__.__name__))
  144. if not sup._linked_types[lesub.__class__][1].check(rel_attr[attr_name]):
  145. raise ValueError("Wrong value '%s' for attribute %s"%(rel_attr[attr_name], attr_name))
  146. #Checks that attributes are uniq for this relation
  147. rels_attr = [ attrs for lesup, lesub, attrs in cls.links_get(lesup) if lesup == lesup ]
  148. for e_attrs in rels_attrs:
  149. if rel_attr == e_attrs:
  150. raise LeObjectError("Relation error : a relation with the same attributes already exists")
  151. return cls._datasource.add_related(lesup, lesub, **rel_attr)
  152. ## @brief Get related objects
  153. # @param leo LeType(instance) : LeType child class instance
  154. # @param letype LeType(class) : the wanted LeType child class (not instance)
  155. # @param leo_is_superior bool : if True leo is the superior in the relation
  156. # @return A dict with LeType child class instance as key and dict {rel_attr_name:rel_attr_value, ...}
  157. # @throw LeObjectError if the relation is not possible
  158. #
  159. # @todo Code factorisation on relation check
  160. # @todo unit tests
  161. @classmethod
  162. def linked_together(cls, leo, letype, leo_is_superior = True):
  163. valid_link = letype in leo._linked_types.keys() if leo_is_superior else leo.__class__ in letype._linked_types.keys()
  164. if not valid_link:
  165. raise LeObjectError("Relation error : %s have no links with %s"%(
  166. leo.__class__ if leo_is_superior else letype,
  167. letype if leo_is_superior else leo.__class__
  168. ))
  169. return cls._datasource.get_related(leo, letype, leo_is_superior)
  170. ## @brief Fetch a relation and its attributes
  171. # @param id_relation int : the relation identifier
  172. # @return a tuple(lesup, lesub, dict_attr) or False if no relation exists with this id
  173. # @throw Exception if the relation is not a rel2type relation
  174. @classmethod
  175. def link_get(cls, id_relation):
  176. return cls._datasource.get_relation(id_relation)
  177. ## @brief Fetch all relations for an objects
  178. # @param leo LeType : LeType child class instance
  179. # @return a list of tuple (lesup, lesub, dict_attr)
  180. def links_get(cls, leo):
  181. return cls._datasource.get_relations(leo)
  182. ## @brief Remove a link (and attributes) between two LeObject
  183. # @param id_relation int : Relation identifier
  184. # @return True if a link has been deleted
  185. # @throw LeObjectError if the relation is not a rel2type
  186. #
  187. # @todo Code factorisation on relation check
  188. # @todo unit tests
  189. @classmethod
  190. def link_remove(cls, id_relation):
  191. if lesub.__class__ not in lesup._linked_types.keys():
  192. raise LeObjectError("Relation errorr : %s cannot be linked with %s"%(lesup.__class__.__name__, lesub.__class__.__name__))
  193. return cls._datasource.del_related(lesup, lesub)
  194. ## @brief Add a hierarchy relation between two LeObject
  195. # @param lesup LeType|LeRoot : LeType child class instance
  196. # @param lesub LeType : LeType child class instance
  197. # @param nature str : The nature of the relation @ref EditorialModel.classtypes
  198. # @param rank str|int : The relation rank. Can be 'last', 'first' or an integer
  199. # @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
  200. # @return The relation ID or False if fails
  201. # @throw LeObjectQueryError replace_if_exists == False and there is a superior
  202. @classmethod
  203. def hierarchy_add(cls, lesup, lesub, nature, rank = 'last', replace_if_exists = False):
  204. #Arguments check
  205. if nature not in EditorialModel.classtypes.EmClassType.natures(lesub._classtype):
  206. raise ValueError("Invalid nature '%s' for %s"%(nature, lesup.__class__.__name__))
  207. if not cls.leo_is_root(lesup):
  208. if nature not in EditorialModel.classtypes.EmClassType.natures(lesup._classtype):
  209. raise ValueError("Invalid nature '%s' for %s"%(nature, lesup.__class__.__name__))
  210. if lesup.__class__ not in lesub._superiors[nature]:
  211. raise ValueError("%s is not a valid superior for %s"%(lesup.__class__, lesub.__class__))
  212. #else:
  213. # lesup is not a LeType but a hierarchy root
  214. if rank not in ['first', 'last'] and not isinstance(rank, int):
  215. raise ValueError("Allowed values for rank are integers and 'first' or 'last' but '%s' found"%rank)
  216. superiors = cls.hierarchy_get(lesub, nature, leo_is_sup = False)
  217. if lesup in len(superiors) > 0:
  218. if not replace_if_exists:
  219. raise LeObjectQueryError("The subordinate allready has a superior")
  220. #remove existig superior
  221. if not cls.hierarchy_del(superiors[0], lesub, nature):
  222. raise RuntimeError("Unable to delete the previous superior")
  223. return self._datasource.add_superior(lesup, lesub, nature, rank)
  224. ## @brief Prepare a field_list
  225. # @param field_list list : List of string representing fields
  226. # @param letype LeType : LeType child class
  227. # @param leclass LeClass : LeClass child class
  228. # @return A well formated field list
  229. @classmethod
  230. def _prepare_field_list(cls, field_list, letype, leclass):
  231. cls._check_fields(letype, leclass, [f for f in field_list if not cls._field_is_relational(f)])
  232. for i, field in enumerate(field_list):
  233. if cls._field_is_relational(field):
  234. field_list[i] = cls._prepare_relational_field(field)
  235. return field_list
  236. ## @brief Preparing letype and leclass arguments
  237. #
  238. # This function will do multiple things :
  239. # - Convert string to LeType or LeClass child instances
  240. # - If both letype and leclass given, check that letype inherit from leclass
  241. #  - If only a letype is given, fetch the parent leclass
  242. # @note If we give only a leclass as argument returned letype will be None
  243. # @note Its possible to give letype=None and leclass=None. In this case the method will return tuple(None,None)
  244. # @param letype LeType|str|None : LeType child instant or its name
  245. # @param leclass LeClass|str|None : LeClass child instant or its name
  246. # @return a tuple with 2 python classes (LeTypeChild, LeClassChild)
  247. @staticmethod
  248. def _prepare_targets(letype = None , leclass = None):
  249. if not(leclass is None):
  250. if isinstance(leclass, str):
  251. leclass = leobject.lefactory.LeFactory.leobj_from_name(leclass)
  252. if not isinstance(leclass, type) or not (leobject.leclass.LeClass in leclass.__bases__) or leclass.__class__ == leobject.leclass.LeClass:
  253. raise ValueError("None | str | LeType child class excpected, but got : '%s' %s"%(leclass,type(leclass)))
  254. if not(letype is None):
  255. if isinstance(letype, str):
  256. letype = leobject.lefactory.LeFactory.leobj_from_name(letype)
  257. if not isinstance(letype, type) or not leobject.letype.LeType in letype.__bases__ or letype.__class__ == leobject.letype.LeType:
  258. raise ValueError("None | str | LeType child class excpected, but got : %s"%type(letype))
  259. if leclass is None:
  260. leclass = letype._leclass
  261. elif leclass != letype._leclass:
  262. raise ValueError("LeType child class %s does'nt inherite from LeClass %s"%(letype.__name__, leclass.__name__))
  263. return (letype, leclass)
  264. ## @brief Check if a fieldname is valid
  265. # @param letype LeType|None : The concerned type (or None)
  266. # @param leclass LeClass|None : The concerned class (or None)
  267. # @param fields list : List of string representing fields
  268. # @throw LeObjectQueryError if their is some problems
  269. # @throw AttributeError if letype is not from the leclass class
  270. # @todo Delete the checks of letype and leclass and ensure that this method is called with letype and leclass arguments from _prepare_targets()
  271. #
  272. # @see @ref leobject_filters
  273. @staticmethod
  274. def _check_fields(letype, leclass, fields):
  275. #Checking that fields in the query_filters are correct
  276. if letype is None and leclass is None:
  277. #Only fields from the object table are allowed
  278. for field in fields:
  279. if field not in EditorialModel.classtypes.common_fields.keys():
  280. raise LeObjectQueryError("Not typename and no classname given, but the field %s is not in the common_fields list"%field)
  281. else:
  282. if letype is None:
  283. field_l = leclass._fieldtypes.keys()
  284. else:
  285. if not (leclass is None):
  286. if letype._leclass != leclass:
  287. raise AttributeError("The EmType %s is not a specialisation of the EmClass %s"%(typename, classname))
  288. field_l = letype._fields
  289. #Checks that fields are in this type
  290. for field in fields:
  291. if field not in field_l:
  292. raise LeObjectQueryError("No field named '%s' in '%s'"%(field, letype.__name__))
  293. pass
  294. ## @brief Prepare filters for datasource
  295. #
  296. # This method divide filters in two categories :
  297. # - filters : standart FIELDNAME OP VALUE filter
  298. # - relationnal_filters : filter on object relation RELATION_NATURE OP VALUE
  299. #
  300. # Both categories of filters are represented in the same way, a tuple with 3 elements (NAME|NAT , OP, VALUE )
  301. #
  302. # @warning This method assume that letype and leclass are returned from _LeObject._prepare_targets() method
  303. # @param filters_l list : This list can contain str "FIELDNAME OP VALUE" and tuples (FIELDNAME, OP, VALUE)
  304. # @param letype LeType|None : needed to check filters
  305. # @param leclass LeClass|None : needed to check filters
  306. # @return a tuple(FILTERS, RELATIONNAL_FILTERS
  307. #
  308. # @see @ref datasource_side
  309. @staticmethod
  310. def _prepare_filters(filters_l, letype = None, leclass = None):
  311. filters = list()
  312. for fil in filters_l:
  313. if len(fil) == 3 and not isinstance(fil, str):
  314. filters.append(tuple(fil))
  315. else:
  316. filters.append(_LeObject._split_filter(fil))
  317. #Checking relational filters (for the moment fields like superior.NATURE)
  318. relational_filters = [ (_LeObject._prepare_relational_field(field), operator, value) for field, operator, value in filters if _LeObject._field_is_relational(field)]
  319. filters = [f for f in filters if not _LeObject._field_is_relational(f[0])]
  320. #Checking the rest of the fields
  321. _LeObject._check_fields(letype, leclass, [ f[0] for f in filters ])
  322. return (filters, relational_filters)
  323. ## @brief Check if a field is relational or not
  324. # @param field str : the field to test
  325. # @return True if the field is relational else False
  326. @staticmethod
  327. def _field_is_relational(field):
  328. return field.startswith('superior.') or field.startswith('subordinate')
  329. ## @brief Check that a relational field is valid
  330. # @param field str : a relational field
  331. # @return a nature
  332. @staticmethod
  333. def _prepare_relational_field(field):
  334. spl = field.split('.')
  335. if len(spl) != 2:
  336. raise LeObjectQueryError("The relationalfield '%s' is not valid"%field)
  337. nature = spl[-1]
  338. if nature not in EditorialModel.classtypes.EmNature.getall():
  339. raise LeObjectQueryError("'%s' is not a valid nature in the field %s"%(nature, field))
  340. if spl[0] == 'superior':
  341. return (REL_SUP, nature)
  342. elif spl[0] == 'subordinate':
  343. return (REL_SUB, nature)
  344. else:
  345. raise LeObjectQueryError("Invalid preffix for relationnal field : '%s'"%spl[0])
  346. ## @brief Check and split a query filter
  347. # @note The query_filter format is "FIELD OPERATOR VALUE"
  348. # @param query_filter str : A query_filter string
  349. # @param cls
  350. # @return a tuple (FIELD, OPERATOR, VALUE)
  351. @classmethod
  352. def _split_filter(cls, query_filter):
  353. if cls._query_re is None:
  354. cls._compile_query_re()
  355. matches = cls._query_re.match(query_filter)
  356. if not matches:
  357. raise ValueError("The query_filter '%s' seems to be invalid"%query_filter)
  358. result = (matches.group('field'), re.sub(r'\s', ' ', matches.group('operator'), count=0), matches.group('value').strip())
  359. for r in result:
  360. if len(r) == 0:
  361. raise ValueError("The query_filter '%s' seems to be invalid"%query_filter)
  362. return result
  363. ## @brief Compile the regex for query_filter processing
  364. # @note Set _LeObject._query_re
  365. @classmethod
  366. def _compile_query_re(cls):
  367. op_re_piece = '(?P<operator>(%s)'%cls._query_operators[0].replace(' ', '\s')
  368. for operator in cls._query_operators[1:]:
  369. op_re_piece += '|(%s)'%operator.replace(' ', '\s')
  370. op_re_piece += ')'
  371. cls._query_re = re.compile('^\s*(?P<field>(((superior)|(subordinate))\.)?[a-z_][a-z0-9\-_]*)\s*'+op_re_piece+'\s*(?P<value>[^<>=!].*)\s*$', flags=re.IGNORECASE)
  372. pass
  373. ## @brief Class designed to represent the hierarchy roots
  374. # @see _LeObject.get_root() _LeObject.is_root()
  375. class LeRoot(object):
  376. pass
  377. class LeObjectError(Exception):
  378. pass
  379. class LeObjectQueryError(LeObjectError):
  380. pass
  381. ## @page leobject_filters LeObject query filters
  382. # The LeObject API provide methods that accept filters allowing the user
  383. # to query the database and fetch LodelEditorialObjects.
  384. #
  385. # The LeObject API translate those filters for the datasource.
  386. #
  387. # @section api_user_side API user side filters
  388. # Filters are string expressing a condition. The string composition
  389. # is as follow : "<FIELD> <OPERATOR> <VALUE>"
  390. # @subsection fpart FIELD
  391. # @subsubsection standart fields
  392. # Standart fields, represents a value of the LeObject for example "title", "lodel_id" etc.
  393. # @subsubsection rfields relationnal fields
  394. # relationnal fields, represents a relation with the object hierarchy. Those fields are composed as follow :
  395. # "<RELATION>.<NATURE>".
  396. #
  397. # - Relation can takes two values : superiors or subordinates
  398. # - Nature is a relation nature ( see EditorialModel.classtypes )
  399. # Examples : "superiors.parent", "subordinates.translation" etc.
  400. # @note The field_list arguement of leobject.leobject._LeObject.get() use the same syntax than the FIELD filter part
  401. # @subsection oppart OPERATOR
  402. # The OPERATOR part of a filter is a comparison operator. There is
  403. # - standart comparison operators : = , <, > , <=, >=, !=
  404. # - list operators : 'in' and 'not in'
  405. # The list of allowed operators is sotred at leobject.leobject._LeObject._query_operators .
  406. # @subsection valpart VALUE
  407. # The VALUE part of a filter is... just a value...
  408. #
  409. # @section datasource_side Datasource side filters
  410. # As said above the API "translate" filters before forwarding them to the datasource.
  411. #
  412. # The translation process transform filters in tuple composed of 3 elements
  413. # ( @ref fpart , @ref oppart , @ref valpart ). Each element is a string.
  414. #
  415. # There is a special case for @ref rfields : the field element is a tuple composed with two elements
  416. # ( RELATION, NATURE ) where NATURE is a string ( see EditorialModel.classtypes ) and RELATION is one of
  417. # the defined constant :
  418. #
  419. # - leobject.leobject.REL_SUB for "subordinates"
  420. # - leobject.leobject.REL_SUP for "superiors"
  421. #
  422. # @note The filters translation process also check if given field are valids compared to the concerned letype and/or the leclass