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.

lecrud.py 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. #-*- coding: utf-8 -*-
  2. ## @package leapi.lecrud
  3. # @brief This package contains the abstract class representing Lodel Editorial components
  4. #
  5. import copy
  6. import warnings
  7. import importlib
  8. import re
  9. from EditorialModel.fieldtypes.generic import DatasConstructor
  10. REL_SUP = 0
  11. REL_SUB = 1
  12. class LeApiErrors(Exception):
  13. ## @brief Instanciate a new exceptions handling multiple exceptions
  14. # @param exptexptions dict : A list of data check Exception with concerned field (or stuff) as key
  15. def __init__(self, msg = "Unknow error", exceptions = None):
  16. self._msg = msg
  17. self._exceptions = dict() if exceptions is None else exceptions
  18. def __repr__(self):
  19. return self.__str__()
  20. def __str__(self):
  21. msg = self._msg
  22. for obj, expt in self._exceptions.items():
  23. msg += "\n\t{expt_obj} : ({expt_name}) {expt_msg}; ".format(
  24. expt_obj = obj,
  25. expt_name=expt.__class__.__name__,
  26. expt_msg=str(expt)
  27. )
  28. return msg
  29. ## @brief When an error concern a query
  30. class LeApiQueryError(LeApiErrors): pass
  31. ## @brief When an error concerns a datas
  32. class LeApiDataCheckError(LeApiErrors): pass
  33. ## @brief Main class to handler lodel editorial components (relations and objects)
  34. class _LeCrud(object):
  35. ## @brief The datasource
  36. _datasource = None
  37. ## @brief abstract property to store the fieldtype representing the component identifier
  38. _uid_fieldtype = None #Will be a dict fieldname => fieldtype
  39. ## @brief will store all the fieldtypes (child classes handle it)
  40. _fieldtypes_all = None
  41. ## @brief Stores a regular expression to parse query filters strings
  42. _query_re = None
  43. ## @brief Stores Query filters operators
  44. _query_operators = ['=', '<=', '>=', '!=', '<', '>', ' in ', ' not in ', ' like ', ' not like ']
  45. ## @brief Asbtract constructor for every child classes
  46. # @param uid int : lodel_id if LeObject, id_relation if its a LeRelation
  47. # @param **kwargs : datas !
  48. # @raise NotImplementedError if trying to instanciate a class that cannot be instanciated
  49. def __init__(self, uid, **kwargs):
  50. if len(kwargs) > 0:
  51. if not self.implements_leobject() and not self.implements_lerelation():
  52. raise NotImplementedError("Abstract class !")
  53. # Try to get the name of the uid field (lodel_id for objects, id_relation for relations)
  54. try:
  55. uid_name = self.uidname()
  56. except NotImplementedError: #Should never append
  57. raise NotImplementedError("Abstract class ! You can only do partial instanciation on classes that have an uid name ! (LeObject & childs + LeRelation & childs)")
  58. # Checking uid value
  59. uid, err = self._uid_fieldtype[uid_name].check_data_value(uid)
  60. if isinstance(err, Exception):
  61. raise err
  62. setattr(self, uid_name, uid)
  63. if uid_name in kwargs:
  64. warnings.warn("When instanciating the uid was given in the uid argument but was also provided in kwargs. Droping the kwargs uid")
  65. del(kwargs[uid_name])
  66. # Populating the object with given datas
  67. errors = dict()
  68. for name, value in kwargs.items():
  69. if name not in self.fieldlist():
  70. errors[name] = AttributeError("No such field '%s' for %s"%(name, self.__class__.__name__))
  71. else:
  72. cvalue, err = self.fieldtypes()[name].check_data_value(value)
  73. if isinstance(err, Exception):
  74. errors[name] = err
  75. else:
  76. setattr(self, name, cvalue)
  77. if len(errors) > 0:
  78. raise LeApiDataCheckError("Invalid arguments given to constructor", errors)
  79. ## @brief A flag to indicate if the object was fully intanciated or not
  80. self._instanciation_complete = len(kwargs) + 1 == len(self.fieldlist())
  81. ## @brief Convert an EmType or EmClass name in a python class name
  82. # @param name str : The name
  83. # @return name.title()
  84. @staticmethod
  85. def name2classname(name):
  86. if not isinstance(name, str):
  87. raise AttributeError("Argument name should be a str and not a %s" % type(name))
  88. return name.title()
  89. ## @brief Convert an EmCalss and EmType name in a rel2type class name
  90. # @param name str : The name
  91. # @return name.title()
  92. @staticmethod
  93. def name2rel2type(class_name, type_name, relation_name):
  94. cls_name = "Rel%s%s%s"%(_LeCrud.name2classname(class_name), _LeCrud.name2classname(type_name), relation_name.title())
  95. return cls_name
  96. ## @brief Given a dynamically generated class name return the corresponding python Class
  97. # @param name str : a concrete class name
  98. # @return False if no such component
  99. @classmethod
  100. def name2class(cls, name):
  101. if not isinstance(name, str):
  102. raise ValueError("Expected name argument as a string but got %s instead"%(type(name)))
  103. mod = importlib.import_module(cls.__module__)
  104. try:
  105. return getattr(mod, name)
  106. except AttributeError:
  107. return False
  108. ## @return LeObject class
  109. @classmethod
  110. def leobject(cls):
  111. return cls.name2class('LeObject')
  112. ## @return A dict with key field name and value a fieldtype instance
  113. @classmethod
  114. def fieldtypes(cls):
  115. raise NotImplementedError("Abstract method") #child classes should return their uid fieldtype
  116. ## @return A dict with fieldtypes marked as internal
  117. # @todo check if this method is in use, else delete it
  118. @classmethod
  119. def fieldtypes_internal(self):
  120. return { fname: ft for fname, ft in cls.fieldtypes().items() if hasattr(ft, 'internal') and ft.internal }
  121. ## @return A list of field name
  122. @classmethod
  123. def fieldlist(cls):
  124. return list(cls.fieldtypes().keys())
  125. ## @return The name of the uniq id field
  126. # @todo test for abstract method !!!
  127. @classmethod
  128. def uidname(cls):
  129. raise NotImplementedError("Abstract method uid_name for %s!"%cls.__name__)
  130. ## @return maybe Bool: True if cls implements LeType
  131. # @param cls Class: a Class or instanciated object
  132. @classmethod
  133. def implements_letype(cls):
  134. return hasattr(cls, '_leclass')
  135. ## @return maybe Bool: True if cls implements LeClass
  136. # @param cls Class: a Class or instanciated object
  137. @classmethod
  138. def implements_leclass(cls):
  139. return hasattr(cls, '_class_id')
  140. ## @return maybe Bool: True if cls implements LeObject
  141. # @param cls Class: a Class or instanciated object
  142. @classmethod
  143. def implements_leobject(cls):
  144. return hasattr(cls, '_me_uid')
  145. ## @return maybe Bool: True if cls is a LeType or an instance of LeType
  146. # @param cls Class: a Class or instanciated object
  147. @classmethod
  148. def is_letype(cls):
  149. return cls.implements_letype()
  150. ## @return maybe Bool: True if cls is a LeClass or an instance of LeClass
  151. # @param cls Class: a Class or instanciated object
  152. @classmethod
  153. def is_leclass(cls):
  154. return cls.implements_leclass() and not cls.implements_letype()
  155. ## @return maybe Bool: True if cls is a LeClass or an instance of LeClass
  156. # @param cls Class: a Class or instanciated object
  157. @classmethod
  158. def is_leobject(cls):
  159. return cls.implements_leobject() and not cls.implements_leclass()
  160. ## @return maybe Bool: True if cls implements LeRelation
  161. # @param cls Class: a Class or instanciated object
  162. @classmethod
  163. def implements_lerelation(cls):
  164. return hasattr(cls, '_superior_field_name')
  165. ## @return maybe Bool: True if cls implements LeRel2Type
  166. # @param cls Class: a Class or instanciated object
  167. @classmethod
  168. def implements_lerel2type(cls):
  169. return hasattr(cls, '_rel_attr_fieldtypes')
  170. ## @return maybe Bool: True if cls is a LeHierarch or an instance of LeHierarch
  171. # @param cls Class: a Class or instanciated object
  172. @classmethod
  173. def is_lehierarch(cls):
  174. return cls.implements_lerelation() and not cls.implements_lerel2type()
  175. ## @return maybe Bool: True if cls is a LeRel2Type or an instance of LeRel2Type
  176. # @param cls Class: a Class or instanciated object
  177. @classmethod
  178. def is_lerel2type(cls):
  179. return cls.implements_lerel2type()
  180. def uidget(self):
  181. return getattr(self, self.uidname())
  182. ## @brief Returns object datas
  183. # @param internal bool : If True return all datas including internal fields
  184. # @param lang str | None : if None return datas indexed with field name, else datas are indexed with field name translation
  185. # @return a dict of fieldname : value
  186. def datas(self, internal = True, lang = None):
  187. res = dict()
  188. for fname, ftt in self.fieldtypes().items():
  189. if (internal or (not internal and not ftt.is_internal)) and hasattr(self, fname):
  190. if lang is None:
  191. res[fname] = getattr(self, fname)
  192. else:
  193. res[self.ml_fields_strings[fname][lang]] = getattr(self, fname)
  194. return res
  195. ## @brief Indicates if an instance is complete
  196. # @return a bool
  197. def is_complete(self):
  198. return self._instanciation_complete
  199. ## @brief Populate the LeType wih datas from DB
  200. # @param field_list None|list : List of fieldname to fetch. If None fetch all the missing datas
  201. # @todo Add checks to forbid the use of this method on abtract classes (LeObject, LeClass, LeType, LeRel2Type, LeRelation etc...)
  202. def populate(self, field_list=None):
  203. if not self.is_complete():
  204. if field_list == None:
  205. field_list = [ fname for fname in self.fieldlist() if not hasattr(self, fname) ]
  206. filters = [self._id_filter()]
  207. rel_filters = []
  208. # Getting datas from db
  209. fdatas = self._datasource.select(self.__class__, field_list, filters, rel_filters)
  210. if fdatas is None or len(fdatas) == 0:
  211. raise LeApiQueryError("Error when trying to populate an object. For type %s id : %d"% (self.__class__.__name__, self.lodel_id))
  212. # Setting datas
  213. for fname, fval in fdatas[0].items():
  214. setattr(self, fname, fval)
  215. self._instanciation_complete = True
  216. ## @brief Return the corresponding instance
  217. #
  218. # @note this method is a kind of factory. Allowing to make a partial instance
  219. # of abstract types using only an uid and then fetching an complete instance of
  220. # the correct class
  221. # @return Corresponding populated LeObject
  222. def get_instance(self):
  223. if self.is_complete():
  224. return self
  225. uid_fname = self.uidname()
  226. qfilter = '{uid_fname} = {uid}'.format(uid_fname = uid_fname, uid = getattr(self, uid_fname))
  227. return leobject.get([qfilter])[0]
  228. ## @brief Update a component in DB
  229. # @param datas dict : If None use instance attributes to update de DB
  230. # @return True if success
  231. # @todo better error handling
  232. # @todo for check_data_consistency, datas must be populated to make update safe !
  233. def update(self, datas=None):
  234. if not self.is_complete():
  235. self.populate()
  236. warnings.warn("\nThis object %s is not complete and has been populated. This is very unsafe\n" % self)
  237. datas = self.datas(internal=False) if datas is None else datas
  238. upd_datas = self.prepare_datas(datas, complete = False, allow_internal = False)
  239. filters = [self._id_filter()]
  240. rel_filters = []
  241. ret = self._datasource.update(self.__class__, self.uidget(), **upd_datas)
  242. if ret == 1:
  243. return True
  244. else:
  245. #ERROR HANDLING
  246. return False
  247. ## @brief Delete a component
  248. # @return True if success
  249. # @todo better error handling
  250. def delete(self):
  251. self._datasource.delete(self.__class__, self.uidget())
  252. ## @brief Check that datas are valid for this type
  253. # @param datas dict : key == field name value are field values
  254. # @param complete bool : if True expect that datas provide values for all non internal fields
  255. # @param allow_internal bool : if True don't raise an error if a field is internal
  256. # @return Checked datas
  257. # @throw LeApiDataCheckError if errors reported during check
  258. @classmethod
  259. def check_datas_value(cls, datas, complete = False, allow_internal = True):
  260. err_l = dict() #Stores errors
  261. correct = [] #Valid fields name
  262. mandatory = [] #mandatory fields name
  263. for fname, ftt in cls.fieldtypes().items():
  264. if allow_internal or not ftt.is_internal():
  265. correct.append(fname)
  266. if complete and not hasattr(ftt, 'default'):
  267. mandatory.append(fname)
  268. mandatory = set(mandatory)
  269. correct = set(correct)
  270. provided = set(datas.keys())
  271. #searching unknow fields
  272. unknown = provided - correct
  273. for u_f in unknown:
  274. #here we can check if the field is unknown or rejected because it is internal
  275. err_l[u_f] = AttributeError("Unknown or unauthorized field '%s'"%u_f)
  276. #searching missings fields
  277. missings = mandatory - provided
  278. for miss_field in missings:
  279. err_l[miss_field] = AttributeError("The data for field '%s' is missing"%miss_field)
  280. #Checks datas
  281. checked_datas = dict()
  282. for name, value in [ (name, value) for name, value in datas.items() if name in correct ]:
  283. ft = cls.fieldtypes()
  284. ft = ft[name]
  285. r = ft.check_data_value(value)
  286. checked_datas[name], err = r
  287. #checked_datas[name], err = cls.fieldtypes()[name].check_data_value(value)
  288. if err:
  289. err_l[name] = err
  290. if len(err_l) > 0:
  291. raise LeApiDataCheckError("Error while checking datas", err_l)
  292. return checked_datas
  293. ## @brief Retrieve a collection of lodel editorial components
  294. #
  295. # @param query_filters list : list of string of query filters (or tuple (FIELD, OPERATOR, VALUE) ) see @ref leobject_filters
  296. # @param field_list list|None : list of string representing fields see @ref leobject_filters
  297. # @param order list : A list of field names or tuple (FIELDNAME, [ASC | DESC])
  298. # @param groups list : A list of field names or tuple (FIELDNAME, [ASC | DESC])
  299. # @param limit int : The maximum number of returned results
  300. # @param offset int : offset
  301. # @return A list of lodel editorial components instance
  302. # @todo think about LeObject and LeClass instanciation (partial instanciation, etc)
  303. @classmethod
  304. def get(cls, query_filters, field_list=None, order=None, group=None, limit=None, offset=0, instanciate=True):
  305. if field_list is None or len(field_list) == 0:
  306. #default field_list
  307. field_list = cls.fieldlist()
  308. field_list = cls._prepare_field_list(field_list) #Can raise LeApiDataCheckError
  309. #preparing filters
  310. filters, relational_filters = cls._prepare_filters(query_filters)
  311. #preparing order
  312. if order:
  313. order = cls._prepare_order_fields(order)
  314. if isinstance(order, Exception):
  315. raise order #can be buffered and raised later, but _prepare_filters raise when fails
  316. #preparing groups
  317. if group:
  318. group = cls._prepare_order_fields(group)
  319. if isinstance(group, Exception):
  320. raise group # can also be buffered and raised later
  321. #checking limit and offset values
  322. if not (limit is None):
  323. if limit <= 0:
  324. raise ValueError("Invalid limit given : %d"%limit)
  325. if not (offset is None):
  326. if offset < 0:
  327. raise ValueError("Invalid offset given : %d"%offset)
  328. #Fetching editorial components from datasource
  329. results = cls._datasource.select(
  330. target_cls = cls,
  331. field_list = field_list,
  332. filters = filters,
  333. rel_filters = relational_filters,
  334. order=order,
  335. group=group,
  336. limit=limit,
  337. offset=offset,
  338. instanciate=instanciate
  339. )
  340. return results
  341. ## @brief Insert a new component
  342. # @param datas dict : The value of object we want to insert
  343. # @return A new id if success else False
  344. @classmethod
  345. def insert(cls, datas, classname=None):
  346. callcls = cls if classname is None else cls.name2class(classname)
  347. if not callcls:
  348. raise LeApiErrors("Error when inserting",{'error':ValueError("The class '%s' was not found"%classname)})
  349. if not callcls.implements_letype() and not callcls.implements_lerelation():
  350. raise ValueError("You can only insert relations and LeTypes objects but tying to insert a '%s'"%callcls.__name__)
  351. insert_datas = callcls.prepare_datas(datas, complete = True, allow_internal = False)
  352. return callcls._datasource.insert(callcls, **insert_datas)
  353. ## @brief Check and prepare datas
  354. #
  355. # @warning when complete = False we are not able to make construct_datas() and _check_data_consistency()
  356. #
  357. # @param datas dict : {fieldname : fieldvalue, ...}
  358. # @param complete bool : If True you MUST give all the datas
  359. # @param allow_internal : Wether or not interal fields are expected in datas
  360. # @return Datas ready for use
  361. # @todo: complete is very unsafe, find a way to get rid of it
  362. @classmethod
  363. def prepare_datas(cls, datas, complete=False, allow_internal=True):
  364. if not complete:
  365. warnings.warn("\nActual implementation can make datas construction and consitency unsafe when datas are not complete\n")
  366. ret_datas = cls.check_datas_value(datas, complete, allow_internal)
  367. if isinstance(ret_datas, Exception):
  368. raise ret_datas
  369. if complete:
  370. ret_datas = cls._construct_datas(ret_datas)
  371. cls._check_datas_consistency(ret_datas)
  372. return ret_datas
  373. #-###################-#
  374. # Private methods #
  375. #-###################-#
  376. ## @brief Build a filter to select an object with a specific ID
  377. # @warning assert that the uid is not composed with multiple fieldtypes
  378. # @return A filter of the form tuple(UID, '=', self.UID)
  379. # @todo This method should not be private
  380. def _id_filter(self):
  381. id_name = self.uidname()
  382. return ( id_name, '=', getattr(self, id_name) )
  383. ## @brief Construct datas values
  384. #
  385. # @param datas dict : Datas that have been returned by LeCrud.check_datas_value() methods
  386. # @return A new dict of datas
  387. @classmethod
  388. def _construct_datas(cls, datas):
  389. constructor = DatasConstructor(cls, datas, cls.fieldtypes())
  390. ret = {
  391. fname:constructor[fname]
  392. for fname, ftype in cls.fieldtypes().items()
  393. if not ftype.is_internal() or ftype.internal != 'autosql'
  394. }
  395. return ret
  396. ## @brief Check datas consistency
  397. # @warning assert that datas is complete
  398. #
  399. # @param datas dict : Datas that have been returned by LeCrud._construct_datas() method
  400. # @throw LeApiDataCheckError if fails
  401. @classmethod
  402. def _check_datas_consistency(cls, datas):
  403. err_l = []
  404. err_l = dict()
  405. for fname, ftype in cls.fieldtypes().items():
  406. ret = ftype.check_data_consistency(cls, fname, datas)
  407. if isinstance(ret, Exception):
  408. err_l[fname] = ret
  409. if len(err_l) > 0:
  410. raise LeApiDataCheckError("Datas consistency checks fails", err_l)
  411. ## @brief Prepare a field_list
  412. # @param field_list list : List of string representing fields
  413. # @return A well formated field list
  414. # @throw LeApiDataCheckError if invalid field given
  415. @classmethod
  416. def _prepare_field_list(cls, field_list):
  417. err_l = dict()
  418. ret_field_list = list()
  419. for field in field_list:
  420. if cls._field_is_relational(field):
  421. ret = cls._prepare_relational_fields(field)
  422. else:
  423. ret = cls._check_field(field)
  424. if isinstance(ret, Exception):
  425. err_l[field] = ret
  426. else:
  427. ret_field_list.append(ret)
  428. if len(err_l) > 0:
  429. raise LeApiDataCheckError(err_l)
  430. return ret_field_list
  431. ## @brief Check that a relational field is valid
  432. # @param field str : a relational field
  433. # @return a nature
  434. @classmethod
  435. def _prepare_relational_fields(cls, field):
  436. raise NotImplementedError("Abstract method")
  437. ## @brief Check that the field list only contains fields that are in the current class
  438. # @return None if no problem, else returns a list of exceptions that occurs during the check
  439. @classmethod
  440. def _check_field(cls, field):
  441. if field not in cls.fieldlist():
  442. return ValueError("No such field '%s' in %s"%(field, cls.__name__))
  443. return field
  444. ## @brief Prepare the order parameter for the get method
  445. # @note if an item in order_list is just a str it is considered as ASC by default
  446. # @param order_list list : A list of field name or tuple (FIELDNAME, [ASC|DESC])
  447. # @return a list of tuple (FIELDNAME, [ASC|DESC] )
  448. @classmethod
  449. def _prepare_order_fields(cls, order_field_list):
  450. errors = dict()
  451. result = []
  452. for order_field in order_field_list:
  453. if not isinstance(order_field, tuple):
  454. order_field = (order_field, 'ASC')
  455. if len(order_field) != 2 or order_field[1].upper() not in ['ASC', 'DESC']:
  456. errors[order_field] = ValueError("Expected a string or a tuple with (FIELDNAME, ['ASC'|'DESC']) but got : %s"%order_field)
  457. else:
  458. ret = cls._check_field(order_field[0])
  459. if isinstance(ret, Exception):
  460. errors[order_field] = ret
  461. order_field = (order_field[0], order_field[1].upper())
  462. result.append(order_field)
  463. if len(errors) > 0:
  464. return LeApiErrors("Errors when preparing ordering fields", errors)
  465. return result
  466. ## @brief Prepare filters for datasource
  467. #
  468. # This method divide filters in two categories :
  469. # - filters : standart FIELDNAME OP VALUE filter
  470. # - relationnal_filters : filter on object relation RELATION_NATURE OP VALUE
  471. #
  472. # Both categories of filters are represented in the same way, a tuple with 3 elements (NAME|NAT , OP, VALUE )
  473. #
  474. # @param filters_l list : This list can contain str "FIELDNAME OP VALUE" and tuples (FIELDNAME, OP, VALUE)
  475. # @return a tuple(FILTERS, RELATIONNAL_FILTERS
  476. #
  477. # @see @ref datasource_side
  478. @classmethod
  479. def _prepare_filters(cls, filters_l):
  480. filters = list()
  481. res_filters = list()
  482. rel_filters = list()
  483. err_l = dict()
  484. #Splitting in tuple if necessary
  485. for fil in filters_l:
  486. if len(fil) == 3 and not isinstance(fil, str):
  487. filters.append(tuple(fil))
  488. else:
  489. filters.append(cls._split_filter(fil))
  490. for field, operator, value in filters:
  491. if cls._field_is_relational(field):
  492. #Checks relational fields
  493. ret = cls._prepare_relational_fields(field)
  494. if isinstance(ret, Exception):
  495. err_l[field] = ret
  496. else:
  497. rel_filters.append((ret, operator, value))
  498. else:
  499. #Checks other fields
  500. ret = cls._check_field(field)
  501. if isinstance(ret, Exception):
  502. err_l[field] = ret
  503. else:
  504. res_filters.append((field,operator, value))
  505. if len(err_l) > 0:
  506. raise LeApiDataCheckError("Error while preparing filters : ", err_l)
  507. return (res_filters, rel_filters)
  508. ## @brief Check and split a query filter
  509. # @note The query_filter format is "FIELD OPERATOR VALUE"
  510. # @param query_filter str : A query_filter string
  511. # @param cls
  512. # @return a tuple (FIELD, OPERATOR, VALUE)
  513. @classmethod
  514. def _split_filter(cls, query_filter):
  515. if cls._query_re is None:
  516. cls._compile_query_re()
  517. matches = cls._query_re.match(query_filter)
  518. if not matches:
  519. raise ValueError("The query_filter '%s' seems to be invalid"%query_filter)
  520. result = (matches.group('field'), re.sub(r'\s', ' ', matches.group('operator'), count=0), matches.group('value').strip())
  521. for r in result:
  522. if len(r) == 0:
  523. raise ValueError("The query_filter '%s' seems to be invalid"%query_filter)
  524. return result
  525. ## @brief Compile the regex for query_filter processing
  526. # @note Set _LeObject._query_re
  527. @classmethod
  528. def _compile_query_re(cls):
  529. op_re_piece = '(?P<operator>(%s)'%cls._query_operators[0].replace(' ', '\s')
  530. for operator in cls._query_operators[1:]:
  531. op_re_piece += '|(%s)'%operator.replace(' ', '\s')
  532. op_re_piece += ')'
  533. cls._query_re = re.compile('^\s*(?P<field>(((superior)|(subordinate))\.)?[a-z_][a-z0-9\-_]*)\s*'+op_re_piece+'\s*(?P<value>[^<>=!].*)\s*$', flags=re.IGNORECASE)
  534. pass
  535. ## @brief Check if a field is relational or not
  536. # @param field str : the field to test
  537. # @return True if the field is relational else False
  538. @staticmethod
  539. def _field_is_relational(field):
  540. return field.startswith('superior.') or field.startswith('subordinate.')
  541. ## @page leobject_filters LeObject query filters
  542. # The LeObject API provide methods that accept filters allowing the user
  543. # to query the database and fetch LodelEditorialObjects.
  544. #
  545. # The LeObject API translate those filters for the datasource.
  546. #
  547. # @section api_user_side API user side filters
  548. # Filters are string expressing a condition. The string composition
  549. # is as follow : "<FIELD> <OPERATOR> <VALUE>"
  550. # @subsection fpart FIELD
  551. # @subsubsection standart fields
  552. # Standart fields, represents a value of the LeObject for example "title", "lodel_id" etc.
  553. # @subsubsection rfields relationnal fields
  554. # relationnal fields, represents a relation with the object hierarchy. Those fields are composed as follow :
  555. # "<RELATION>.<NATURE>".
  556. #
  557. # - Relation can takes two values : superiors or subordinates
  558. # - Nature is a relation nature ( see EditorialModel.classtypes )
  559. # Examples : "superiors.parent", "subordinates.translation" etc.
  560. # @note The field_list arguement of leapi.leapi._LeObject.get() use the same syntax than the FIELD filter part
  561. # @subsection oppart OPERATOR
  562. # The OPERATOR part of a filter is a comparison operator. There is
  563. # - standart comparison operators : = , <, > , <=, >=, !=
  564. # - vagueness string comparison 'like' and 'not like'
  565. # - list operators : 'in' and 'not in'
  566. # The list of allowed operators is sotred at leapi.leapi._LeObject._query_operators .
  567. # @subsection valpart VALUE
  568. # The VALUE part of a filter is... just a value...
  569. #
  570. # @section datasource_side Datasource side filters
  571. # As said above the API "translate" filters before forwarding them to the datasource.
  572. #
  573. # The translation process transform filters in tuple composed of 3 elements
  574. # ( @ref fpart , @ref oppart , @ref valpart ). Each element is a string.
  575. #
  576. # There is a special case for @ref rfields : the field element is a tuple composed with two elements
  577. # ( RELATION, NATURE ) where NATURE is a string ( see EditorialModel.classtypes ) and RELATION is one of
  578. # the defined constant :
  579. #
  580. # - leapi.lecrud.REL_SUB for "subordinates"
  581. # - leapi.lecrud.REL_SUP for "superiors"
  582. #
  583. # @note The filters translation process also check if given field are valids compared to the concerned letype and/or the leclass
  584. ## @page lecrud_instanciation LeCrud child classes instanciations
  585. #
  586. # _LeCrud provide a generic __init__ method for all its child classes. The following notes are
  587. # important parts of the instanciation mechanism.
  588. #
  589. # The constructor takes 2 parameters :
  590. # - a uniq identifier (uid)
  591. # - **kwargs for object datas
  592. #
  593. # @section lecrud_pi Partial instancation
  594. #
  595. # You can make partial instanciations by giving only parts of datas and even by giving only a uid
  596. #
  597. # @warning Partial instanciation needs an uid field name (lodel_id for LeObject and id_relation for LeRelation). This implies that you cannot make partial instance of a LeCrud.
  598. #
  599. # @subsection lecrud_pitools Partial instances tools
  600. #
  601. # The _LeCrud.is_complete() method indicates whether or not an instance is partial.
  602. #
  603. # The _LeCrud.populate() method fetch missing datas
  604. #
  605. # You partially instanciate an abtract class (like LeClass or LeRelation) using only a uid. Then you cannot populate this kind of instance (you cannot dinamically change the type of an instance). The _LeCrud.get_instance() method returns a populated instance with the good type.
  606. #