Ei kuvausta
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

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