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.

query.py 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. #-*- coding: utf-8 -*-
  2. import re
  3. from .leobject import LeObject, LeApiErrors, LeApiDataCheckError
  4. from lodel.plugin.hooks import LodelHook
  5. from lodel import logger
  6. class LeQueryError(Exception):
  7. ##@brief Instanciate a new exceptions handling multiple exceptions
  8. #@param msg str : Exception message
  9. #@param exceptions dict : A list of data check Exception with concerned
  10. # field (or stuff) as key
  11. def __init__(self, msg = "Unknow error", exceptions = None):
  12. self._msg = msg
  13. self._exceptions = dict() if exceptions is None else exceptions
  14. def __repr__(self):
  15. return self.__str__()
  16. def __str__(self):
  17. msg = self._msg
  18. if isinstance(self._exceptions, dict):
  19. for_iter = self._exceptions.items()
  20. else:
  21. for_iter = enumerate(self.__exceptions)
  22. for obj, expt in for_iter:
  23. msg += "\n\t{expt_obj} : ({expt_name}) {expt_msg}; ".format(
  24. expt_obj = obj,
  25. expt_name=expt.__class__.__name__,
  26. expt_msg=str(expt)
  27. )
  28. return msg
  29. class LeQuery(object):
  30. ##@brief Hookname prefix
  31. _hook_prefix = None
  32. ##@brief arguments for the LeObject.check_data_value()
  33. _data_check_args = { 'complete': False, 'allow_internal': False }
  34. ##@brief Abstract constructor
  35. # @param target_class LeObject : class of object the query is about
  36. def __init__(self, target_class):
  37. if self._hook_prefix is None:
  38. raise NotImplementedError("Abstract class")
  39. if not issubclass(target_class, LeObject):
  40. raise TypeError("target class has to be a child class of LeObject")
  41. self._target_class = target_class
  42. ##@brief Execute a query and return the result
  43. # @param **datas
  44. # @return the query result
  45. # @see LeQuery.__query()
  46. #
  47. # @note maybe the datasource in not an argument but should be determined
  48. #elsewhere
  49. def execute(self, datasource, datas = None):
  50. if len(datas) > 0:
  51. self._target_class.check_datas_value(
  52. datas,
  53. **self._data_check_args)
  54. self._target_class.prepare_datas() #not yet implemented
  55. if self._hook_prefix is None:
  56. raise NotImplementedError("Abstract method")
  57. LodelHook.call_hook( self._hook_prefix+'_pre',
  58. self._target_class,
  59. datas)
  60. ret = self.__query(datasource, **datas)
  61. ret = LodelHook.call_hook( self._hook_prefix+'_post',
  62. self._target_class,
  63. ret)
  64. return ret
  65. ##@brief Childs classes implements this method to execute the query
  66. # @param **datas
  67. # @return query result
  68. def __query(self, **datas):
  69. raise NotImplementedError("Asbtract method")
  70. ##@return a dict with query infos
  71. def dump_infos(self):
  72. return {'target_class': self._target_class}
  73. def __repr__(self):
  74. ret = "<{classname} target={target_class}>"
  75. return ret.format(
  76. classname=self.__class__.__name__,
  77. target_class = self._target_class)
  78. class LeFilteredQuery(LeQuery):
  79. ##@brief The available operators used in query definitions
  80. _query_operators = [
  81. '=',
  82. '<=',
  83. '>=',
  84. '!=',
  85. '<',
  86. '>',
  87. 'in',
  88. 'not in',
  89. 'like',
  90. 'not like']
  91. ##@brief Regular expression to process filters
  92. _query_re = None
  93. ##@brief Abtract constructor for queries with filter
  94. # @param target_class LeObject : class of object the query is about
  95. # @param query_filters list : with a tuple (only one filter) or a list of tuple
  96. # or a dict: {OP,list(filters)} with OP = 'OR' or 'AND
  97. # For tuple (FIELD,OPERATOR,VALUE)
  98. def __init__(self, target_class, query_filters = None):
  99. super().__init__(target_class)
  100. ##@brief The query filter tuple(std_filter, relational_filters)
  101. self.__query_filter = None
  102. self.set_query_filter(query_filters)
  103. ##@brief Add filter(s) to the query
  104. #@param query_filter list|tuple|str : A single filter or a list of filters
  105. #@see LeFilteredQuery._prepare_filters()
  106. def set_query_filter(self, query_filter):
  107. if isinstance(query_filter, str):
  108. query_filter = [query_filter]
  109. self.__query_filter = self._prepare_filters(query_filter)
  110. def dump_infos(self):
  111. ret = super().dump_infos()
  112. ret['query_filter'] = self.__query_filter
  113. return ret
  114. def __repr__(self):
  115. ret = "<{classname} target={target_class} query_filter={query_filter}>"
  116. return ret.format(
  117. classname=self.__class__.__name__,
  118. query_filter = self.__query_filter,
  119. target_class = self._target_class)
  120. ## @brief Prepare filters for datasource
  121. #
  122. #A filter can be a string or a tuple with len = 3.
  123. #
  124. #This method divide filters in two categories :
  125. #
  126. #@par Simple filters
  127. #
  128. #Those filters concerns fields that represent object values (a title,
  129. #the content, etc.) They are composed of three elements : FIELDNAME OP
  130. # VALUE . Where :
  131. #- FIELDNAME is the name of the field
  132. #- OP is one of the authorized comparison operands ( see
  133. #@ref LeFilteredQuery.query_operators )
  134. #- VALUE is... a value
  135. #
  136. #@par Relational filters
  137. #
  138. #Those filters concerns on reference fields ( see the corresponding
  139. #abstract datahandler @ref lodel.leapi.datahandlers.base_classes.Reference)
  140. #The filter as quite the same composition than simple filters :
  141. # FIELDNAME[.REF_FIELD] OP VALUE . Where :
  142. #- FIELDNAME is the name of the reference field
  143. #- REF_FIELD is an optionnal addon to the base field. It indicate on wich
  144. #field of the referenced object the comparison as to be done. If no
  145. #REF_FIELD is indicated the comparison will be done on identifier.
  146. #
  147. #@param cls
  148. #@param filters_l list : This list of str or tuple (or both)
  149. #@return a tuple(FILTERS, RELATIONNAL_FILTERS
  150. #@todo move this doc in another place (a dedicated page ?)
  151. def _prepare_filters(self, filters_l):
  152. filters = list()
  153. res_filters = list()
  154. rel_filters = list()
  155. err_l = dict()
  156. #Splitting in tuple if necessary
  157. for i,fil in enumerate(filters_l):
  158. if len(fil) == 3 and not isinstance(fil, str):
  159. filters.append(tuple(fil))
  160. else:
  161. try:
  162. filters.append(self.split_filter(fil))
  163. except ValueError as e:
  164. err_l["filter %d" % i] = e
  165. for field, operator, value in filters:
  166. # Spliting field name to be able to detect a relational field
  167. field_spl = field.split('.')
  168. if len(field_spl) == 2:
  169. field, ref_field = field_spl
  170. elif len(field_spl) == 1:
  171. ref_field = None
  172. else:
  173. err_l[field] = NameError( "'%s' is not a valid relational \
  174. field name" % fieldname)
  175. continue
  176. # Checking field against target_class
  177. ret = self.__check_field(self._target_class, field)
  178. if isinstance(ret, Exception):
  179. err_l[field] = ret
  180. continue
  181. # Check that the field is relational if ref_field given
  182. if ref_field is not None and not cls.field(field).is_reference():
  183. # inconsistency
  184. err_l[field] = NameError( "The field '%s' in %s is not\
  185. a relational field, but %s.%s was present in the filter"
  186. % ( field,
  187. field,
  188. ref_field))
  189. # Prepare relational field
  190. if self._target_class.field(field).is_reference():
  191. ret = self._prepare_relational_fields(field, ref_field)
  192. if isinstance(ret, Exception):
  193. err_l[field] = ret
  194. else:
  195. rel_filters.append((ret, operator, value))
  196. else:
  197. res_filters.append((field,operator, value))
  198. if len(err_l) > 0:
  199. raise LeApiDataCheckError(
  200. "Error while preparing filters : ",
  201. err_l)
  202. return (res_filters, rel_filters)
  203. ## @brief Check and split a query filter
  204. # @note The query_filter format is "FIELD OPERATOR VALUE"
  205. # @param query_filter str : A query_filter string
  206. # @param cls
  207. # @return a tuple (FIELD, OPERATOR, VALUE)
  208. @classmethod
  209. def split_filter(cls, query_filter):
  210. if cls._query_re is None:
  211. cls.__compile_query_re()
  212. matches = cls._query_re.match(query_filter)
  213. if not matches:
  214. raise ValueError("The query_filter '%s' seems to be invalid"%query_filter)
  215. result = (matches.group('field'), re.sub(r'\s', ' ', matches.group('operator'), count=0), matches.group('value').strip())
  216. for r in result:
  217. if len(r) == 0:
  218. raise ValueError("The query_filter '%s' seems to be invalid"%query_filter)
  219. return result
  220. ## @brief Compile the regex for query_filter processing
  221. # @note Set _LeObject._query_re
  222. @classmethod
  223. def __compile_query_re(cls):
  224. op_re_piece = '(?P<operator>(%s)'%cls._query_operators[0].replace(' ', '\s')
  225. for operator in cls._query_operators[1:]:
  226. op_re_piece += '|(%s)'%operator.replace(' ', '\s')
  227. op_re_piece += ')'
  228. 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)
  229. pass
  230. @classmethod
  231. def __check_field(cls, target_class, fieldname):
  232. try:
  233. target_class.field(fieldname)
  234. except NameError:
  235. tc_name = target_class.__name__
  236. return ValueError("No such field '%s' in %s" % ( fieldname,
  237. tc_name))
  238. ##@brief Prepare a relational filter
  239. #
  240. #Relational filters are composed of a tuple like the simple filters
  241. #but the first element of this tuple is a tuple to :
  242. #
  243. #<code>( (FIELDNAME, {REF_CLASS: REF_FIELD}), OP, VALUE)</code>
  244. # Where :
  245. #- FIELDNAME is the field name is the target class
  246. #- the second element is a dict with :
  247. # - REF_CLASS as key. It's a LeObject child class
  248. # - REF_FIELD as value. The name of the referenced field in the REF_CLASS
  249. #
  250. #Visibly the REF_FIELD value of the dict will vary only when
  251. #no REF_FIELD is explicitly given in the filter string notation
  252. #and REF_CLASSES has differents uid
  253. #
  254. #@par String notation examples
  255. #<pre>contributeur IN (1,2,3,5)</pre> will be transformed into :
  256. #<pre>(
  257. # (
  258. # contributeur,
  259. # {
  260. # auteur: 'lodel_id',
  261. # traducteur: 'lodel_id'
  262. # }
  263. # ),
  264. # ' IN ',
  265. # [ 1,2,3,5 ])</pre>
  266. #@todo move the documentation to another place
  267. #
  268. #@param fieldname str : The relational field name
  269. #@param ref_field str|None : The referenced field name (if None use
  270. #uniq identifiers as referenced field
  271. #@return a well formed relational filter tuple or an Exception instance
  272. @classmethod
  273. def __prepare_relational_fields(cls, fieldname, ref_field = None):
  274. datahandler = self._target_class.field(fieldname)
  275. # now we are going to fetch the referenced class to see if the
  276. # reference field is valid
  277. ref_classes = datahandler.linked_classes
  278. ref_dict = dict()
  279. if ref_field is None:
  280. for ref_class in ref_classes:
  281. ref_dict[ref_class] = ref_class.uid_fieldname
  282. else:
  283. for ref_class in ref_classes:
  284. if ref_field in ref_class.fieldnames(True):
  285. ref_dict[ref_class] = ref_field
  286. else:
  287. logger.debug("Warning the class %s is not considered in \
  288. the relational filter %s" % ref_class.__name__)
  289. if len(ref_dict) == 0:
  290. return NameError( "No field named '%s' in referenced objects"
  291. % ref_field)
  292. return ( (fieldname, ref_dict), op, value)
  293. ##@brief A query to insert a new object
  294. class LeInsertQuery(LeQuery):
  295. _hook_prefix = 'leapi_insert_'
  296. _data_check_args = { 'complete': True, 'allow_internal': False }
  297. def __init__(self, target_class):
  298. super().__init__(target_class)
  299. ## @brief Implements an insert query operation, with only one insertion
  300. # @param **datas : datas to be inserted
  301. def __query(self, datasource, **datas):
  302. nb_inserted = datasource.insert(self._target_class,**datas)
  303. if nb_inserted < 0:
  304. raise LeQueryError("Insertion error")
  305. return nb_inserted
  306. ## @brief Implements an insert query operation, with multiple insertions
  307. # @param datas : list of **datas to be inserted
  308. def __query(self, datasource, datas):
  309. nb_inserted = datasource.insert_multi(self._target_class,datas_list)
  310. if nb_inserted < 0:
  311. raise LeQueryError("Multiple insertions error")
  312. return nb_inserted
  313. ## @brief Execute the insert query
  314. def execute(self, datasource, **datas):
  315. super().execute(datasource, **datas)
  316. ##@brief A query to update datas for a given object
  317. class LeUpdateQuery(LeFilteredQuery):
  318. _hook_prefix = 'leapi_update_'
  319. _data_check_args = { 'complete': True, 'allow_internal': False }
  320. def __init__(self, target_class, query_filter):
  321. super().__init__(target_class, query_filter)
  322. ##@brief Implements an update query
  323. # @param **datas : datas to update
  324. # @returns the number of updated items
  325. # @exception when the number of updated items is not as expected
  326. def __query(self, datasource, **datas):
  327. # select _uid corresponding to query_filter
  328. l_uids=datasource.select(self._target_class,list(self._target_class.getuid()),query_filter,None, None, None, None, 0, False)
  329. # list of dict l_uids : _uid(s) of the objects to be updated, corresponding datas
  330. nb_updated = datasource.update(self._target_class,l_uids, **datas)
  331. if nb_updated != len(l_uids):
  332. raise LeQueryError("Number of updated items: %d is not as expected: %d " % (nb_updated, len(l_uids)))
  333. return nb_updated
  334. ## @brief Execute the update query
  335. def execute(self, datasource, **datas):
  336. super().execute(datasource, **datas)
  337. ##@brief A query to delete an object
  338. class LeDeleteQuery(LeFilteredQuery):
  339. _hook_prefix = 'leapi_delete_'
  340. def __init__(self, target_class, query_filter):
  341. super().__init__(target_class, query_filter)
  342. ## @brief Execute the delete query
  343. def execute(self, datasource):
  344. super().execute()
  345. ##@brief Implements delete query operations
  346. # @returns the number of deleted items
  347. # @exception when the number of deleted items is not as expected
  348. def __query(self, datasource):
  349. # select _uid corresponding to query_filter
  350. l_uids=datasource.select(self._target_class,list(self._target_class.getuid()),query_filter,None, None, None, None, 0, False)
  351. # list of dict l_uids : _uid(s) of the objects to be deleted
  352. nb_deleted = datasource.update(self._target_class,l_uids, **datas)
  353. if nb_deleted != len(l_uids):
  354. raise LeQueryError("Number of deleted items %d is not as expected %d " % (nb_deleted, len(l_uids)))
  355. return nb_deleted
  356. class LeGetQuery(LeFilteredQuery):
  357. _hook_prefix = 'leapi_get_'
  358. ##@brief Instanciate a new get query
  359. # @param target_class LeObject : class of object the query is about
  360. # @param query_filters dict : {OP, list of query filters }
  361. # or tuple (FIELD, OPERATOR, VALUE) )
  362. # @param field_list list|None : list of string representing fields see @ref leobject_filters
  363. # @param order list : A list of field names or tuple (FIELDNAME, [ASC | DESC])
  364. # @param group list : A list of field names or tuple (FIELDNAME, [ASC | DESC])
  365. # @param limit int : The maximum number of returned results
  366. # @param offset int : offset
  367. def __init__(self, target_class, query_filter, **kwargs):
  368. super().__init__(target_class, query_filter)
  369. ##@brief The fields to get
  370. self.__field_list = None
  371. ##@brief An equivalent to the SQL ORDER BY
  372. self.__order = None
  373. ##@brief An equivalent to the SQL GROUP BY
  374. self.__group = None
  375. ##@brief An equivalent to the SQL LIMIT x
  376. self.__limit = None
  377. ##@brief An equivalent to the SQL LIMIT x, OFFSET
  378. self.__offset = 0
  379. # Checking kwargs and assigning default values if there is some
  380. for argname in kwargs:
  381. if argname not in ('order', 'group', 'limit', 'offset'):
  382. raise TypeError("Unexpected argument '%s'" % argname)
  383. if 'field_list' not in kwargs:
  384. #field_list = target_class.get_field_list
  385. self.__field_list = target_class.fieldnames(include_ro = True)
  386. else:
  387. #target_class.check_fields(kwargs['field_list'])
  388. self.__field_list = kwargs['field_list']
  389. if 'order' in kwargs:
  390. #check kwargs['order']
  391. self.__order = kwargs['order']
  392. if 'group' in kwargs:
  393. #check kwargs['group']
  394. self.__group = kwargs['group']
  395. if 'limit' in kwargs:
  396. try:
  397. self.__limit = int(kwargs[limit])
  398. if self.__limit <= 0:
  399. raise ValueError()
  400. except ValueError:
  401. raise ValueError("limit argument expected to be an interger > 0")
  402. if 'offset' in kwargs:
  403. try:
  404. self.__offset = int(kwargs['offset'])
  405. if self.__offset < 0:
  406. raise ValueError()
  407. except ValueError:
  408. raise ValueError("offset argument expected to be an integer >= 0")
  409. ##@brief Execute the get query
  410. def execute(self, datasource):
  411. super().execute(datasource)
  412. ##@brief Implements select query operations
  413. # @returns a list containing the item(s)
  414. def __query(self, datasource):
  415. # select datas corresponding to query_filter
  416. l_datas=datasource.select(self._target_class,list(self.field_list),self.query_filter,None, self.__order, self.__group, self.__limit, self.offset, False)
  417. return l_datas
  418. ##@return a dict with query infos
  419. def dump_infos(self):
  420. ret = super().dump_infos()
  421. ret.update( { 'field_list' : self.__field_list,
  422. 'order' : self.__order,
  423. 'group' : self.__group,
  424. 'limit' : self.__limit,
  425. 'offset': self.__offset,
  426. })
  427. return ret
  428. def __repr__(self):
  429. ret = "<LeGetQuery target={target_class} filter={query_filter} field_list={field_list} order={order} group={group} limit={limit} offset={offset}>"
  430. return ret.format(**self.dump_infos())