Commit 1cf64762 authored by Sylvain Thénault's avatar Sylvain Thénault
Browse files

[entity] continue cleanup of Entity/AnyEntity namespace

* prefix by cw_ or _cw all '2nd zone' attributes / methods, other
  most commonly used will be done later (some methods used by client
  are made private anyway when they are for internal purpose anyway)

* kill set_eid, use direct affectation instead

* kill the auto-transmutation feature (pre_add_hook), hence releasing
  3.9 will require releasing file cube as well
parent 9ab2b4c74baf
......@@ -584,7 +584,7 @@ class NoHookRQLObjectStore(RQLObjectStore):
kwargs[k] = getattr(v, 'eid', v)
entity, rels = self.metagen.base_etype_dicts(etype)
entity = copy(entity)
entity._related_cache = {}
entity.cw_clear_relation_cache()
self.metagen.init_entity(entity)
entity.update(kwargs)
entity.edited_attributes = set(entity)
......
......@@ -306,7 +306,7 @@ class CubicWebTC(TestCase):
req.execute('SET X in_group G WHERE X eid %%(x)s, G name IN(%s)'
% ','.join(repr(g) for g in groups),
{'x': user.eid})
user.clear_related_cache('in_group', 'subject')
user.cw_clear_relation_cache('in_group', 'subject')
if commit:
req.cnx.commit()
return user
......
......@@ -42,7 +42,7 @@ class AnyEntity(Entity):
for rschema, attrschema in self.e_schema.attribute_definitions():
if rschema.meta:
continue
value = self.get_value(rschema.type)
value = self.cw_attr_value(rschema.type)
if value:
# make the value printable (dates, floats, bytes, etc.)
return self.printable_value(rschema.type, value, attrschema.type,
......@@ -107,7 +107,7 @@ class AnyEntity(Entity):
"""
if rtype is None:
return self.dc_title().lower()
value = self.get_value(rtype)
value = self.cw_attr_value(rtype)
# do not restrict to `unicode` because Bytes will return a `str` value
if isinstance(value, basestring):
return self.printable_value(rtype, format='text/plain').lower()
......
......@@ -108,7 +108,7 @@ class WorkflowTC(CubicWebTC):
self.commit()
iworkflowable.change_state('deactivated', u'deactivate 2')
self.commit()
e.clear_related_cache('wf_info_for', 'object')
e.cw_clear_relation_cache('wf_info_for', 'object')
self.assertEquals([tr.comment for tr in e.reverse_wf_info_for],
['deactivate 1', 'activate 1', 'deactivate 2'])
self.assertEquals(iworkflowable.latest_trinfo().comment, 'deactivate 2')
......@@ -128,7 +128,7 @@ class WorkflowTC(CubicWebTC):
def _test_manager_deactivate(self, user):
iworkflowable = user.cw_adapt_to('IWorkflowable')
user.clear_related_cache('in_state', 'subject')
user.cw_clear_relation_cache('in_state', 'subject')
self.assertEquals(len(user.in_state), 1)
self.assertEquals(iworkflowable.state, 'deactivated')
trinfo = iworkflowable.latest_trinfo()
......
......@@ -173,7 +173,7 @@ class Workflow(AnyEntity):
{'os': todelstate.eid, 'ns': replacement.eid})
execute('SET X to_state NS WHERE X to_state OS, OS eid %(os)s, NS eid %(ns)s',
{'os': todelstate.eid, 'ns': replacement.eid})
todelstate.delete()
todelstate.cw_delete()
class BaseTransition(AnyEntity):
......
This diff is collapsed.
......@@ -233,7 +233,7 @@ class Model(entities.AnyEntity):
return self.req.datastore_get(self.eid)
except AttributeError: # self.req is not a server session
return Get(self.eid)
self.set_defaults()
self._cw_set_defaults()
values = self._to_gae_dict(convert=False)
parent = key_name = _app = None
if self._gaeinitargs is not None:
......@@ -343,7 +343,7 @@ class Model(entities.AnyEntity):
self.req = req
dbmodel = self.to_gae_model()
key = Put(dbmodel)
self.set_eid(str(key))
self.eid = str(key)
if self.req is not None and self.rset is None:
self.rset = rset_from_objs(self.req, dbmodel, ('eid',),
'Any X WHERE X eid %(x)s', {'x': self.eid})
......@@ -409,7 +409,7 @@ class Model(entities.AnyEntity):
def dynamic_properties(self):
raise NotImplementedError('use eschema')
def is_saved(self):
def cw_is_saved(self):
return self.has_eid()
def parent(self):
......
......@@ -49,15 +49,15 @@ def _clear_related_cache(session, gaesubject, rtype, gaeobject):
except KeyError:
pass
else:
entity.clear_related_cache(rtype, role)
entity.cw_clear_relation_cache(rtype, role)
if gaesubject.kind() == 'CWUser':
for asession in session.repo._sessions.itervalues():
if asession.user.eid == subject:
asession.user.clear_related_cache(rtype, 'subject')
asession.user.cw_clear_relation_cache(rtype, 'subject')
if gaeobject.kind() == 'CWUser':
for asession in session.repo._sessions.itervalues():
if asession.user.eid == object:
asession.user.clear_related_cache(rtype, 'object')
asession.user.cw_clear_relation_cache(rtype, 'object')
def _mark_modified(session, gaeentity):
modified = session.transaction_data.setdefault('modifiedentities', {})
......
......@@ -15,9 +15,6 @@
#
# You should have received a copy of the GNU Lesser General Public License along
# with CubicWeb. If not, see <http://www.gnu.org/licenses/>.
"""
"""
from cubicweb.goa.testlib import *
from cubicweb import Binary
......@@ -612,7 +609,7 @@ class RQLTest(GAEBasedTC):
def test_error_unknown_eid(self):
rset = self.req.execute('Any X WHERE X eid %(x)s', {'x': '1234'})
self.assertEquals(len(rset), 0)
self.blog.delete()
self.blog.cw_delete()
rset = self.req.execute('Any X WHERE X eid %(x)s', {'x': self.blog.eid})
self.assertEquals(len(rset), 0)
......
......@@ -15,9 +15,8 @@
#
# You should have received a copy of the GNU Lesser General Public License along
# with CubicWeb. If not, see <http://www.gnu.org/licenses/>.
"""bookmark related hooks
"""bookmark related hooks"""
"""
__docformat__ = "restructuredtext en"
from cubicweb.server import hook
......@@ -28,7 +27,7 @@ class AutoDeleteBookmarkOp(hook.Operation):
def precommit_event(self):
if not self.session.deleted_in_transaction(self.bookmark.eid):
if not self.bookmark.bookmarked_by:
self.bookmark.delete()
self.bookmark.cw_delete()
class DelBookmarkedByHook(hook.Hook):
......
......@@ -29,9 +29,9 @@ from cubicweb.server import BEFORE_ADD_RELATIONS, ON_COMMIT_ADD_RELATIONS, hook
def check_entity_attributes(session, entity, editedattrs=None):
eid = entity.eid
eschema = entity.e_schema
# .skip_security_attributes is there to bypass security for attributes
# ._cw_skip_security_attributes is there to bypass security for attributes
# set by hooks by modifying the entity's dictionnary
dontcheck = entity.skip_security_attributes
dontcheck = entity._cw_skip_security_attributes
if editedattrs is None:
try:
editedattrs = entity.edited_attributes
......@@ -57,7 +57,7 @@ class _CheckEntityPermissionOp(hook.LateOperation):
for values in session.transaction_data.pop('check_entity_perm_op'):
entity = session.entity_from_eid(values[0])
action = values[1]
entity.check_perm(action)
entity.cw_check_perm(action)
check_entity_attributes(session, entity, values[2:])
def commit_event(self):
......@@ -105,10 +105,10 @@ class AfterUpdateEntitySecurityHook(SecurityHook):
def __call__(self):
try:
# check user has permission right now, if not retry at commit time
self.entity.check_perm('update')
self.entity.cw_check_perm('update')
check_entity_attributes(self._cw, self.entity)
except Unauthorized:
self.entity.clear_local_perm_cache('update')
self.entity._cw_clear_local_perm_cache('update')
# save back editedattrs in case the entity is reedited later in the
# same transaction, which will lead to edited_attributes being
# overwritten
......@@ -122,7 +122,7 @@ class BeforeDelEntitySecurityHook(SecurityHook):
events = ('before_delete_entity',)
def __call__(self):
self.entity.check_perm('delete')
self.entity.cw_check_perm('delete')
class BeforeAddRelationSecurityHook(SecurityHook):
......
......@@ -145,7 +145,7 @@ class TreeMixIn(object):
entities=entities)
def children_rql(self):
return self.related_rql(self.tree_attribute, self.children_target)
return self.cw_related_rql(self.tree_attribute, self.children_target)
def is_leaf(self):
return len(self.children()) == 0
......
......@@ -453,7 +453,7 @@ class ResultSet(object):
etype = self.description[row][col]
entity = self.req.vreg['etypes'].etype_class(etype)(req, rset=self,
row=row, col=col)
entity.set_eid(eid)
entity.eid = eid
# cache entity
req.set_entity_cache(entity)
eschema = entity.e_schema
......@@ -494,7 +494,7 @@ class ResultSet(object):
rrset.req = req
else:
rrset = self._build_entity(row, outerselidx).as_rset()
entity.set_related_cache(attr, role, rrset)
entity.cw_set_relation_cache(attr, role, rrset)
return entity
@cached
......
......@@ -1033,7 +1033,7 @@ class has_permission(EntitySelector):
return self.score(req, rset, row, col)
def score_entity(self, entity):
if entity.has_perm(self.action):
if entity.cw_has_perm(self.action):
return 1
return 0
......
......@@ -565,7 +565,7 @@ class Repository(object):
session.close()
session = Session(user, self, cnxprops)
user._cw = user.cw_rset.req = session
user.clear_related_cache()
user.cw_clear_relation_cache()
self._sessions[session.id] = session
self.info('opened %s', session)
self.hm.call_hooks('session_open', session)
......@@ -1021,17 +1021,12 @@ class Repository(object):
the entity instance
"""
# init edited_attributes before calling before_add_entity hooks
entity._is_saved = False # entity has an eid but is not yet saved
entity.edited_attributes = set(entity)
entity_ = entity.pre_add_hook()
# XXX kill that transmutation feature !
if not entity_ is entity:
entity.__class__ = entity_.__class__
entity.__dict__.update(entity_.__dict__)
entity._cw_is_saved = False # entity has an eid but is not yet saved
entity.edited_attributes = set(entity) # XXX cw_edited_attributes
eschema = entity.e_schema
source = self.locate_etype_source(entity.__regid__)
# allocate an eid to the entity before calling hooks
entity.set_eid(self.system_source.create_eid(session))
entity.eid = self.system_source.create_eid(session)
# set caches asap
extid = self.init_entity_caches(session, entity, source)
if server.DEBUG & server.DBG_REPO:
......@@ -1046,12 +1041,12 @@ class Repository(object):
rschema = eschema.subjrels[attr]
if not rschema.final: # inlined relation
relations.append((attr, entity[attr]))
entity.set_defaults()
entity._cw_set_defaults()
if session.is_hook_category_activated('integrity'):
entity.check(creation=True)
entity._cw_check(creation=True)
source.add_entity(session, entity)
self.add_info(session, entity, source, extid, complete=False)
entity._is_saved = True # entity has an eid and is saved
entity._cw_is_saved = True # entity has an eid and is saved
# prefill entity relation caches
for rschema in eschema.subject_relations():
rtype = str(rschema)
......@@ -1060,12 +1055,13 @@ class Repository(object):
if rschema.final:
entity.setdefault(rtype, None)
else:
entity.set_related_cache(rtype, 'subject', session.empty_rset())
entity.cw_set_relation_cache(rtype, 'subject',
session.empty_rset())
for rschema in eschema.object_relations():
rtype = str(rschema)
if rtype in schema.VIRTUAL_RTYPES:
continue
entity.set_related_cache(rtype, 'object', session.empty_rset())
entity.cw_set_relation_cache(rtype, 'object', session.empty_rset())
# set inline relation cache before call to after_add_entity
for attr, value in relations:
session.update_rel_cache_add(entity.eid, attr, value)
......@@ -1094,7 +1090,7 @@ class Repository(object):
entity.edited_attributes = edited_attributes
try:
if session.is_hook_category_activated('integrity'):
entity.check()
entity._cw_check()
only_inline_rels, need_fti_update = True, False
relations = []
source = self.source_from_eid(entity.eid, session)
......@@ -1132,7 +1128,7 @@ class Repository(object):
hm.call_hooks('after_update_entity', session, entity=entity)
for attr, value, prevvalue in relations:
# if the relation is already cached, update existant cache
relcache = entity.relation_cached(attr, 'subject')
relcache = entity.cw_relation_cached(attr, 'subject')
if prevvalue is not None:
hm.call_hooks('after_delete_relation', session,
eidfrom=entity.eid, rtype=attr, eidto=prevvalue)
......@@ -1142,8 +1138,8 @@ class Repository(object):
if relcache is not None:
session.update_rel_cache_add(entity.eid, attr, value)
else:
entity.set_related_cache(attr, 'subject',
session.eid_rset(value))
entity.cw_set_relation_cache(attr, 'subject',
session.eid_rset(value))
hm.call_hooks('after_add_relation', session,
eidfrom=entity.eid, rtype=attr, eidto=value)
finally:
......
......@@ -242,7 +242,7 @@ class Session(RequestSessionBase):
entity = self.entity_cache(eid)
except KeyError:
return
rcache = entity.relation_cached(rtype, role)
rcache = entity.cw_relation_cached(rtype, role)
if rcache is not None:
rset, entities = rcache
rset = rset.copy()
......@@ -258,14 +258,15 @@ class Session(RequestSessionBase):
targetentity.cw_col = 0
rset.rowcount += 1
entities.append(targetentity)
entity._related_cache['%s_%s' % (rtype, role)] = (rset, tuple(entities))
entity._cw_related_cache['%s_%s' % (rtype, role)] = (
rset, tuple(entities))
def _update_entity_rel_cache_del(self, eid, rtype, role, targeteid):
try:
entity = self.entity_cache(eid)
except KeyError:
return
rcache = entity.relation_cached(rtype, role)
rcache = entity.cw_relation_cached(rtype, role)
if rcache is not None:
rset, entities = rcache
for idx, row in enumerate(rset.rows):
......@@ -284,7 +285,8 @@ class Session(RequestSessionBase):
del rset.description[idx]
del entities[idx]
rset.rowcount -= 1
entity._related_cache['%s_%s' % (rtype, role)] = (rset, tuple(entities))
entity._cw_related_cache['%s_%s' % (rtype, role)] = (
rset, tuple(entities))
# resource accessors ######################################################
......
......@@ -341,7 +341,7 @@ class AbstractSource(object):
entity.
"""
entity = self.repo.vreg['etypes'].etype_class(etype)(session)
entity.set_eid(eid)
entity.eid = eid
return entity
def after_entity_insertion(self, session, lid, entity):
......
......@@ -1007,10 +1007,10 @@ class NativeSQLSource(SQLAdapterMixIn, AbstractSource):
entity[rtype] = unicode(value, session.encoding, 'replace')
else:
entity[rtype] = value
entity.set_eid(eid)
entity.eid = eid
session.repo.init_entity_caches(session, entity, self)
entity.edited_attributes = set(entity)
entity.check()
entity._cw_check()
self.repo.hm.call_hooks('before_add_entity', session, entity=entity)
# restore the entity
action.changes['cw_eid'] = eid
......@@ -1077,7 +1077,7 @@ class NativeSQLSource(SQLAdapterMixIn, AbstractSource):
return [session._(
"Can't undo creation of entity %(eid)s of type %(etype)s, type "
"no more supported" % {'eid': eid, 'etype': etype})]
entity.set_eid(eid)
entity.eid = eid
# for proper eid/type cache update
hook.set_operation(session, 'pendingeids', eid,
CleanupDeletedEidsCacheOp)
......
......@@ -487,7 +487,7 @@ class InsertRelationsStep(Step):
value = row[index]
index += 1
if rorder == InsertRelationsStep.FINAL:
edef.rql_set_value(rtype, value)
edef._cw_rql_set_value(rtype, value)
elif rorder == InsertRelationsStep.RELATION:
self.plan.add_relation_def( (edef, rtype, value) )
edef.querier_pending_relations[(rtype, 'subject')] = value
......@@ -584,7 +584,7 @@ class UpdateStep(Step):
edef = edefs[eid]
except KeyError:
edefs[eid] = edef = session.entity_from_eid(eid)
edef.rql_set_value(str(rschema), rhsval)
edef._cw_rql_set_value(str(rschema), rhsval)
else:
repo.glob_add_relation(session, lhsval, str(rschema), rhsval)
result[i] = newrow
......
......@@ -15,9 +15,6 @@
#
# You should have received a copy of the GNU Lesser General Public License along
# with CubicWeb. If not, see <http://www.gnu.org/licenses/>.
"""
"""
from os.path import dirname, join, abspath
from datetime import datetime, timedelta
......@@ -113,11 +110,11 @@ class TwoSourcesTC(CubicWebTC):
self.assertEquals(len(rset), 4)
# since they are orderd by eid, we know the 3 first one is coming from the system source
# and the others from external source
self.assertEquals(rset.get_entity(0, 0).metainformation(),
self.assertEquals(rset.get_entity(0, 0).cw_metainformation(),
{'source': {'adapter': 'native', 'uri': 'system'},
'type': u'Card', 'extid': None})
externent = rset.get_entity(3, 0)
metainf = externent.metainformation()
metainf = externent.cw_metainformation()
self.assertEquals(metainf['source'], {'adapter': 'pyrorql', 'base-url': 'http://extern.org/', 'uri': 'extern'})
self.assertEquals(metainf['type'], 'Card')
self.assert_(metainf['extid'])
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment