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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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. import leapi.leobject
  9. class LeApiErrors(Exception):
  10. ## @brief Instanciate a new exceptions handling multiple exceptions
  11. # @param expt_l list : A list of data check Exception
  12. def __init__(self, msg = "Unknow error", exceptions = None):
  13. self._msg = msg
  14. self._exceptions = list() if exceptions is None else exceptions
  15. def __str__(self):
  16. msg = self._msg
  17. for expt in self._exceptions:
  18. msg += " {expt_name}:{expt_msg}; ".format(expt_name=expt.__class__.__name__, expt_msg=str(expt))
  19. return msg
  20. def __repr__(self):
  21. return str(self)
  22. ## @brief When an error concern a query
  23. class LeApiQueryError(LeApiErrors): pass
  24. ## @brief When an error concerns a datas
  25. class LeApiDataCheckError(LeApiErrors): pass
  26. ## @brief Main class to handler lodel editorial components (relations and objects)
  27. class _LeCrud(object):
  28. ## @brief The datasource
  29. _datasource = None
  30. ## @brief abstract property to store the fieldtype representing the component identifier
  31. _uid_fieldtype = None #Will be a dict fieldname => fieldtype
  32. ## @brief will store all the fieldtypes (child classes handle it)
  33. _fieldtypes_all = None
  34. ## @brief Stores a regular expression to parse query filters strings
  35. _query_re = None
  36. ## @brief Stores Query filters operators
  37. _query_operators = ['=', '<=', '>=', '!=', '<', '>', ' in ', ' not in ']
  38. def __init__(self):
  39. raise NotImplementedError("Abstract class")
  40. ## @brief Given a dynamically generated class name return the corresponding python Class
  41. # @param name str : a concrete class name
  42. # @return False if no such component
  43. @classmethod
  44. def name2class(cls, name):
  45. mod = importlib.import_module(cls.__module__)
  46. try:
  47. return getattr(mod, name)
  48. except AttributeError:
  49. return False
  50. ## @return LeObject class
  51. @classmethod
  52. def leobject(cls):
  53. return cls.name2class('LeObject')
  54. ## @return A dict with key field name and value a fieldtype instance
  55. @classmethod
  56. def fieldtypes(cls):
  57. raise NotImplementedError("Abstract method") #child classes should return their uid fieldtype
  58. ## @return A dict with fieldtypes marked as internal
  59. @classmethod
  60. def fieldtypes_internal(self):
  61. return { fname: ft for fname, ft in cls.fieldtypes().items() if hasattr(ft, 'internal') and ft.internal }
  62. ## @return A list of field name
  63. @classmethod
  64. def fieldlist(cls):
  65. return cls.fieldtypes().keys()
  66. ## @brief Update a component in DB
  67. # @param datas dict : If None use instance attributes to update de DB
  68. # @return True if success
  69. # @todo better error handling
  70. def update(self, datas = None):
  71. datas = self.datas(internal=False) if datas is None else datas
  72. upd_datas = self.prepare_datas(datas, complete = False, allow_internal = False)
  73. filters = [self._id_filter()]
  74. rel_filters = []
  75. ret = self._datasource.update(self.__class__, filters, rel_filters, upd_datas)
  76. if ret == 1:
  77. return True
  78. else:
  79. #ERROR HANDLING
  80. return False
  81. ## @brief Delete a component
  82. # @return True if success
  83. # @todo better error handling
  84. def delete(self):
  85. filters = [self._id_filter()]
  86. rel_filters = []
  87. ret = self._datasource.delete(self.__class__, filters, rel_filters)
  88. if ret == 1:
  89. return True
  90. else:
  91. #ERROR HANDLING
  92. return False
  93. ## @brief Check that datas are valid for this type
  94. # @param datas dict : key == field name value are field values
  95. # @param complete bool : if True expect that datas provide values for all non internal fields
  96. # @param allow_internal bool : if True don't raise an error if a field is internal
  97. # @return Checked datas
  98. # @throw LeApiDataCheckError if errors reported during check
  99. @classmethod
  100. def check_datas_value(cls, datas, complete = False, allow_internal = True):
  101. err_l = [] #Stores errors
  102. correct = [] #Valid fields name
  103. mandatory = [] #mandatory fields name
  104. for fname, ftt in cls.fieldtypes().items():
  105. if allow_internal or not ftt.is_internal():
  106. correct.append(fname)
  107. if complete and not hasattr(ftt, 'default'):
  108. mandatory.append(fname)
  109. mandatory = set(mandatory)
  110. correct = set(correct)
  111. provided = set(datas.keys())
  112. #searching unknow fields
  113. print("provided", provided, "correct", correct)
  114. unknown = provided - correct
  115. for u_f in unknown:
  116. #here we can check if the field is unknown or rejected because it is internal
  117. err_l.append(AttributeError("Unknown or unauthorized field '%s'"%u_f))
  118. #searching missings fields
  119. missings = mandatory - provided
  120. for miss_field in missings:
  121. err_l.append(AttributeError("The data for field '%s' is missing"%miss_field))
  122. #Checks datas
  123. checked_datas = dict()
  124. for name, value in [ (name, value) for name, value in datas.items() if name in correct ]:
  125. checked_datas[name], err = cls.fieldtypes()[name].check_data_value(value)
  126. if err:
  127. err_l.append(err)
  128. if len(err_l) > 0:
  129. raise LeApiDataCheckError("Error while checking datas", err_l)
  130. return checked_datas
  131. ## @brief Retrieve a collection of lodel editorial components
  132. #
  133. # @param query_filters list : list of string of query filters (or tuple (FIELD, OPERATOR, VALUE) ) see @ref leobject_filters
  134. # @param field_list list|None : list of string representing fields see @ref leobject_filters
  135. # @return A list of lodel editorial components instance
  136. # @todo think about LeObject and LeClass instanciation (partial instanciation, etc)
  137. @classmethod
  138. def get(cls, query_filters, field_list = None):
  139. if not(isinstance(cls, cls.name2class('LeObject'))) and not(isinstance(cls, cls.name2class('LeRelation'))):
  140. raise NotImplementedError("Cannot call get with LeCrud")
  141. if field_list is None or len(field_list) == 0:
  142. #default field_list
  143. field_list = cls.default_fieldlist()
  144. field_list = cls.prepare_field_list(field_list) #Can raise LeApiDataCheckError
  145. #preparing filters
  146. filters, relational_filters = cls._prepare_filters(field_list)
  147. #Fetching datas from datasource
  148. db_datas = cls._datasource.get(cls, filters, relational_filters)
  149. return [ cls(**datas) for datas in db_datas]
  150. ## @brief Given filters delete components
  151. # @param filters list : list of string of query filters (or tuple (FIELD, OPERATOR, VALUE) ) see @ref leobject_filters
  152. # @return the number of deleted components
  153. # @todo Check for Abstract calls (with cls == LeCrud)
  154. @classmethod
  155. def delete_multi(cls, filters):
  156. filters, rel_filters = cls._prepare_filters(filters)
  157. return cls._datasource.delete(cls, filters, rel_filters)
  158. ## @brief Insert a new component
  159. # @param datas dict : The value of object we want to insert
  160. # @return A new id if success else False
  161. @classmethod
  162. def insert(cls, datas):
  163. insert_datas = self.prepare_datas(datas, complete = True, allow_internal = False)
  164. return cls._datasource.insert(cls, insert_datas)
  165. ## @brief Check and prepare datas
  166. #
  167. # @warning when complete = False we are not able to make construct_datas() and _check_data_consistency()
  168. #
  169. # @param datas dict : {fieldname : fieldvalue, ...}
  170. # @param complete bool : If True you MUST give all the datas
  171. # @param allow_internal : Wether or not interal fields are expected in datas
  172. # @return Datas ready for use
  173. @classmethod
  174. def prepare_datas(cls, datas, complete = False, allow_internal = True):
  175. if not complete:
  176. warnings.warn("Actual implementation can make datas construction and consitency checks fails when datas are not complete")
  177. ret_dats = self.check_datas_value(cls, datas, complete, allow_internal)
  178. ret_datas = self._construct_datas(cls, ret_datas)
  179. ret_datas = self._check_data_consistency(cls, ret_datas)
  180. return ret_datas
  181. #-###################-#
  182. # Private methods #
  183. #-###################-#
  184. ## @brief Build a filter to select an object with a specific ID
  185. # @warning assert that the uid is not composed with multiple fieldtypes
  186. # @return A filter of the form tuple(UID, '=', self.UID)
  187. def _id_filter(self):
  188. id_name = self._uid_fieldtype.keys()[0]
  189. return ( id_name, '=', getattr(self, id_name) )
  190. ## @brief Construct datas values
  191. #
  192. # @warning assert that datas is complete
  193. #
  194. # @param datas dict : Datas that have been returned by LeCrud.check_datas_value() methods
  195. # @return A new dict of datas
  196. # @todo Decide wether or not the datas are modifed inplace or returned in a new dict (second solution for the moment)
  197. @classmethod
  198. def _construct_datas(cls, datas):
  199. res_datas = dict()
  200. for fname, ftype in cls.fieldtypes().items():
  201. if fname in datas:
  202. res_datas[fname] = ftype.construct_data(datas)
  203. return res_datas
  204. ## @brief Check datas consistency
  205. # @warning assert that datas is complete
  206. #
  207. # @param datas dict : Datas that have been returned by LeCrud._construct_datas() method
  208. # @throw LeApiDataCheckError if fails
  209. @classmethod
  210. def _check_datas_consistency(cls, datas):
  211. err_l = []
  212. for fname, ftype in cls.fieldtypes().items():
  213. ret = ftype.check_data_consistency(datas)
  214. if isinstance(ret, Exception):
  215. err_l.append(ret)
  216. if len(err_l) > 0:
  217. raise LeApiDataCheckError("Datas consistency checks fails", err_l)
  218. ## @brief Prepare a field_list
  219. # @param field_list list : List of string representing fields
  220. # @return A well formated field list
  221. # @throw LeApiDataCheckError if invalid field given
  222. @classmethod
  223. def _prepare_field_list(cls, field_list):
  224. ret_field_list = list()
  225. for field in field_list:
  226. if cls._field_is_relational(field):
  227. ret = cls._prepare_relational_field(field)
  228. else:
  229. ret = cls._check_field(field)
  230. if isinstance(ret, Exception):
  231. err_l.append(ret)
  232. else:
  233. ret_field_list.append(ret)
  234. if len(err_l) > 0:
  235. raise LeApiDataCheckError(err_l)
  236. return ret_field_list
  237. ## @brief Check that a relational field is valid
  238. # @param field str : a relational field
  239. # @return a nature
  240. @classmethod
  241. def _prepare_relational_fields(cls, field):
  242. raise NotImplementedError("Abstract method")
  243. ## @brief Check that the field list only contains fields that are in the current class
  244. # @return None if no problem, else returns a list of exceptions that occurs during the check
  245. @classmethod
  246. def _check_field(cls, field):
  247. err_l = list()
  248. if field not in cls.fieldlist():
  249. return ValueError("No such field '%s' in %s"%(field, cls.__name__))
  250. return field
  251. ## @brief Prepare filters for datasource
  252. #
  253. # This method divide filters in two categories :
  254. # - filters : standart FIELDNAME OP VALUE filter
  255. # - relationnal_filters : filter on object relation RELATION_NATURE OP VALUE
  256. #
  257. # Both categories of filters are represented in the same way, a tuple with 3 elements (NAME|NAT , OP, VALUE )
  258. #
  259. # @param filters_l list : This list can contain str "FIELDNAME OP VALUE" and tuples (FIELDNAME, OP, VALUE)
  260. # @return a tuple(FILTERS, RELATIONNAL_FILTERS
  261. #
  262. # @see @ref datasource_side
  263. @classmethod
  264. def _prepare_filters(cls, filters_l):
  265. filters = list()
  266. res_filters = list()
  267. rel_filters = list()
  268. err_l = list()
  269. for fil in filters_l:
  270. if len(fil) == 3 and not isinstance(fil, str):
  271. filters.append(tuple(fil))
  272. else:
  273. filters.append(cls._split_filter(fil))
  274. for field, operator, value in filters:
  275. if cls._field_is_relational(field):
  276. #Checks relational fields
  277. ret = cls._prepare_relational_field(field)
  278. if isinstance(ret, Exception):
  279. err_l.append(ret)
  280. else:
  281. rel_filters.append((ret, operator, value))
  282. else:
  283. #Checks other fields
  284. ret = cls._check_field(field)
  285. if isinstance(ret, Exception):
  286. err_l.append(ret)
  287. else:
  288. res_filters.append((field,operator, value))
  289. if len(err_l) > 0:
  290. raise LeApiDataCheckError(err_l)
  291. return (res_filters, rel_filters)
  292. ## @brief Check and split a query filter
  293. # @note The query_filter format is "FIELD OPERATOR VALUE"
  294. # @param query_filter str : A query_filter string
  295. # @param cls
  296. # @return a tuple (FIELD, OPERATOR, VALUE)
  297. @classmethod
  298. def _split_filter(cls, query_filter):
  299. if cls._query_re is None:
  300. cls._compile_query_re()
  301. matches = cls._query_re.match(query_filter)
  302. if not matches:
  303. raise ValueError("The query_filter '%s' seems to be invalid"%query_filter)
  304. result = (matches.group('field'), re.sub(r'\s', ' ', matches.group('operator'), count=0), matches.group('value').strip())
  305. for r in result:
  306. if len(r) == 0:
  307. raise ValueError("The query_filter '%s' seems to be invalid"%query_filter)
  308. return result
  309. ## @brief Compile the regex for query_filter processing
  310. # @note Set _LeObject._query_re
  311. @classmethod
  312. def _compile_query_re(cls):
  313. op_re_piece = '(?P<operator>(%s)'%cls._query_operators[0].replace(' ', '\s')
  314. for operator in cls._query_operators[1:]:
  315. op_re_piece += '|(%s)'%operator.replace(' ', '\s')
  316. op_re_piece += ')'
  317. 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)
  318. pass
  319. ## @brief Check if a field is relational or not
  320. # @param field str : the field to test
  321. # @return True if the field is relational else False
  322. @staticmethod
  323. def _field_is_relational(field):
  324. return field.startswith('superior.') or field.startswith('subordinate')