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

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