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.

leobject.py 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. #-*- coding: utf-8 -*-
  2. import importlib
  3. import warnings
  4. import copy
  5. from lodel.context import LodelContext
  6. LodelContext.expose_modules(globals(), {
  7. 'lodel.logger': 'logger',
  8. 'lodel.settings': 'Settings',
  9. 'lodel.settings.utils': 'SettingsError',
  10. 'lodel.leapi.query': ['LeInsertQuery', 'LeUpdateQuery', 'LeDeleteQuery',
  11. 'LeGetQuery'],
  12. 'lodel.leapi.exceptions': ['LeApiError', 'LeApiErrors',
  13. 'LeApiDataCheckError', 'LeApiDataCheckErrors', 'LeApiQueryError',
  14. 'LeApiQueryErrors'],
  15. 'lodel.plugin.exceptions': ['PluginError', 'PluginTypeError',
  16. 'LodelScriptError', 'DatasourcePluginError'],
  17. 'lodel.exceptions': ['LodelFatalError'],
  18. 'lodel.plugin.hooks': ['LodelHook'],
  19. 'lodel.plugin': ['Plugin', 'DatasourcePlugin'],
  20. 'lodel.leapi.datahandlers.base_classes': ['DatasConstructor', 'Reference']})
  21. ##@brief Stores the name of the field present in each LeObject that indicates
  22. #the name of LeObject subclass represented by this object
  23. CLASS_ID_FIELDNAME = "classname"
  24. ##@brief Wrapper class for LeObject getter & setter
  25. #
  26. # This class intend to provide easy & friendly access to LeObject fields values
  27. # without name collision problems
  28. # @note Wrapped methods are : LeObject.data() & LeObject.set_data()
  29. class LeObjectValues(object):
  30. ##@brief Construct a new LeObjectValues
  31. # @param set_callback method : The LeObject.set_datas() method of corresponding LeObject class
  32. # @param get_callback method : The LeObject.get_datas() method of corresponding LeObject class
  33. def __init__(self, fieldnames_callback, set_callback, get_callback):
  34. self._setter = set_callback
  35. self._getter = get_callback
  36. ##@brief Provide read access to datas values
  37. # @note Read access should be provided for all fields
  38. # @param fname str : Field name
  39. def __getattribute__(self, fname):
  40. getter = super().__getattribute__('_getter')
  41. return getter(fname)
  42. ##@brief Provide write access to datas values
  43. # @note Write acces shouldn't be provided for internal or immutable fields
  44. # @param fname str : Field name
  45. # @param fval * : the field value
  46. def __setattribute__(self, fname, fval):
  47. setter = super().__getattribute__('_setter')
  48. return setter(fname, fval)
  49. class LeObject(object):
  50. ##@brief boolean that tells if an object is abtract or not
  51. _abstract = None
  52. ##@brief A dict that stores DataHandler instances indexed by field name
  53. _fields = None
  54. ##@brief A tuple of fieldname (or a uniq fieldname) representing uid
  55. _uid = None
  56. ##@brief Read only datasource ( see @ref lodel2_datasources )
  57. _ro_datasource = None
  58. ##@brief Read & write datasource ( see @ref lodel2_datasources )
  59. _rw_datasource = None
  60. ##@brief Store the list of child classes
  61. _child_classes = None
  62. ##@brief Name of the datasource plugin
  63. _datasource_name = None
  64. def __new__(cls, **kwargs):
  65. self = object.__new__(cls)
  66. ##@brief A dict that stores fieldvalues indexed by fieldname
  67. self.__datas = { fname:None for fname in self._fields }
  68. ##@brief Store a list of initianilized fields when instanciation not complete else store True
  69. self.__initialized = list()
  70. ##@brief Datas accessor. Instance of @ref LeObjectValues
  71. self.d = LeObjectValues(self.fieldnames, self.set_data, self.data)
  72. for fieldname, fieldval in kwargs.items():
  73. self.__datas[fieldname] = fieldval
  74. self.__initialized.append(fieldname)
  75. self.__is_initialized = False
  76. self.__set_initialized()
  77. return self
  78. ##@brief Construct an object representing an Editorial component
  79. # @note Can be considered as EmClass instance
  80. def __init__(self, **kwargs):
  81. if self._abstract:
  82. raise NotImplementedError("%s is abstract, you cannot instanciate it." % self.__class__.__name__ )
  83. # Checks that uid is given
  84. for uid_name in self._uid:
  85. if uid_name not in kwargs:
  86. raise LeApiError("Cannot instanciate a LeObject without it's identifier")
  87. self.__datas[uid_name] = kwargs[uid_name]
  88. del(kwargs[uid_name])
  89. self.__initialized.append(uid_name)
  90. # Processing given fields
  91. allowed_fieldnames = self.fieldnames(include_ro = False)
  92. err_list = dict()
  93. for fieldname, fieldval in kwargs.items():
  94. if fieldname not in allowed_fieldnames:
  95. if fieldname in self._fields:
  96. err_list[fieldname] = LeApiError(
  97. "Value given but the field is internal")
  98. else:
  99. err_list[fieldname] = LeApiError(
  100. "Unknown fieldname : '%s'" % fieldname)
  101. else:
  102. self.__datas[fieldname] = fieldval
  103. self.__initialized.append(fieldname)
  104. if len(err_list) > 0:
  105. raise LeApiErrors(msg = "Unable to __init__ %s" % self.__class__,
  106. exceptions = err_list)
  107. self.__set_initialized()
  108. #-----------------------------------#
  109. # Fields datas handling methods #
  110. #-----------------------------------#
  111. ##@brief Property method True if LeObject is initialized else False
  112. @property
  113. def initialized(self):
  114. return self.__is_initialized
  115. ##@return The uid field name
  116. @classmethod
  117. def uid_fieldname(cls):
  118. return cls._uid
  119. ##@brief Return a list of fieldnames
  120. # @param include_ro bool : if True include read only field names
  121. # @return a list of str
  122. @classmethod
  123. def fieldnames(cls, include_ro = False):
  124. if not include_ro:
  125. return [ fname for fname in cls._fields if not cls._fields[fname].is_internal() ]
  126. else:
  127. return list(cls._fields.keys())
  128. @classmethod
  129. def name2objname(cls, name):
  130. return name.title()
  131. ##@brief Return the datahandler asssociated with a LeObject field
  132. # @param fieldname str : The fieldname
  133. # @return A data handler instance
  134. #@todo update class of exception raised
  135. @classmethod
  136. def data_handler(cls, fieldname):
  137. if not fieldname in cls._fields:
  138. raise NameError("No field named '%s' in %s" % (fieldname, cls.__name__))
  139. return cls._fields[fieldname]
  140. ##@brief Getter for references datahandlers
  141. #@param with_backref bool : if true return only references with back_references
  142. #@return <code>{'fieldname': datahandler, ...}</code>
  143. @classmethod
  144. def reference_handlers(cls, with_backref = True):
  145. return { fname: fdh
  146. for fname, fdh in cls.fields(True).items()
  147. if fdh.is_reference() and \
  148. (not with_backref or fdh.back_reference is not None)}
  149. ##@brief Return a LeObject child class from a name
  150. # @warning This method has to be called from dynamically generated LeObjects
  151. # @param leobject_name str : LeObject name
  152. # @return A LeObject child class
  153. # @throw NameError if invalid name given
  154. @classmethod
  155. def name2class(cls, leobject_name):
  156. if cls.__module__ == 'lodel.leapi.leobject':
  157. raise NotImplementedError("Abstract method")
  158. mod = importlib.import_module(cls.__module__)
  159. try:
  160. return getattr(mod, leobject_name)
  161. except (AttributeError, TypeError) :
  162. raise LeApiError("No LeObject named '%s'" % leobject_name)
  163. @classmethod
  164. def is_abstract(cls):
  165. return cls._abstract
  166. ##@brief Field data handler getter
  167. #@param fieldname str : The field name
  168. #@return A datahandler instance
  169. #@throw NameError if the field doesn't exist
  170. @classmethod
  171. def field(cls, fieldname):
  172. try:
  173. return cls._fields[fieldname]
  174. except KeyError:
  175. raise NameError("No field named '%s' in %s" % ( fieldname,
  176. cls.__name__))
  177. ##@return A dict with fieldname as key and datahandler as instance
  178. @classmethod
  179. def fields(cls, include_ro = False):
  180. if include_ro:
  181. return copy.copy(cls._fields)
  182. else:
  183. return {fname:cls._fields[fname] for fname in cls._fields if not cls._fields[fname].is_internal()}
  184. ##@brief Return the list of parents classes
  185. #
  186. #@note the first item of the list is the current class, the second is it's
  187. #parent etc...
  188. #@param cls
  189. #@warning multiple inheritance broken by this method
  190. #@return a list of LeObject child classes
  191. #@todo multiple parent capabilities implementation
  192. @classmethod
  193. def hierarch(cls):
  194. res = [cls]
  195. cur = cls
  196. while True:
  197. cur = cur.__bases__[0] # Multiple inheritance broken HERE
  198. if cur in (LeObject, object):
  199. break
  200. else:
  201. res.append(cur)
  202. return res
  203. ##@brief Return a tuple a child classes
  204. #@return a tuple of child classes
  205. @classmethod
  206. def child_classes(cls):
  207. return copy.copy(cls._child_classes)
  208. ##@brief Return the parent class that is the "source" of uid
  209. #
  210. #The method goal is to return the parent class that defines UID.
  211. #@return a LeObject child class or false if no UID defined
  212. @classmethod
  213. def uid_source(cls):
  214. if cls._uid is None or len(cls._uid) == 0:
  215. return False
  216. hierarch = cls.hierarch()
  217. prev = hierarch[0]
  218. uid_handlers = set( cls._fields[name] for name in cls._uid )
  219. for pcls in cls.hierarch()[1:]:
  220. puid_handlers = set(cls._fields[name] for name in pcls._uid)
  221. if set(pcls._uid) != set(prev._uid) \
  222. or puid_handlers != uid_handlers:
  223. break
  224. prev = pcls
  225. return prev
  226. ##@brief Initialise both datasources (ro and rw)
  227. #
  228. #This method is used once at dyncode load to replace the datasource string
  229. #by a datasource instance to avoid doing this operation for each query
  230. #@see LeObject::_init_datasource()
  231. @classmethod
  232. def _init_datasources(cls):
  233. if isinstance(cls._datasource_name, str):
  234. rw_ds = ro_ds = cls._datasource_name
  235. else:
  236. ro_ds, rw_ds = cls._datasource_name
  237. #Read only datasource initialisation
  238. cls._ro_datasource = DatasourcePlugin.init_datasource(ro_ds, True)
  239. if cls._ro_datasource is None:
  240. log_msg = "No read only datasource set for LeObject %s"
  241. log_msg %= cls.__name__
  242. logger.debug(log_msg)
  243. else:
  244. log_msg = "Read only datasource '%s' initialized for LeObject %s"
  245. log_msg %= (ro_ds, cls.__name__)
  246. logger.debug(log_msg)
  247. #Read write datasource initialisation
  248. cls._rw_datasource = DatasourcePlugin.init_datasource(rw_ds, False)
  249. if cls._ro_datasource is None:
  250. log_msg = "No read/write datasource set for LeObject %s"
  251. log_msg %= cls.__name__
  252. logger.debug(log_msg)
  253. else:
  254. log_msg = "Read/write datasource '%s' initialized for LeObject %s"
  255. log_msg %= (ro_ds, cls.__name__)
  256. logger.debug(log_msg)
  257. ##@brief Return the uid of the current LeObject instance
  258. #@return the uid value
  259. #@warning Broke multiple uid capabilities
  260. def uid(self):
  261. return self.data(self._uid[0])
  262. ##@brief Read only access to all datas
  263. # @note for fancy data accessor use @ref LeObject.g attribute @ref LeObjectValues instance
  264. # @param name str : field name
  265. # @return the Value
  266. # @throw RuntimeError if the field is not initialized yet
  267. # @throw NameError if name is not an existing field name
  268. def data(self, field_name):
  269. if field_name not in self._fields.keys():
  270. raise NameError("No such field in %s : %s" % (self.__class__.__name__, field_name))
  271. if not self.initialized and field_name not in self.__initialized:
  272. raise RuntimeError("The field %s is not initialized yet (and have no value)" % field_name)
  273. return self.__datas[field_name]
  274. ##@brief Read only access to all datas
  275. #@return a dict representing datas of current instance
  276. def datas(self, internal = False):
  277. return {fname:self.data(fname) for fname in self.fieldnames(internal)}
  278. ##@brief Datas setter
  279. # @note for fancy data accessor use @ref LeObject.g attribute @ref LeObjectValues instance
  280. # @param fname str : field name
  281. # @param fval * : field value
  282. # @return the value that is really set
  283. # @throw NameError if fname is not valid
  284. # @throw AttributeError if the field is not writtable
  285. def set_data(self, fname, fval):
  286. if fname not in self.fieldnames(include_ro = False):
  287. if fname not in self._fields.keys():
  288. raise NameError("No such field in %s : %s" % (self.__class__.__name__, fname))
  289. else:
  290. raise AttributeError("The field %s is read only" % fname)
  291. self.__datas[fname] = fval
  292. if not self.initialized and fname not in self.__initialized:
  293. # Add field to initialized fields list
  294. self.__initialized.append(fname)
  295. self.__set_initialized()
  296. if self.initialized:
  297. # Running full value check
  298. ret = self.__check_modified_values()
  299. if ret is None:
  300. return self.__datas[fname]
  301. else:
  302. raise LeApiErrors("Data check error", ret)
  303. else:
  304. # Doing value check on modified field
  305. # We skip full validation here because the LeObject is not fully initialized yet
  306. val, err = self._fields[fname].check_data_value(fval)
  307. if isinstance(err, Exception):
  308. #Revert change to be in valid state
  309. del(self.__datas[fname])
  310. del(self.__initialized[-1])
  311. raise LeApiErrors("Data check error", {fname:err})
  312. else:
  313. self.__datas[fname] = val
  314. ##@brief Update the __initialized attribute according to LeObject internal state
  315. #
  316. # Check the list of initialized fields and set __initialized to True if all fields initialized
  317. def __set_initialized(self):
  318. if isinstance(self.__initialized, list):
  319. expected_fields = self.fieldnames(include_ro = False) + self._uid
  320. if set(expected_fields) == set(self.__initialized):
  321. self.__is_initialized = True
  322. ##@brief Designed to be called when datas are modified
  323. #
  324. # Make different checks on the LeObject given it's state (fully initialized or not)
  325. # @return None if checks succeded else return an exception list
  326. def __check_modified_values(self):
  327. err_list = dict()
  328. if self.__initialized is True:
  329. # Data value check
  330. for fname in self.fieldnames(include_ro = False):
  331. val, err = self._fields[fname].check_data_value(self.__datas[fname])
  332. if err is not None:
  333. err_list[fname] = err
  334. else:
  335. self.__datas[fname] = val
  336. # Data construction
  337. if len(err_list) == 0:
  338. for fname in self.fieldnames(include_ro = True):
  339. try:
  340. field = self._fields[fname]
  341. self.__datas[fname] = field.construct_data( self,
  342. fname,
  343. self.__datas,
  344. self.__datas[fname]
  345. )
  346. except Exception as exp:
  347. err_list[fname] = exp
  348. # Datas consistency check
  349. if len(err_list) == 0:
  350. for fname in self.fieldnames(include_ro = True):
  351. field = self._fields[fname]
  352. ret = field.check_data_consistency(self, fname, self.__datas)
  353. if isinstance(ret, Exception):
  354. err_list[fname] = ret
  355. else:
  356. # Data value check for initialized datas
  357. for fname in self.__initialized:
  358. val, err = self._fields[fname].check_data_value(self.__datas[fname])
  359. if err is not None:
  360. err_list[fname] = err
  361. else:
  362. self.__datas[fname] = val
  363. return err_list if len(err_list) > 0 else None
  364. #--------------------#
  365. # Other methods #
  366. #--------------------#
  367. ##@brief Temporary method to set private fields attribute at dynamic code generation
  368. #
  369. # This method is used in the generated dynamic code to set the _fields attribute
  370. # at the end of the dyncode parse
  371. # @warning This method is deleted once the dynamic code loaded
  372. # @param field_list list : list of EmField instance
  373. # @param cls
  374. @classmethod
  375. def _set__fields(cls, field_list):
  376. cls._fields = field_list
  377. ## @brief Check that datas are valid for this type
  378. # @param datas dict : key == field name value are field values
  379. # @param complete bool : if True expect that datas provide values for all non internal fields
  380. # @param allow_internal bool : if True don't raise an error if a field is internal
  381. # @param cls
  382. # @return Checked datas
  383. # @throw LeApiDataCheckError if errors reported during check
  384. @classmethod
  385. def check_datas_value(cls, datas, complete = False, allow_internal = True):
  386. err_l = dict() #Error storing
  387. correct = set() #valid fields name
  388. mandatory = set() #mandatory fields name
  389. for fname, datahandler in cls._fields.items():
  390. if allow_internal or not datahandler.is_internal():
  391. correct.add(fname)
  392. if complete and not hasattr(datahandler, 'default'):
  393. mandatory.add(fname)
  394. provided = set(datas.keys())
  395. # searching for unknow fields
  396. for u_f in provided - correct:
  397. #Here we can check if the field is invalid or rejected because
  398. # it is internel
  399. err_l[u_f] = AttributeError("Unknown or unauthorized field '%s'" % u_f)
  400. # searching for missing mandatory fieldsa
  401. for missing in mandatory - provided:
  402. err_l[missing] = AttributeError("The data for field '%s' is missing" % missing)
  403. #Checks datas
  404. checked_datas = dict()
  405. for name, value in [ (name, value) for name, value in datas.items() if name in correct ]:
  406. dh = cls._fields[name]
  407. res = dh.check_data_value(value)
  408. checked_datas[name], err = res
  409. if err:
  410. err_l[name] = err
  411. if len(err_l) > 0:
  412. raise LeApiDataCheckErrors("Error while checking datas", err_l)
  413. return checked_datas
  414. ##@brief Check and prepare datas
  415. #
  416. # @warning when complete = False we are not able to make construct_datas() and _check_data_consistency()
  417. #
  418. # @param datas dict : {fieldname : fieldvalue, ...}
  419. # @param complete bool : If True you MUST give all the datas
  420. # @param allow_internal : Wether or not interal fields are expected in datas
  421. # @param cls
  422. # @return Datas ready for use
  423. # @todo: complete is very unsafe, find a way to get rid of it
  424. @classmethod
  425. def prepare_datas(cls, datas, complete=False, allow_internal=True):
  426. if not complete:
  427. warnings.warn("\nActual implementation can make broken datas \
  428. construction and consitency when datas are not complete\n")
  429. ret_datas = cls.check_datas_value(datas, complete, allow_internal)
  430. if isinstance(ret_datas, Exception):
  431. raise ret_datas
  432. if complete:
  433. ret_datas = cls._construct_datas(ret_datas)
  434. cls._check_datas_consistency(ret_datas)
  435. return ret_datas
  436. ## @brief Construct datas values
  437. #
  438. # @param cls
  439. # @param datas dict : Datas that have been returned by LeCrud.check_datas_value() methods
  440. # @return A new dict of datas
  441. # @todo IMPLEMENTATION
  442. @classmethod
  443. def _construct_datas(cls, datas):
  444. constructor = DatasConstructor(cls, datas, cls._fields)
  445. ret = {
  446. fname:constructor[fname]
  447. for fname, ftype in cls._fields.items()
  448. if not ftype.is_internal() or ftype.internal != 'autosql'
  449. }
  450. return ret
  451. ## @brief Check datas consistency
  452. # @warning assert that datas is complete
  453. # @param cls
  454. # @param datas dict : Datas that have been returned by LeCrud._construct_datas() method
  455. # @throw LeApiDataCheckError if fails
  456. @classmethod
  457. def _check_datas_consistency(cls, datas):
  458. err_l = []
  459. err_l = dict()
  460. for fname, dh in cls._fields.items():
  461. ret = dh.check_data_consistency(cls, fname, datas)
  462. if isinstance(ret, Exception):
  463. err_l[fname] = ret
  464. if len(err_l) > 0:
  465. raise LeApiDataCheckError("Datas consistency checks fails", err_l)
  466. ## @brief Check datas consistency
  467. # @warning assert that datas is complete
  468. # @param cls
  469. # @param datas dict : Datas that have been returned by LeCrud.prepare_datas() method
  470. @classmethod
  471. def make_consistency(cls, datas, type_query = 'insert'):
  472. for fname, dh in cls._fields.items():
  473. ret = dh.make_consistency(fname, datas, type_query)
  474. ## @brief Add a new instance of LeObject
  475. # @return a new uid en case of success, False otherwise
  476. @classmethod
  477. def insert(cls, datas):
  478. query = LeInsertQuery(cls)
  479. return query.execute(datas)
  480. ## @brief Update an instance of LeObject
  481. #
  482. #@param datas : list of new datas
  483. def update(self, datas = None):
  484. datas = self.datas(internal=False) if datas is None else datas
  485. uids = self._uid
  486. query_filter = list()
  487. for uid in uids:
  488. query_filter.append((uid, '=', self.data(uid)))
  489. try:
  490. query = LeUpdateQuery(self.__class__, query_filter)
  491. except Exception as err:
  492. raise err
  493. try:
  494. result = query.execute(datas)
  495. except Exception as err:
  496. raise err
  497. return result
  498. ## @brief Delete an instance of LeObject
  499. #
  500. #@return 1 if the objet has been deleted
  501. def delete(self):
  502. uids = self._uid
  503. query_filter = list()
  504. for uid in uids:
  505. query_filter.append((uid, '=', self.data(uid)))
  506. query = LeDeleteQuery(self.__class__, query_filter)
  507. result = query.execute()
  508. return result
  509. ## @brief Delete instances of LeObject
  510. #@param uids a list: lists of (fieldname, fieldvalue), with fieldname in cls._uids
  511. #@returns the
  512. @classmethod
  513. def delete_bundle(cls, query_filters):
  514. deleted = 0
  515. try:
  516. query = LeDeleteQuery(cls, query_filters)
  517. except Exception as err:
  518. raise err
  519. try:
  520. result = query.execute()
  521. except Exception as err:
  522. raise err
  523. if not result is None:
  524. deleted += result
  525. return deleted
  526. ## @brief Get instances of LeObject
  527. #
  528. #@param target_class LeObject : class of object the query is about
  529. #@param query_filters dict : (filters, relational filters), with filters is a list of tuples : (FIELD, OPERATOR, VALUE) )
  530. #@param field_list list|None : list of string representing fields see
  531. #@ref leobject_filters
  532. #@param order list : A list of field names or tuple (FIELDNAME,[ASC | DESC])
  533. #@param group list : A list of field names or tuple (FIELDNAME,[ASC | DESC])
  534. #@param limit int : The maximum number of returned results
  535. #@param offset int : offset
  536. #@param Inst
  537. #@return a list of items (lists of (fieldname, fieldvalue))
  538. @classmethod
  539. def get(cls, query_filters, field_list=None, order=None, group=None, limit=None, offset=0):
  540. if field_list is not None:
  541. for uid in [ uidname
  542. for uidname in cls.uid_fieldname()
  543. if uidname not in field_list ]:
  544. field_list.append(uid)
  545. if CLASS_ID_FIELDNAME not in field_list:
  546. field_list.append(CLASS_ID_FIELDNAME)
  547. try:
  548. query = LeGetQuery(
  549. cls, query_filters = query_filters, field_list = field_list,
  550. order = order, group = group, limit = limit, offset = offset)
  551. except ValueError as err:
  552. raise err
  553. try:
  554. result = query.execute()
  555. except Exception as err:
  556. raise err
  557. objects = list()
  558. for res in result:
  559. res_cls = cls.name2class(res[CLASS_ID_FIELDNAME])
  560. inst = res_cls.__new__(res_cls,**res)
  561. objects.append(inst)
  562. return objects
  563. ##@brief Retrieve an object given an UID
  564. #@todo broken multiple UID
  565. @classmethod
  566. def get_from_uid(cls, uid):
  567. if cls.uid_fieldname() is None:
  568. raise LodelFatalError(
  569. "No uid defined for class %s" % cls.__name__)
  570. uidname = cls.uid_fieldname()[0] #Brokes composed UID
  571. res = cls.get([(uidname,'=', uid)])
  572. #dedoublonnage vu que query ou la datasource est bugué
  573. if len(res) > 1:
  574. res_cp = res
  575. res = []
  576. while len(res_cp) > 0:
  577. cur_res = res_cp.pop()
  578. if cur_res.uid() in [ r.uid() for r in res_cp]:
  579. logger.error("DOUBLON detected in query results !!!")
  580. else:
  581. res.append(cur_res)
  582. if len(res) > 1:
  583. raise LodelFatalError("Get from uid returned more than one \
  584. object ! For class %s with uid value = %s" % (cls, uid))
  585. elif len(res) == 0:
  586. return None
  587. return res[0]