説明なし
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

lecrud.py 15KB

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