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

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