Bez popisu
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 27KB

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