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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. #-*- coding: utf-8 -*-
  2. import re
  3. import copy
  4. import inspect
  5. import warnings
  6. from .exceptions import *
  7. from lodel.plugin.hooks import LodelHook
  8. from lodel import logger
  9. ##@todo check datas when running query
  10. class LeQuery(object):
  11. ##@brief Hookname prefix
  12. _hook_prefix = None
  13. ##@brief arguments for the LeObject.check_data_value()
  14. _data_check_args = { 'complete': False, 'allow_internal': False }
  15. ##@brief Abstract constructor
  16. # @param target_class LeObject : class of object the query is about
  17. def __init__(self, target_class):
  18. from .leobject import LeObject
  19. if self._hook_prefix is None:
  20. raise NotImplementedError("Abstract class")
  21. if not inspect.isclass(target_class) or \
  22. not issubclass(target_class, LeObject):
  23. raise TypeError("target class has to be a child class of LeObject but %s given"% target_class)
  24. self._target_class = target_class
  25. self._ro_datasource = target_class._ro_datasource
  26. self._rw_datasource = target_class._rw_datasource
  27. ##@brief Execute a query and return the result
  28. # @param **datas
  29. # @return the query result
  30. # @see LeQuery._query()
  31. #
  32. def execute(self, datas):
  33. if not datas is None:
  34. self._target_class.check_datas_value(
  35. datas,
  36. **self._data_check_args)
  37. self._target_class.prepare_datas(datas) #not yet implemented
  38. if self._hook_prefix is None:
  39. raise NotImplementedError("Abstract method")
  40. LodelHook.call_hook( self._hook_prefix+'_pre',
  41. self._target_class,
  42. datas)
  43. ret = self._query(datas = datas)
  44. ret = LodelHook.call_hook( self._hook_prefix+'_post',
  45. self._target_class,
  46. ret)
  47. return ret
  48. ##@brief Childs classes implements this method to execute the query
  49. # @param **datas
  50. # @return query result
  51. def _query(self, **datas):
  52. raise NotImplementedError("Asbtract method")
  53. ##@return a dict with query infos
  54. def dump_infos(self):
  55. return {'target_class': self._target_class}
  56. def __repr__(self):
  57. ret = "<{classname} target={target_class}>"
  58. return ret.format(
  59. classname=self.__class__.__name__,
  60. target_class = self._target_class)
  61. ##@brief Abstract class handling query with filters
  62. class LeFilteredQuery(LeQuery):
  63. ##@brief The available operators used in query definitions
  64. _query_operators = [
  65. ' = ',
  66. ' <= ',
  67. ' >= ',
  68. ' != ',
  69. ' < ',
  70. ' > ',
  71. ' in ',
  72. ' not in ',
  73. ' like ',
  74. ' not like ']
  75. ##@brief Regular expression to process filters
  76. _query_re = None
  77. ##@brief Abtract constructor for queries with filter
  78. #@param target_class LeObject : class of object the query is about
  79. #@param query_filters list : with a tuple (only one filter) or a list of
  80. # tuple or a dict: {OP,list(filters)} with OP = 'OR' or 'AND for tuple
  81. # (FIELD,OPERATOR,VALUE)
  82. def __init__(self, target_class, query_filters = None):
  83. super().__init__(target_class)
  84. ##@brief The query filter tuple(std_filter, relational_filters)
  85. self._query_filter = None
  86. ##@brief Stores potential subqueries (used when a query implies
  87. # more than one datasource.
  88. #
  89. # Subqueries are tuple(target_class_ref_field, LeGetQuery)
  90. self.subqueries = None
  91. query_filters = [] if query_filters is None else query_filters
  92. self.set_query_filter(query_filters)
  93. ##@brief Abstract FilteredQuery execution method
  94. #
  95. # This method takes care to execute subqueries before calling super execute
  96. def execute(self, datas = None):
  97. #copy originals filters
  98. orig_filters = copy.copy(self._query_filter)
  99. std_filters, rel_filters = self._query_filter
  100. for rfield, subq in self.subqueries:
  101. subq_res = subq.execute()
  102. std_filters.append(
  103. (rfield, ' in ', subq_res))
  104. self._query_filter = (std_filters, rel_filters)
  105. try:
  106. filters, rel_filters = self._query_filter
  107. res = super().execute(datas)
  108. except Exception as e:
  109. #restoring filters even if an exception is raised
  110. self.__query_filter = orig_filters
  111. raise e #reraise
  112. #restoring filters
  113. self._query_filter = orig_filters
  114. return res
  115. ##@brief Add filter(s) to the query
  116. #
  117. # This method is also able to slice query if different datasources are
  118. # implied in the request
  119. #
  120. #@param query_filter list|tuple|str : A single filter or a list of filters
  121. #@see LeFilteredQuery._prepare_filters()
  122. #@warning Does not support multiple UID
  123. def set_query_filter(self, query_filter):
  124. if isinstance(query_filter, str):
  125. query_filter = [query_filter]
  126. #Query filter prepration
  127. filters_orig , rel_filters = self._prepare_filters(query_filter)
  128. # Here we now that each relational filter concern only one datasource
  129. # thank's to _prepare_relational_fields
  130. #Multiple datasources detection
  131. self_ds_name = self._target_class._datasource_name
  132. result_rel_filters = list() # The filters that will stay in the query
  133. other_ds_filters = dict()
  134. for rfilter in rel_filters:
  135. (rfield, ref_dict), op, value = rfilter
  136. #rfield : the field in self._target_class
  137. tmp_rel_filter = dict() #designed to stores rel_field of same DS
  138. # First step : simplification
  139. # Trying to delete relational filters done on referenced class uid
  140. for tclass, tfield in copy.copy(ref_dict).items():
  141. #tclass : reference target class
  142. #tfield : referenced field from target class
  143. #
  144. # !!!WARNING!!!
  145. # The line below brake multi UID support
  146. #
  147. if tfield == tclass.uid_fieldname()[0]:
  148. #This relational filter can be simplified as
  149. # ref_field, op, value
  150. # Note : we will have to dedup filters_orig
  151. filters_orig.append((rfield, op, value))
  152. del(ref_dict[tclass])
  153. if len(ref_dict) == 0:
  154. continue
  155. #Determine what to do with other relational filters given
  156. # referenced class datasource
  157. #Remember : each class in a relational filter has the same
  158. # datasource
  159. tclass = list(ref_dict.keys())[0]
  160. cur_ds = tclass._datasource_name
  161. if cur_ds == self_ds_name:
  162. # Same datasource, the filter stay is self query
  163. result_rel_filters.append(((rfield, ref_dict), op, value))
  164. else:
  165. # Different datasource, we will have to create a subquery
  166. if cur_ds not in other_ds_filters:
  167. other_ds_filters[cur_ds] = list()
  168. other_ds_filters[cur_ds].append(
  169. ((rfield, ref_dict), op, value))
  170. #deduplication of std filters
  171. filters_orig = list(set(filters_orig))
  172. # Sets _query_filter attribute of self query
  173. self._query_filter = (filters_orig, result_rel_filters)
  174. #Sub queries creation
  175. subq = list()
  176. for ds, rfilters in other_ds_filters.items():
  177. for rfilter in rfilters:
  178. (rfield, ref_dict), op, value = rfilter
  179. for tclass, tfield in ref_dict.items():
  180. query = LeGetQuery(
  181. target_class = tclass,
  182. query_filters = [(tfield, op, value)],
  183. field_list = [tfield])
  184. subq.append((rfield, query))
  185. self.subqueries = subq
  186. ##@return informations
  187. def dump_infos(self):
  188. ret = super().dump_infos()
  189. ret['query_filter'] = self._query_filter
  190. ret['subqueries'] = self.subqueries
  191. return ret
  192. def __repr__(self):
  193. res = "<{classname} target={target_class} query_filter={query_filter}"
  194. res = res.format(
  195. classname=self.__class__.__name__,
  196. query_filter = self._query_filter,
  197. target_class = self._target_class)
  198. if len(self.subqueries) > 0:
  199. for n,subq in enumerate(self.subqueries):
  200. res += "\n\tSubquerie %d : %s"
  201. res %= (n, subq)
  202. res += '>'
  203. return res
  204. ## @brief Prepare filters for datasource
  205. #
  206. #A filter can be a string or a tuple with len = 3.
  207. #
  208. #This method divide filters in two categories :
  209. #
  210. #@par Simple filters
  211. #
  212. #Those filters concerns fields that represent object values (a title,
  213. #the content, etc.) They are composed of three elements : FIELDNAME OP
  214. # VALUE . Where :
  215. #- FIELDNAME is the name of the field
  216. #- OP is one of the authorized comparison operands ( see
  217. #@ref LeFilteredQuery.query_operators )
  218. #- VALUE is... a value
  219. #
  220. #@par Relational filters
  221. #
  222. #Those filters concerns on reference fields ( see the corresponding
  223. #abstract datahandler @ref lodel.leapi.datahandlers.base_classes.Reference)
  224. #The filter as quite the same composition than simple filters :
  225. # FIELDNAME[.REF_FIELD] OP VALUE . Where :
  226. #- FIELDNAME is the name of the reference field
  227. #- REF_FIELD is an optionnal addon to the base field. It indicate on wich
  228. #field of the referenced object the comparison as to be done. If no
  229. #REF_FIELD is indicated the comparison will be done on identifier.
  230. #
  231. #@param cls
  232. #@param filters_l list : This list of str or tuple (or both)
  233. #@return a tuple(FILTERS, RELATIONNAL_FILTERS
  234. #@todo move this doc in another place (a dedicated page ?)
  235. #@warning Does not supports multiple UID for an EmClass
  236. def _prepare_filters(self, filters_l):
  237. filters = list()
  238. res_filters = list()
  239. rel_filters = list()
  240. err_l = dict()
  241. #Splitting in tuple if necessary
  242. for i,fil in enumerate(filters_l):
  243. if len(fil) == 3 and not isinstance(fil, str):
  244. filters.append(tuple(fil))
  245. else:
  246. try:
  247. filters.append(self.split_filter(fil))
  248. except ValueError as e:
  249. err_l["filter %d" % i] = e
  250. for field, operator, value in filters:
  251. err_key = "%s %s %s" % (field, operator, value) #to push in err_l
  252. # Spliting field name to be able to detect a relational field
  253. field_spl = field.split('.')
  254. if len(field_spl) == 2:
  255. field, ref_field = field_spl
  256. elif len(field_spl) == 1:
  257. ref_field = None
  258. else:
  259. err_l[field] = NameError( "'%s' is not a valid relational \
  260. field name" % fieldname)
  261. continue
  262. # Checking field against target_class
  263. ret = self._check_field(self._target_class, field)
  264. if isinstance(ret, Exception):
  265. err_l[field] = ret
  266. continue
  267. field_datahandler = self._target_class.field(field)
  268. if ref_field is not None and not field_datahandler.is_reference():
  269. # inconsistency
  270. err_l[field] = NameError( "The field '%s' in %s is not \
  271. a relational field, but %s.%s was present in the filter"
  272. % ( field,
  273. self._target_class.__name__,
  274. field,
  275. ref_field))
  276. if field_datahandler.is_reference():
  277. #Relationnal field
  278. if ref_field is None:
  279. # ref_field default value
  280. #
  281. # !!! WARNING !!!
  282. # This piece of code does not supports multiple UID for an
  283. # emclass
  284. #
  285. ref_uid = [
  286. lc._uid[0] for lc in field_datahandler.linked_classes]
  287. if len(set(ref_uid)) == 1:
  288. ref_field = ref_uid[0]
  289. else:
  290. if len(ref_uid) > 1:
  291. msg = "The referenced classes are identified by \
  292. fields with different name. Unable to determine wich field to use for the \
  293. reference"
  294. else:
  295. msg = "Unknow error when trying to determine wich \
  296. field to use for the relational filter"
  297. err_l[err_key] = RuntimeError(msg)
  298. continue
  299. # Prepare relational field
  300. ret = self._prepare_relational_fields(field, ref_field)
  301. if isinstance(ret, Exception):
  302. err_l[err_key] = ret
  303. continue
  304. else:
  305. rel_filters.append((ret, operator, value))
  306. else:
  307. res_filters.append((field,operator, value))
  308. if len(err_l) > 0:
  309. raise LeApiDataCheckError(
  310. "Error while preparing filters : ",
  311. err_l)
  312. return (res_filters, rel_filters)
  313. ## @brief Check and split a query filter
  314. # @note The query_filter format is "FIELD OPERATOR VALUE"
  315. # @param query_filter str : A query_filter string
  316. # @param cls
  317. # @return a tuple (FIELD, OPERATOR, VALUE)
  318. @classmethod
  319. def split_filter(cls, query_filter):
  320. if cls._query_re is None:
  321. cls.__compile_query_re()
  322. matches = cls._query_re.match(query_filter)
  323. if not matches:
  324. msg = "The query_filter '%s' seems to be invalid"
  325. raise ValueError(msg % query_filter)
  326. result = (
  327. matches.group('field'),
  328. re.sub(r'\s', ' ', matches.group('operator'), count=0),
  329. matches.group('value').strip())
  330. result = [r.strip() for r in result]
  331. for r in result:
  332. if len(r) == 0:
  333. msg = "The query_filter '%s' seems to be invalid"
  334. raise ValueError(msg % 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)'
  341. op_re_piece %= cls._query_operators[0].replace(' ', '\s')
  342. for operator in cls._query_operators[1:]:
  343. op_re_piece += '|(%s)'%operator.replace(' ', '\s')
  344. op_re_piece += ')'
  345. re_full = '^\s*(?P<field>([a-z_][a-z0-9\-_]*\.)?[a-z_][a-z0-9\-_]*)\s*'
  346. re_full += op_re_piece+'\s*(?P<value>.*)\s*$'
  347. cls._query_re = re.compile(re_full, flags=re.IGNORECASE)
  348. pass
  349. @classmethod
  350. def _check_field(cls, target_class, fieldname):
  351. try:
  352. target_class.field(fieldname)
  353. except NameError as e:
  354. msg = "No field named '%s' in %s'"
  355. msg %= (fieldname, target_class.__name__)
  356. return NameError(msg)
  357. ##@brief Prepare a relational filter
  358. #
  359. #Relational filters are composed of a tuple like the simple filters
  360. #but the first element of this tuple is a tuple to :
  361. #
  362. #<code>( (FIELDNAME, {REF_CLASS: REF_FIELD}), OP, VALUE)</code>
  363. # Where :
  364. #- FIELDNAME is the field name is the target class
  365. #- the second element is a dict with :
  366. # - REF_CLASS as key. It's a LeObject child class
  367. # - REF_FIELD as value. The name of the referenced field in the REF_CLASS
  368. #
  369. #Visibly the REF_FIELD value of the dict will vary only when
  370. #no REF_FIELD is explicitly given in the filter string notation
  371. #and REF_CLASSES has differents uid
  372. #
  373. #@par String notation examples
  374. #<pre>contributeur IN (1,2,3,5)</pre> will be transformed into :
  375. #<pre>(
  376. # (
  377. # contributeur,
  378. # {
  379. # auteur: 'lodel_id',
  380. # traducteur: 'lodel_id'
  381. # }
  382. # ),
  383. # ' IN ',
  384. # [ 1,2,3,5 ])</pre>
  385. #@todo move the documentation to another place
  386. #
  387. #@param fieldname str : The relational field name
  388. #@param ref_field str|None : The referenced field name (if None use
  389. #uniq identifiers as referenced field
  390. #@return a well formed relational filter tuple or an Exception instance
  391. def _prepare_relational_fields(self, fieldname, ref_field = None):
  392. datahandler = self._target_class.field(fieldname)
  393. # now we are going to fetch the referenced class to see if the
  394. # reference field is valid
  395. ref_classes = datahandler.linked_classes
  396. ref_dict = dict()
  397. if ref_field is None:
  398. for ref_class in ref_classes:
  399. ref_dict[ref_class] = ref_class.uid_fieldname
  400. else:
  401. r_ds = None
  402. for ref_class in ref_classes:
  403. if r_ds is None:
  404. r_ds = ref_class._datasource_name
  405. elif ref_class._datasource_name != r_ds:
  406. return RuntimeError("All referenced class doesn't have the\
  407. same datasource. Query not possible")
  408. if ref_field in ref_class.fieldnames(True):
  409. ref_dict[ref_class] = ref_field
  410. else:
  411. msg = "Warning the class %s is not considered in \
  412. the relational filter %s"
  413. msg %= (ref_class.__name__, ref_field)
  414. logger.debug(msg)
  415. if len(ref_dict) == 0:
  416. return NameError( "No field named '%s' in referenced objects %s"
  417. % (ref_field, ref_class.__name__))
  418. return (fieldname, ref_dict)
  419. ##@brief A query to insert a new object
  420. class LeInsertQuery(LeQuery):
  421. _hook_prefix = 'leapi_insert_'
  422. _data_check_args = { 'complete': True, 'allow_internal': False }
  423. def __init__(self, target_class):
  424. super().__init__(target_class)
  425. ## @brief Implements an insert query operation, with only one insertion
  426. # @param new_datas : datas to be inserted
  427. def _query(self, datas):
  428. datas = self._target_class.prepare_datas(datas, True, False)
  429. id_inserted = self._rw_datasource.insert(self._target_class,datas)
  430. return id_inserted
  431. """
  432. ## @brief Implements an insert query operation, with multiple insertions
  433. # @param datas : list of **datas to be inserted
  434. def _query(self, datas):
  435. nb_inserted = self._datasource.insert_multi(
  436. self._target_class,datas_list)
  437. if nb_inserted < 0:
  438. raise LeApiQueryError("Multiple insertions error")
  439. return nb_inserted
  440. """
  441. ## @brief Execute the insert query
  442. def execute(self, datas):
  443. return super().execute(datas = datas)
  444. ##@brief A query to update datas for a given object
  445. #
  446. #@todo Change behavior, Huge optimization problem when updating using filters
  447. #and not instance. We have to run a GET and then 1 update by fecthed object...
  448. class LeUpdateQuery(LeFilteredQuery):
  449. _hook_prefix = 'leapi_update_'
  450. _data_check_args = { 'complete': True, 'allow_internal': False }
  451. ##@brief Instanciate an update query
  452. #
  453. #If a class and not an instance is given, no query_filters are expected
  454. #and the update will be fast and simple. Else we have to run a get query
  455. #before updating (to fetch datas, update them and then, construct them
  456. #and check their consistency)
  457. #@param target LeObject clas or instance
  458. #@param query_filters list|None
  459. #@todo change strategy with instance update. We have to accept datas for
  460. #the execute method
  461. def __init__(self, target, query_filters = None):
  462. ##@brief This attr is set only if the target argument is an
  463. #instance of a LeObject subclass
  464. self.__leobject_instance_datas = None
  465. target_class = target
  466. if not inspect.isclass(target):
  467. if query_filters is not None:
  468. msg = "No query_filters accepted when an instance is given as \
  469. target to LeUpdateQuery constructor"
  470. raise AttributeError(msg)
  471. target_class = target.__class__
  472. if target_class.initialized:
  473. self.__leobject_instance_datas = target.datas(True)
  474. else:
  475. query_filters = [(target._uid[0], '=', str(target.uid()))]
  476. super().__init__(target_class, query_filters)
  477. ##@brief Implements an update query
  478. #@param filters list : see @ref LeFilteredQuery
  479. #@param rel_filters list : see @ref LeFilteredQuery
  480. #@param datas dict : datas to update
  481. #@returns the number of updated items
  482. #@todo change stategy for instance update. Datas should be allowed
  483. #for execute method (and query)
  484. def _query(self, datas):
  485. uid_name = self._target_class._uid[0]
  486. if self.__leobject_instance_datas is not None:
  487. #Instance update
  488. #Building query_filter
  489. filters = [(
  490. uid_name,
  491. '=',
  492. str(self.__leobject_instance_datas[uid_name]))]
  493. res = self._rw_datasource.update(
  494. self._target_class, filters, [],
  495. self.__leobject_instance_datas)
  496. else:
  497. #Update by filters, we have to fetch datas before updating
  498. res = self._ro_datasource.select(
  499. self._target_class, self._target_class.fieldnames(True),
  500. self._query_filter[0],
  501. self._query_filter[1])
  502. #Checking and constructing datas
  503. upd_datas = dict()
  504. for res_data in res:
  505. res_data.update(datas)
  506. res_datas = self._target_class.prepare_datas(
  507. res_data, True, True)
  508. filters = [(uid_name, '=', str(res_data[uid_name]))]
  509. res = self._rw_datasource.update(
  510. self._target_class, filters, [],
  511. res_datas)
  512. return res
  513. ## @brief Execute the update query
  514. def execute(self, datas = None):
  515. if self.__leobject_instance_datas is not None and datas is not None:
  516. raise LeApiQueryError("No datas expected when running an update \
  517. query on an instance")
  518. if self.__leobject_instance_datas is None and datas is None:
  519. raise LeApiQueryError("Datas are mandatory when running an update \
  520. query on a class with filters")
  521. return super().execute(datas = datas)
  522. ##@brief A query to delete an object
  523. class LeDeleteQuery(LeFilteredQuery):
  524. _hook_prefix = 'leapi_delete_'
  525. def __init__(self, target_class, query_filter):
  526. super().__init__(target_class, query_filter)
  527. ## @brief Execute the delete query
  528. def execute(self, datas = None):
  529. return super().execute()
  530. ##@brief Implements delete query operations
  531. #@param filters list : see @ref LeFilteredQuery
  532. #@param rel_filters list : see @ref LeFilteredQuery
  533. #@returns the number of deleted items
  534. def _query(self, datas = None):
  535. filters, rel_filters = self._query_filter
  536. nb_deleted = self._rw_datasource.delete(
  537. self._target_class, filters, rel_filters)
  538. return nb_deleted
  539. class LeGetQuery(LeFilteredQuery):
  540. _hook_prefix = 'leapi_get_'
  541. ##@brief Instanciate a new get query
  542. #@param target_class LeObject : class of object the query is about
  543. #@param query_filters dict : {OP, list of query filters }
  544. # or tuple (FIELD, OPERATOR, VALUE) )
  545. #@param field_list list|None : list of string representing fields see
  546. # @ref leobject_filters
  547. #@param order list : A list of field names or tuple (FIELDNAME,[ASC | DESC])
  548. #@param group list : A list of field names or tuple (FIELDNAME,[ASC | DESC])
  549. #@param limit int : The maximum number of returned results
  550. #@param offset int : offset
  551. def __init__(self, target_class, query_filters, **kwargs):
  552. super().__init__(target_class, query_filters)
  553. ##@brief The fields to get
  554. self._field_list = None
  555. ##@brief An equivalent to the SQL ORDER BY
  556. self._order = None
  557. ##@brief An equivalent to the SQL GROUP BY
  558. self._group = None
  559. ##@brief An equivalent to the SQL LIMIT x
  560. self._limit = None
  561. ##@brief An equivalent to the SQL LIMIT x, OFFSET
  562. self._offset = 0
  563. # Checking kwargs and assigning default values if there is some
  564. for argname in kwargs:
  565. if argname not in (
  566. 'field_list', 'order', 'group', 'limit', 'offset'):
  567. raise TypeError("Unexpected argument '%s'" % argname)
  568. if 'field_list' not in kwargs:
  569. self.set_field_list(target_class.fieldnames(include_ro = True))
  570. else:
  571. self.set_field_list(kwargs['field_list'])
  572. if 'order' in kwargs:
  573. #check kwargs['order']
  574. self._order = kwargs['order']
  575. if 'group' in kwargs:
  576. #check kwargs['group']
  577. self._group = kwargs['group']
  578. if 'limit' in kwargs and kwargs['limit'] is not None:
  579. try:
  580. self._limit = int(kwargs['limit'])
  581. if self._limit <= 0:
  582. raise ValueError()
  583. except ValueError:
  584. msg = "limit argument expected to be an interger > 0"
  585. raise ValueError(msg)
  586. if 'offset' in kwargs:
  587. try:
  588. self._offset = int(kwargs['offset'])
  589. if self._offset < 0:
  590. raise ValueError()
  591. except ValueError:
  592. msg = "offset argument expected to be an integer >= 0"
  593. raise ValueError(msg)
  594. ##@brief Set the field list
  595. # @param field_list list | None : If None use all fields
  596. # @return None
  597. # @throw LeApiQueryError if unknown field given
  598. def set_field_list(self, field_list):
  599. err_l = dict()
  600. for fieldname in field_list:
  601. ret = self._check_field(self._target_class, fieldname)
  602. if isinstance(ret, Exception):
  603. msg = "No field named '%s' in %s"
  604. msg %= (fieldname, self._target_class.__name__)
  605. expt = NameError(msg)
  606. err_l[fieldname] = expt
  607. if len(err_l) > 0:
  608. msg = "Error while setting field_list in a get query"
  609. raise LeApiQueryErrors(msg = msg, exceptions = err_l)
  610. self._field_list = list(set(field_list))
  611. ##@brief Execute the get query
  612. def execute(self, datas = None):
  613. return super().execute()
  614. ##@brief Implements select query operations
  615. # @returns a list containing the item(s)
  616. def _query(self, datas = None):
  617. # select datas corresponding to query_filter
  618. l_datas=self._ro_datasource.select(
  619. target = self._target_class,
  620. field_list = list(self._field_list),
  621. filters = self._query_filter[0],
  622. relational_filters = self._query_filter[1],
  623. order = self._order,
  624. group = self._group,
  625. limit = self._limit,
  626. offset = self._offset)
  627. return l_datas
  628. ##@return a dict with query infos
  629. def dump_infos(self):
  630. ret = super().dump_infos()
  631. ret.update( { 'field_list' : self._field_list,
  632. 'order' : self._order,
  633. 'group' : self._group,
  634. 'limit' : self._limit,
  635. 'offset': self._offset,
  636. })
  637. return ret
  638. def __repr__(self):
  639. res = "<LeGetQuery target={target_class} filter={query_filter} \
  640. field_list={field_list} order={order} group={group} limit={limit} \
  641. offset={offset}"
  642. res = res.format(**self.dump_infos())
  643. if len(self.subqueries) > 0:
  644. for n,subq in enumerate(self.subqueries):
  645. res += "\n\tSubquerie %d : %s"
  646. res %= (n, subq)
  647. res += ">"
  648. return res