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

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