Nenhuma descrição
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

leobject.py 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  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. if cls._ro_datasource is None:
  217. log_msg = "No read only datasource set for LeObject %s"
  218. log_msg %= cls.__name__
  219. logger.debug(log_msg)
  220. else:
  221. log_msg = "Read only datasource '%s' initialized for LeObject %s"
  222. log_msg %= (ro_ds, cls.__name__)
  223. logger.debug(log_msg)
  224. #Read write datasource initialisation
  225. cls._rw_datasource = cls._init_datasource(rw_ds, False)
  226. if cls._ro_datasource is None:
  227. log_msg = "No read/write datasource set for LeObject %s"
  228. log_msg %= cls.__name__
  229. logger.debug(log_msg)
  230. else:
  231. log_msg = "Read/write datasource '%s' initialized for LeObject %s"
  232. log_msg %= (ro_ds, cls.__name__)
  233. logger.debug(log_msg)
  234. ##@brief Replace the _datasource attribute value by a datasource instance
  235. #
  236. #This method is used once at dyncode load to replace the datasource string
  237. #by a datasource instance to avoid doing this operation for each query
  238. #@param ds_name str : The name of the datasource to instanciate
  239. #@param ro bool : if true initialise the _ro_datasource attribute else
  240. #initialise _rw_datasource attribute
  241. #@throw SettingsError if an error occurs
  242. @classmethod
  243. def _init_datasource(cls, ds_name, ro):
  244. expt_msg = "In LeAPI class '%s' " % cls.__name__
  245. if ds_name not in Settings.datasources._fields:
  246. #Checking that datasource exists
  247. expt_msg += "Unknown or unconfigured datasource %s for class %s"
  248. expt_msg %= (ds_name, cls.__name__)
  249. raise SettingsError(expt_msg)
  250. try:
  251. #fetching plugin name
  252. ds_plugin_name, ds_identifier = cls._get_ds_plugin_name(ds_name, ro)
  253. except NameError:
  254. expt_msg += "Datasource %s is missconfigured, missing identifier."
  255. expt_msg %= ds_name
  256. raise SettingsError(expt_msg)
  257. except RuntimeError:
  258. expt_msg += "Error in datasource %s configuration. Trying to use \
  259. a read only as a read&write datasource"
  260. expt_msg %= ds_name
  261. raise SettingsError(expt_msg)
  262. except ValueError as e:
  263. expt_msg += str(e)
  264. raise SettingsError(expt_msg)
  265. try:
  266. ds_conf = cls._get_ds_connection_conf(ds_identifier, ds_plugin_name)
  267. except NameError as e:
  268. expt_msg += str(e)
  269. raise SettingsError(expt_msg)
  270. #Checks that the datasource plugin exists
  271. ds_plugin_module = Plugin.get(ds_plugin_name).loader_module()
  272. try:
  273. datasource_class = getattr(ds_plugin_module, "Datasource")
  274. except AttributeError as e:
  275. expt_msg += "The datasource plugin %s seems to be invalid. Error \
  276. raised when trying to import Datasource"
  277. expt_msg %= ds_identifier
  278. raise SettingsError(expt_msg)
  279. return datasource_class(**ds_conf)
  280. ##@brief Try to fetch a datasource configuration
  281. #@param ds_identifier str : datasource name
  282. #@param ds_plugin_name : datasource plugin name
  283. #@return a dict containing datasource initialisation options
  284. #@throw NameError if a datasource plugin or instance cannot be found
  285. @staticmethod
  286. def _get_ds_connection_conf(ds_identifier,ds_plugin_name):
  287. if ds_plugin_name not in Settings.datasource._fields:
  288. msg = "Unknown or unconfigured datasource plugin %s"
  289. msg %= ds_plugin
  290. raise NameError(msg)
  291. ds_conf = getattr(Settings.datasource, ds_plugin_name)
  292. if ds_identifier not in ds_conf._fields:
  293. msg = "Unknown or unconfigured datasource instance %s"
  294. msg %= ds_identifier
  295. raise NameError(msg)
  296. ds_conf = getattr(ds_conf, ds_identifier)
  297. return {k: getattr(ds_conf,k) for k in ds_conf._fields }
  298. ##@brief fetch datasource plugin name
  299. #@param ds_name str : datasource name
  300. #@param ro bool : if true consider the datasource as read only
  301. #@return a tuple(DATASOURCE_PLUGIN_NAME, DATASOURCE_CONNECTION_NAME)
  302. #@throw NameError if datasource identifier not found
  303. #@throw RuntimeError if datasource is read_only but ro flag was false
  304. @staticmethod
  305. def _get_ds_plugin_name(ds_name, ro):
  306. datasource_orig_name = ds_name
  307. # fetching connection identifier given datasource name
  308. ds_identifier = getattr(Settings.datasources, ds_name)
  309. read_only = getattr(ds_identifier, 'read_only')
  310. try:
  311. ds_identifier = getattr(ds_identifier, 'identifier')
  312. except NameError as e:
  313. raise e
  314. if read_only and not ro:
  315. raise RuntimeError()
  316. res = ds_identifier.split('.')
  317. if len(res) != 2:
  318. raise ValueError("expected value for identifier is like \
  319. DS_PLUGIN_NAME.DS_INSTANCE_NAME. But got %s" % ds_identifier)
  320. return res
  321. ##@brief Return the uid of the current LeObject instance
  322. #@return the uid value
  323. #@warning Broke multiple uid capabilities
  324. def uid(self):
  325. return self.data(self._uid[0])
  326. ##@brief Read only access to all datas
  327. # @note for fancy data accessor use @ref LeObject.g attribute @ref LeObjectValues instance
  328. # @param name str : field name
  329. # @return the Value
  330. # @throw RuntimeError if the field is not initialized yet
  331. # @throw NameError if name is not an existing field name
  332. def data(self, field_name):
  333. if field_name not in self._fields.keys():
  334. raise NameError("No such field in %s : %s" % (self.__class__.__name__, field_name))
  335. if not self.initialized and field_name not in self.__initialized:
  336. raise RuntimeError("The field %s is not initialized yet (and have no value)" % field_name)
  337. return self.__datas[field_name]
  338. ##@brief Read only access to all datas
  339. #@return a dict representing datas of current instance
  340. def datas(self, internal = False):
  341. return {fname:self.data(fname) for fname in self.fieldnames(internal)}
  342. ##@brief Datas setter
  343. # @note for fancy data accessor use @ref LeObject.g attribute @ref LeObjectValues instance
  344. # @param fname str : field name
  345. # @param fval * : field value
  346. # @return the value that is really set
  347. # @throw NameError if fname is not valid
  348. # @throw AttributeError if the field is not writtable
  349. def set_data(self, fname, fval):
  350. if fname not in self.fieldnames(include_ro = False):
  351. if fname not in self._fields.keys():
  352. raise NameError("No such field in %s : %s" % (self.__class__.__name__, fname))
  353. else:
  354. raise AttributeError("The field %s is read only" % fname)
  355. self.__datas[fname] = fval
  356. if not self.initialized and fname not in self.__initialized:
  357. # Add field to initialized fields list
  358. self.__initialized.append(fname)
  359. self.__set_initialized()
  360. if self.initialized:
  361. # Running full value check
  362. ret = self.__check_modified_values()
  363. if ret is None:
  364. return self.__datas[fname]
  365. else:
  366. raise LeApiErrors("Data check error", ret)
  367. else:
  368. # Doing value check on modified field
  369. # We skip full validation here because the LeObject is not fully initialized yet
  370. val, err = self._fields[fname].check_data_value(fval)
  371. if isinstance(err, Exception):
  372. #Revert change to be in valid state
  373. del(self.__datas[fname])
  374. del(self.__initialized[-1])
  375. raise LeApiErrors("Data check error", {fname:err})
  376. else:
  377. self.__datas[fname] = val
  378. ##@brief Update the __initialized attribute according to LeObject internal state
  379. #
  380. # Check the list of initialized fields and set __initialized to True if all fields initialized
  381. def __set_initialized(self):
  382. if isinstance(self.__initialized, list):
  383. expected_fields = self.fieldnames(include_ro = False) + self._uid
  384. if set(expected_fields) == set(self.__initialized):
  385. self.__is_initialized = True
  386. ##@brief Designed to be called when datas are modified
  387. #
  388. # Make different checks on the LeObject given it's state (fully initialized or not)
  389. # @return None if checks succeded else return an exception list
  390. def __check_modified_values(self):
  391. err_list = dict()
  392. if self.__initialized is True:
  393. # Data value check
  394. for fname in self.fieldnames(include_ro = False):
  395. val, err = self._fields[fname].check_data_value(self.__datas[fname])
  396. if err is not None:
  397. err_list[fname] = err
  398. else:
  399. self.__datas[fname] = val
  400. # Data construction
  401. if len(err_list) == 0:
  402. for fname in self.fieldnames(include_ro = True):
  403. try:
  404. field = self._fields[fname]
  405. self.__datas[fname] = fields.construct_data( self,
  406. fname,
  407. self.__datas,
  408. self.__datas[fname]
  409. )
  410. except Exception as e:
  411. err_list[fname] = e
  412. # Datas consistency check
  413. if len(err_list) == 0:
  414. for fname in self.fieldnames(include_ro = True):
  415. field = self._fields[fname]
  416. ret = field.check_data_consistency(self, fname, self.__datas)
  417. if isinstance(ret, Exception):
  418. err_list[fname] = ret
  419. else:
  420. # Data value check for initialized datas
  421. for fname in self.__initialized:
  422. val, err = self._fields[fname].check_data_value(self.__datas[fname])
  423. if err is not None:
  424. err_list[fname] = err
  425. else:
  426. self.__datas[fname] = val
  427. return err_list if len(err_list) > 0 else None
  428. #--------------------#
  429. # Other methods #
  430. #--------------------#
  431. ##@brief Temporary method to set private fields attribute at dynamic code generation
  432. #
  433. # This method is used in the generated dynamic code to set the _fields attribute
  434. # at the end of the dyncode parse
  435. # @warning This method is deleted once the dynamic code loaded
  436. # @param field_list list : list of EmField instance
  437. # @param cls
  438. @classmethod
  439. def _set__fields(cls, field_list):
  440. cls._fields = field_list
  441. ## @brief Check that datas are valid for this type
  442. # @param datas dict : key == field name value are field values
  443. # @param complete bool : if True expect that datas provide values for all non internal fields
  444. # @param allow_internal bool : if True don't raise an error if a field is internal
  445. # @param cls
  446. # @return Checked datas
  447. # @throw LeApiDataCheckError if errors reported during check
  448. @classmethod
  449. def check_datas_value(cls, datas, complete = False, allow_internal = True):
  450. err_l = dict() #Error storing
  451. correct = set() #valid fields name
  452. mandatory = set() #mandatory fields name
  453. for fname, datahandler in cls._fields.items():
  454. if allow_internal or not datahandler.is_internal():
  455. correct.add(fname)
  456. if complete and not hasattr(datahandler, 'default'):
  457. mandatory.add(fname)
  458. provided = set(datas.keys())
  459. # searching for unknow fields
  460. for u_f in provided - correct:
  461. #Here we can check if the field is invalid or rejected because
  462. # it is internel
  463. err_l[u_f] = AttributeError("Unknown or unauthorized field '%s'" % u_f)
  464. # searching for missing mandatory fieldsa
  465. for missing in mandatory - provided:
  466. err_l[missing] = AttributeError("The data for field '%s' is missing" % missing)
  467. #Checks datas
  468. checked_datas = dict()
  469. for name, value in [ (name, value) for name, value in datas.items() if name in correct ]:
  470. dh = cls._fields[name]
  471. res = dh.check_data_value(value)
  472. checked_datas[name], err = res
  473. if err:
  474. err_l[name] = err
  475. if len(err_l) > 0:
  476. raise LeApiDataCheckErrors("Error while checking datas", err_l)
  477. return checked_datas
  478. ##@brief Check and prepare datas
  479. #
  480. # @warning when complete = False we are not able to make construct_datas() and _check_data_consistency()
  481. #
  482. # @param datas dict : {fieldname : fieldvalue, ...}
  483. # @param complete bool : If True you MUST give all the datas
  484. # @param allow_internal : Wether or not interal fields are expected in datas
  485. # @param cls
  486. # @return Datas ready for use
  487. # @todo: complete is very unsafe, find a way to get rid of it
  488. @classmethod
  489. def prepare_datas(cls, datas, complete=False, allow_internal=True):
  490. if not complete:
  491. warnings.warn("\nActual implementation can make broken datas \
  492. construction and consitency when datas are not complete\n")
  493. ret_datas = cls.check_datas_value(datas, complete, allow_internal)
  494. if isinstance(ret_datas, Exception):
  495. raise ret_datas
  496. if complete:
  497. ret_datas = cls._construct_datas(ret_datas)
  498. cls._check_datas_consistency(ret_datas)
  499. return ret_datas
  500. ## @brief Construct datas values
  501. #
  502. # @param cls
  503. # @param datas dict : Datas that have been returned by LeCrud.check_datas_value() methods
  504. # @return A new dict of datas
  505. # @todo IMPLEMENTATION
  506. @classmethod
  507. def _construct_datas(cls, datas):
  508. constructor = DatasConstructor(cls, datas, cls._fields)
  509. ret = {
  510. fname:constructor[fname]
  511. for fname, ftype in cls._fields.items()
  512. if not ftype.is_internal() or ftype.internal != 'autosql'
  513. }
  514. return ret
  515. ## @brief Check datas consistency
  516. # @warning assert that datas is complete
  517. # @param cls
  518. # @param datas dict : Datas that have been returned by LeCrud._construct_datas() method
  519. # @throw LeApiDataCheckError if fails
  520. @classmethod
  521. def _check_datas_consistency(cls, datas):
  522. err_l = []
  523. err_l = dict()
  524. for fname, dh in cls._fields.items():
  525. ret = dh.check_data_consistency(cls, fname, datas)
  526. if isinstance(ret, Exception):
  527. err_l[fname] = ret
  528. if len(err_l) > 0:
  529. raise LeApiDataCheckError("Datas consistency checks fails", err_l)
  530. ## @brief Add a new instance of LeObject
  531. # @return a new uid en case of success, False otherwise
  532. @classmethod
  533. def insert(cls, datas):
  534. query = LeInsertQuery(cls)
  535. return query.execute(datas)
  536. ## @brief Update an instance of LeObject
  537. #
  538. #@param datas : list of new datas
  539. def update(self, datas = None):
  540. datas = self.datas(internal=False) if datas is None else datas
  541. uids = self._uid
  542. query_filter = list()
  543. for uid in uids:
  544. query_filter.append((uid, '=', self.data(uid)))
  545. try:
  546. query = LeUpdateQuery(self.__class__, query_filter)
  547. except Exception as err:
  548. raise err
  549. try:
  550. result = query.execute(datas)
  551. except Exception as err:
  552. raise err
  553. return result
  554. ## @brief Delete an instance of LeObject
  555. #
  556. #@return 1 if the objet has been deleted
  557. def delete(self):
  558. uids = self._uid
  559. query_filter = list()
  560. for uid in uids:
  561. query_filter.append((uid, '=', self.data(uid)))
  562. query = LeDeleteQuery(self.__class__, query_filter)
  563. result = query.execute()
  564. return result
  565. ## @brief Delete instances of LeObject
  566. #@param uids a list: lists of (fieldname, fieldvalue), with fieldname in cls._uids
  567. #@returns the
  568. @classmethod
  569. def delete_bundle(cls, query_filters):
  570. deleted = 0
  571. try:
  572. query = LeDeleteQuery(cls, query_filters)
  573. except Exception as err:
  574. raise err
  575. try:
  576. result = query.execute()
  577. except Exception as err:
  578. raise err
  579. if not result is None:
  580. deleted += result
  581. return deleted
  582. ## @brief Get instances of LeObject
  583. #
  584. #@param target_class LeObject : class of object the query is about
  585. #@param query_filters dict : (filters, relational filters), with filters is a list of tuples : (FIELD, OPERATOR, VALUE) )
  586. #@param field_list list|None : list of string representing fields see
  587. #@ref leobject_filters
  588. #@param order list : A list of field names or tuple (FIELDNAME,[ASC | DESC])
  589. #@param group list : A list of field names or tuple (FIELDNAME,[ASC | DESC])
  590. #@param limit int : The maximum number of returned results
  591. #@param offset int : offset
  592. #@param Inst
  593. #@return a list of items (lists of (fieldname, fieldvalue))
  594. @classmethod
  595. def get(cls, query_filters, field_list=None, order=None, group=None, limit=None, offset=0):
  596. if field_list is None:
  597. field_list = cls.fieldnames(True)
  598. else:
  599. for uid in [ uidname
  600. for uidname in cls.uid_fieldname()
  601. if uidname not in field_list ]:
  602. field_list.append(uid)
  603. if CLASS_ID_FIELDNAME not in field_list:
  604. field_list.append(CLASS_ID_FIELDNAME)
  605. try:
  606. query = LeGetQuery(
  607. cls, query_filters = query_filters, field_list = field_list,
  608. order = order, group = group, limit = limit, offset = offset)
  609. except ValueError as err:
  610. raise err
  611. try:
  612. result = query.execute()
  613. except Exception as err:
  614. raise err
  615. objects = list()
  616. for res in result:
  617. res_cls = cls.name2class(res[CLASS_ID_FIELDNAME])
  618. inst = res_cls.__new__(res_cls,**res)
  619. objects.append(inst)
  620. return objects