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.

lecrud.py 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. #-*- coding: utf-8 -*-
  2. ## @package leapi.lecrud
  3. # @brief This package contains the abstract class representing Lodel Editorial components
  4. #
  5. import warnings
  6. import importlib
  7. import re
  8. REL_SUP = 0
  9. REL_SUB = 1
  10. class LeApiErrors(Exception):
  11. ## @brief Instanciate a new exceptions handling multiple exceptions
  12. # @param exptexptions dict : A list of data check Exception with concerned field (or stuff) as key
  13. def __init__(self, msg = "Unknow error", exceptions = None):
  14. self._msg = msg
  15. self._exceptions = dict() if exceptions is None else exceptions
  16. def __repr__(self):
  17. return self.__str__()
  18. def __str__(self):
  19. msg = self._msg
  20. for obj, expt in self._exceptions.items():
  21. msg += "\n\t{expt_obj} : ({expt_name}) {expt_msg}; ".format(
  22. expt_obj = obj,
  23. expt_name=expt.__class__.__name__,
  24. expt_msg=str(expt)
  25. )
  26. return msg
  27. ## @brief When an error concern a query
  28. class LeApiQueryError(LeApiErrors): pass
  29. ## @brief When an error concerns a datas
  30. class LeApiDataCheckError(LeApiErrors): pass
  31. ## @brief Main class to handler lodel editorial components (relations and objects)
  32. class _LeCrud(object):
  33. ## @brief The datasource
  34. _datasource = None
  35. ## @brief abstract property to store the fieldtype representing the component identifier
  36. _uid_fieldtype = None #Will be a dict fieldname => fieldtype
  37. ## @brief will store all the fieldtypes (child classes handle it)
  38. _fieldtypes_all = None
  39. ## @brief Stores a regular expression to parse query filters strings
  40. _query_re = None
  41. ## @brief Stores Query filters operators
  42. _query_operators = ['=', '<=', '>=', '!=', '<', '>', ' in ', ' not in ', ' like ', ' not like ']
  43. def __init__(self):
  44. raise NotImplementedError("Abstract class")
  45. ## @brief Given a dynamically generated class name return the corresponding python Class
  46. # @param name str : a concrete class name
  47. # @return False if no such component
  48. @classmethod
  49. def name2class(cls, name):
  50. if not isinstance(name, str):
  51. raise ValueError("Expected name argument as a string but got %s instead"%(type(name)))
  52. mod = importlib.import_module(cls.__module__)
  53. try:
  54. return getattr(mod, name)
  55. except AttributeError:
  56. return False
  57. ## @return LeObject class
  58. @classmethod
  59. def leobject(cls):
  60. return cls.name2class('LeObject')
  61. ## @return A dict with key field name and value a fieldtype instance
  62. @classmethod
  63. def fieldtypes(cls):
  64. raise NotImplementedError("Abstract method") #child classes should return their uid fieldtype
  65. ## @return A dict with fieldtypes marked as internal
  66. # @todo check if this method is in use, else delete it
  67. @classmethod
  68. def fieldtypes_internal(self):
  69. return { fname: ft for fname, ft in cls.fieldtypes().items() if hasattr(ft, 'internal') and ft.internal }
  70. ## @return A list of field name
  71. @classmethod
  72. def fieldlist(cls):
  73. return list(cls.fieldtypes().keys())
  74. ## @return The name of the uniq id field
  75. # @todo test for abstract method !!!
  76. @classmethod
  77. def uidname(cls):
  78. if cls._uid_fieldtype is None or len(cls._uid_fieldtype) == 0:
  79. raise NotImplementedError("Abstract method uid_name for %s!"%cls.__name__)
  80. return list(cls._uid_fieldtype.keys())[0]
  81. ## @return maybe Bool: True if cls implements LeType
  82. # @param cls Class: a Class or instanciated object
  83. @classmethod
  84. def implements_letype(cls):
  85. return hasattr(cls, '_leclass')
  86. ## @return maybe Bool: True if cls implements LeClass
  87. # @param cls Class: a Class or instanciated object
  88. @classmethod
  89. def implements_leclass(cls):
  90. return hasattr(cls, '_class_id')
  91. ## @return maybe Bool: True if cls implements LeObject
  92. # @param cls Class: a Class or instanciated object
  93. @classmethod
  94. def implements_leobject(cls):
  95. return hasattr(cls, '_me_uid')
  96. ## @return maybe Bool: True if cls is a LeType or an instance of LeType
  97. # @param cls Class: a Class or instanciated object
  98. @classmethod
  99. def is_letype(cls):
  100. return cls.implements_letype()
  101. ## @return maybe Bool: True if cls is a LeClass or an instance of LeClass
  102. # @param cls Class: a Class or instanciated object
  103. @classmethod
  104. def is_leclass(cls):
  105. return cls.implements_leclass() and not cls.implements_letype()
  106. ## @return maybe Bool: True if cls is a LeClass or an instance of LeClass
  107. # @param cls Class: a Class or instanciated object
  108. @classmethod
  109. def is_leobject(cls):
  110. return cls.implements_leobject() and not cls.implements_leclass()
  111. ## @return maybe Bool: True if cls implements LeRelation
  112. # @param cls Class: a Class or instanciated object
  113. @classmethod
  114. def implements_lerelation(cls):
  115. return hasattr(cls, '_lesup_fieldtype')
  116. ## @return maybe Bool: True if cls implements LeRel2Type
  117. # @param cls Class: a Class or instanciated object
  118. @classmethod
  119. def implements_lerel2type(cls):
  120. return hasattr(cls, '_rel_attr_fieldtypes')
  121. ## @return maybe Bool: True if cls is a LeHierarch or an instance of LeHierarch
  122. # @param cls Class: a Class or instanciated object
  123. @classmethod
  124. def is_lehierarch(cls):
  125. return cls.implements_lerelation() and not cls.implements_lerel2type()
  126. ## @return maybe Bool: True if cls is a LeRel2Type or an instance of LeRel2Type
  127. # @param cls Class: a Class or instanciated object
  128. @classmethod
  129. def is_lerel2type(cls):
  130. return cls.implements_lerel2type()
  131. ## @brief Returns object datas
  132. # @param
  133. # @return a dict of fieldname : value
  134. def datas(self, internal = False):
  135. res = dict()
  136. for fname, ftt in self.fieldtypes().items():
  137. if (internal or (not internal and ftt.is_internal)) and hasattr(self, fname):
  138. res[fname] = getattr(self, fname)
  139. ## @brief Update a component in DB
  140. # @param datas dict : If None use instance attributes to update de DB
  141. # @return True if success
  142. # @todo better error handling
  143. def update(self, datas = None):
  144. datas = self.datas(internal=False) if datas is None else datas
  145. upd_datas = self.prepare_datas(datas, complete = False, allow_internal = False)
  146. filters = [self._id_filter()]
  147. rel_filters = []
  148. ret = self._datasource.update(self.__class__, filters, rel_filters, **upd_datas)
  149. if ret == 1:
  150. return True
  151. else:
  152. #ERROR HANDLING
  153. return False
  154. ## @brief Delete a component (instance method)
  155. # @return True if success
  156. # @todo better error handling
  157. def _delete(self):
  158. filters = [self._id_filter()]
  159. ret = _LeCrud.delete(self.__class__, filters)
  160. if ret == 1:
  161. return True
  162. else:
  163. #ERROR HANDLING
  164. return False
  165. ## @brief Check that datas are valid for this type
  166. # @param datas dict : key == field name value are field values
  167. # @param complete bool : if True expect that datas provide values for all non internal fields
  168. # @param allow_internal bool : if True don't raise an error if a field is internal
  169. # @return Checked datas
  170. # @throw LeApiDataCheckError if errors reported during check
  171. @classmethod
  172. def check_datas_value(cls, datas, complete = False, allow_internal = True):
  173. err_l = dict() #Stores errors
  174. correct = [] #Valid fields name
  175. mandatory = [] #mandatory fields name
  176. for fname, ftt in cls.fieldtypes().items():
  177. if allow_internal or not ftt.is_internal():
  178. correct.append(fname)
  179. if complete and not hasattr(ftt, 'default'):
  180. mandatory.append(fname)
  181. mandatory = set(mandatory)
  182. correct = set(correct)
  183. provided = set(datas.keys())
  184. #searching unknow fields
  185. unknown = provided - correct
  186. for u_f in unknown:
  187. #here we can check if the field is unknown or rejected because it is internal
  188. err_l[u_f] = AttributeError("Unknown or unauthorized field '%s'"%u_f)
  189. #searching missings fields
  190. missings = mandatory - provided
  191. for miss_field in missings:
  192. err_l[miss_field] = AttributeError("The data for field '%s' is missing"%miss_field)
  193. #Checks datas
  194. checked_datas = dict()
  195. for name, value in [ (name, value) for name, value in datas.items() if name in correct ]:
  196. ft = cls.fieldtypes()
  197. ft = ft[name]
  198. r = ft.check_data_value(value)
  199. checked_datas[name], err = r
  200. #checked_datas[name], err = cls.fieldtypes()[name].check_data_value(value)
  201. if err:
  202. err_l[name] = err
  203. if len(err_l) > 0:
  204. raise LeApiDataCheckError("Error while checking datas", err_l)
  205. return checked_datas
  206. ## @brief Given filters delete editorial components
  207. # @param filters list :
  208. # @return The number of deleted components
  209. @staticmethod
  210. def delete(cls, filters):
  211. filters, rel_filters = cls._prepare_filters(filters)
  212. return cls._datasource.delete(cls, filters, rel_filters)
  213. ## @brief Retrieve a collection of lodel editorial components
  214. #
  215. # @param query_filters list : list of string of query filters (or tuple (FIELD, OPERATOR, VALUE) ) see @ref leobject_filters
  216. # @param field_list list|None : list of string representing fields see @ref leobject_filters
  217. # @param order list : A list of field names or tuple (FIELDNAME, [ASC | DESC])
  218. # @param groups list : A list of field names or tuple (FIELDNAME, [ASC | DESC])
  219. # @param limit int : The maximum number of returned results
  220. # @param offset int : offset
  221. # @return A list of lodel editorial components instance
  222. # @todo think about LeObject and LeClass instanciation (partial instanciation, etc)
  223. @classmethod
  224. def get(cls, query_filters, field_list=None, order=None, group=None, limit=None, offset=0):
  225. if field_list is None or len(field_list) == 0:
  226. #default field_list
  227. field_list = cls.fieldlist()
  228. field_list = cls._prepare_field_list(field_list) #Can raise LeApiDataCheckError
  229. #preparing filters
  230. filters, relational_filters = cls._prepare_filters(query_filters)
  231. #preparing order
  232. if order:
  233. order = cls._prepare_order_fields(order)
  234. if isinstance(order, Exception):
  235. raise order #can be buffered and raised later, but _prepare_filters raise when fails
  236. #preparing groups
  237. if group:
  238. group = cls._prepare_order_fields(group)
  239. if isinstance(group, Exception):
  240. raise group # can also be buffered and raised later
  241. #checking limit and offset values
  242. if not (limit is None):
  243. if limit <= 0:
  244. raise ValueError("Invalid limit given : %d"%limit)
  245. if not (offset is None):
  246. if offset < 0:
  247. raise ValueError("Invalid offset given : %d"%offset)
  248. #Fetching editorial components from datasource
  249. results = cls._datasource.select(
  250. target_cls = cls,
  251. field_list = field_list,
  252. filters = filters,
  253. rel_filters = relational_filters,
  254. order=order,
  255. group=group,
  256. limit=limit,
  257. offset=offset
  258. )
  259. return results
  260. ## @brief Insert a new component
  261. # @param datas dict : The value of object we want to insert
  262. # @return A new id if success else False
  263. @classmethod
  264. def insert(cls, datas, classname = None):
  265. callcls = cls if classname is None else cls.name2class(classname)
  266. if not callcls:
  267. raise LeApiErrors("Error when inserting",[ValueError("The class '%s' was not found"%classname)])
  268. if not callcls.implements_letype() and not callcls.implements_lerelation():
  269. raise ValueError("You can only insert relations and LeTypes objects but tying to insert a '%s'"%callcls.__name__)
  270. insert_datas = callcls.prepare_datas(datas, complete = True, allow_internal = False)
  271. return callcls._datasource.insert(callcls, **insert_datas)
  272. ## @brief Check and prepare datas
  273. #
  274. # @warning when complete = False we are not able to make construct_datas() and _check_data_consistency()
  275. #
  276. # @param datas dict : {fieldname : fieldvalue, ...}
  277. # @param complete bool : If True you MUST give all the datas
  278. # @param allow_internal : Wether or not interal fields are expected in datas
  279. # @return Datas ready for use
  280. @classmethod
  281. def prepare_datas(cls, datas, complete = False, allow_internal = True):
  282. if not complete:
  283. warnings.warn("\nActual implementation can make datas construction and consitency checks fails when datas are not complete\n")
  284. ret_datas = cls.check_datas_value(datas, complete, allow_internal)
  285. if isinstance(ret_datas, Exception):
  286. raise ret_datas
  287. ret_datas = cls._construct_datas(ret_datas)
  288. cls._check_datas_consistency(ret_datas)
  289. return ret_datas
  290. #-###################-#
  291. # Private methods #
  292. #-###################-#
  293. ## @brief Build a filter to select an object with a specific ID
  294. # @warning assert that the uid is not composed with multiple fieldtypes
  295. # @return A filter of the form tuple(UID, '=', self.UID)
  296. # @todo This method should not be private
  297. def _id_filter(self):
  298. id_name = self.uidname()
  299. return ( id_name, '=', getattr(self, id_name) )
  300. ## @brief Construct datas values
  301. #
  302. # @warning assert that datas is complete
  303. #
  304. # @param datas dict : Datas that have been returned by LeCrud.check_datas_value() methods
  305. # @return A new dict of datas
  306. # @todo Decide wether or not the datas are modifed inplace or returned in a new dict (second solution for the moment)
  307. @classmethod
  308. def _construct_datas(cls, datas):
  309. res_datas = dict()
  310. for fname, ftype in cls.fieldtypes().items():
  311. if fname in datas:
  312. res_datas[fname] = ftype.construct_data(cls, fname, datas)
  313. return res_datas
  314. ## @brief Check datas consistency
  315. # @warning assert that datas is complete
  316. #
  317. # @param datas dict : Datas that have been returned by LeCrud._construct_datas() method
  318. # @throw LeApiDataCheckError if fails
  319. @classmethod
  320. def _check_datas_consistency(cls, datas):
  321. err_l = []
  322. err_l = dict()
  323. for fname, ftype in cls.fieldtypes().items():
  324. ret = ftype.check_data_consistency(cls, fname, datas)
  325. if isinstance(ret, Exception):
  326. err_l[fname] = ret
  327. if len(err_l) > 0:
  328. raise LeApiDataCheckError("Datas consistency checks fails", err_l)
  329. ## @brief Prepare a field_list
  330. # @param field_list list : List of string representing fields
  331. # @return A well formated field list
  332. # @throw LeApiDataCheckError if invalid field given
  333. @classmethod
  334. def _prepare_field_list(cls, field_list):
  335. err_l = dict()
  336. ret_field_list = list()
  337. for field in field_list:
  338. if cls._field_is_relational(field):
  339. ret = cls._prepare_relational_field(field)
  340. else:
  341. ret = cls._check_field(field)
  342. if isinstance(ret, Exception):
  343. err_l[field] = ret
  344. else:
  345. ret_field_list.append(ret)
  346. if len(err_l) > 0:
  347. raise LeApiDataCheckError(err_l)
  348. return ret_field_list
  349. ## @brief Check that a relational field is valid
  350. # @param field str : a relational field
  351. # @return a nature
  352. @classmethod
  353. def _prepare_relational_fields(cls, field):
  354. raise NotImplementedError("Abstract method")
  355. ## @brief Check that the field list only contains fields that are in the current class
  356. # @return None if no problem, else returns a list of exceptions that occurs during the check
  357. @classmethod
  358. def _check_field(cls, field):
  359. if field not in cls.fieldlist():
  360. return ValueError("No such field '%s' in %s"%(field, cls.__name__))
  361. return field
  362. ## @brief Prepare the order parameter for the get method
  363. # @note if an item in order_list is just a str it is considered as ASC by default
  364. # @param order_list list : A list of field name or tuple (FIELDNAME, [ASC|DESC])
  365. # @return a list of tuple (FIELDNAME, [ASC|DESC] )
  366. @classmethod
  367. def _prepare_order_fields(cls, order_field_list):
  368. errors = dict()
  369. result = []
  370. for order_field in order_field_list:
  371. if not isinstance(order_field, tuple):
  372. order_field = (order_field, 'ASC')
  373. if len(order_field) != 2 or order_field[1].upper() not in ['ASC', 'DESC']:
  374. errors[order_field] = ValueError("Expected a string or a tuple with (FIELDNAME, ['ASC'|'DESC']) but got : %s"%order_field)
  375. else:
  376. ret = cls._check_field(order_field[0])
  377. if isinstance(ret, Exception):
  378. errors[order_field] = ret
  379. order_field = (order_field[0], order_field[1].upper())
  380. result.append(order_field)
  381. if len(errors) > 0:
  382. return LeApiErrors("Errors when preparing ordering fields", errors)
  383. return result
  384. ## @brief Prepare filters for datasource
  385. #
  386. # This method divide filters in two categories :
  387. # - filters : standart FIELDNAME OP VALUE filter
  388. # - relationnal_filters : filter on object relation RELATION_NATURE OP VALUE
  389. #
  390. # Both categories of filters are represented in the same way, a tuple with 3 elements (NAME|NAT , OP, VALUE )
  391. #
  392. # @param filters_l list : This list can contain str "FIELDNAME OP VALUE" and tuples (FIELDNAME, OP, VALUE)
  393. # @return a tuple(FILTERS, RELATIONNAL_FILTERS
  394. #
  395. # @see @ref datasource_side
  396. @classmethod
  397. def _prepare_filters(cls, filters_l):
  398. filters = list()
  399. res_filters = list()
  400. rel_filters = list()
  401. err_l = dict()
  402. #Splitting in tuple if necessary
  403. for fil in filters_l:
  404. if len(fil) == 3 and not isinstance(fil, str):
  405. filters.append(tuple(fil))
  406. else:
  407. filters.append(cls._split_filter(fil))
  408. for field, operator, value in filters:
  409. if cls._field_is_relational(field):
  410. #Checks relational fields
  411. ret = cls._prepare_relational_field(field)
  412. if isinstance(ret, Exception):
  413. err_l[field] = ret
  414. else:
  415. rel_filters.append((ret, operator, value))
  416. else:
  417. #Checks other fields
  418. ret = cls._check_field(field)
  419. if isinstance(ret, Exception):
  420. err_l[field] = ret
  421. else:
  422. res_filters.append((field,operator, value))
  423. if len(err_l) > 0:
  424. raise LeApiDataCheckError("Error while preparing filters : ", err_l)
  425. return (res_filters, rel_filters)
  426. ## @brief Check and split a query filter
  427. # @note The query_filter format is "FIELD OPERATOR VALUE"
  428. # @param query_filter str : A query_filter string
  429. # @param cls
  430. # @return a tuple (FIELD, OPERATOR, VALUE)
  431. @classmethod
  432. def _split_filter(cls, query_filter):
  433. if cls._query_re is None:
  434. cls._compile_query_re()
  435. matches = cls._query_re.match(query_filter)
  436. if not matches:
  437. raise ValueError("The query_filter '%s' seems to be invalid"%query_filter)
  438. result = (matches.group('field'), re.sub(r'\s', ' ', matches.group('operator'), count=0), matches.group('value').strip())
  439. for r in result:
  440. if len(r) == 0:
  441. raise ValueError("The query_filter '%s' seems to be invalid"%query_filter)
  442. return result
  443. ## @brief Compile the regex for query_filter processing
  444. # @note Set _LeObject._query_re
  445. @classmethod
  446. def _compile_query_re(cls):
  447. op_re_piece = '(?P<operator>(%s)'%cls._query_operators[0].replace(' ', '\s')
  448. for operator in cls._query_operators[1:]:
  449. op_re_piece += '|(%s)'%operator.replace(' ', '\s')
  450. op_re_piece += ')'
  451. 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)
  452. pass
  453. ## @brief Check if a field is relational or not
  454. # @param field str : the field to test
  455. # @return True if the field is relational else False
  456. @staticmethod
  457. def _field_is_relational(field):
  458. return field.startswith('superior.') or field.startswith('subordinate')
  459. ## @page leobject_filters LeObject query filters
  460. # The LeObject API provide methods that accept filters allowing the user
  461. # to query the database and fetch LodelEditorialObjects.
  462. #
  463. # The LeObject API translate those filters for the datasource.
  464. #
  465. # @section api_user_side API user side filters
  466. # Filters are string expressing a condition. The string composition
  467. # is as follow : "<FIELD> <OPERATOR> <VALUE>"
  468. # @subsection fpart FIELD
  469. # @subsubsection standart fields
  470. # Standart fields, represents a value of the LeObject for example "title", "lodel_id" etc.
  471. # @subsubsection rfields relationnal fields
  472. # relationnal fields, represents a relation with the object hierarchy. Those fields are composed as follow :
  473. # "<RELATION>.<NATURE>".
  474. #
  475. # - Relation can takes two values : superiors or subordinates
  476. # - Nature is a relation nature ( see EditorialModel.classtypes )
  477. # Examples : "superiors.parent", "subordinates.translation" etc.
  478. # @note The field_list arguement of leapi.leapi._LeObject.get() use the same syntax than the FIELD filter part
  479. # @subsection oppart OPERATOR
  480. # The OPERATOR part of a filter is a comparison operator. There is
  481. # - standart comparison operators : = , <, > , <=, >=, !=
  482. # - vagueness string comparison 'like' and 'not like'
  483. # - list operators : 'in' and 'not in'
  484. # The list of allowed operators is sotred at leapi.leapi._LeObject._query_operators .
  485. # @subsection valpart VALUE
  486. # The VALUE part of a filter is... just a value...
  487. #
  488. # @section datasource_side Datasource side filters
  489. # As said above the API "translate" filters before forwarding them to the datasource.
  490. #
  491. # The translation process transform filters in tuple composed of 3 elements
  492. # ( @ref fpart , @ref oppart , @ref valpart ). Each element is a string.
  493. #
  494. # There is a special case for @ref rfields : the field element is a tuple composed with two elements
  495. # ( RELATION, NATURE ) where NATURE is a string ( see EditorialModel.classtypes ) and RELATION is one of
  496. # the defined constant :
  497. #
  498. # - leapi.lecrud.REL_SUB for "subordinates"
  499. # - leapi.lecrud.REL_SUP for "superiors"
  500. #
  501. # @note The filters translation process also check if given field are valids compared to the concerned letype and/or the leclass