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

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