author | Adrien Di Mascio <Adrien.DiMascio@logilab.fr> |
Tue, 22 Sep 2009 12:11:12 +0200 | |
changeset 3369 | 7b88d12b4ee2 |
parent 3300 | c7c4775a5619 |
parent 3316 | c4c07aab1c39 |
child 3376 | f5c69485381f |
permissions | -rw-r--r-- |
0 | 1 |
"""Base class for entity objects manipulated in clients |
2 |
||
3 |
:organization: Logilab |
|
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1904
diff
changeset
|
4 |
:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2. |
0 | 5 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1904
diff
changeset
|
6 |
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses |
0 | 7 |
""" |
8 |
__docformat__ = "restructuredtext en" |
|
9 |
||
1154 | 10 |
from warnings import warn |
11 |
||
0 | 12 |
from logilab.common import interface |
13 |
from logilab.common.compat import all |
|
14 |
from logilab.common.decorators import cached |
|
2613
5e19c2bb370e
R [all] logilab.common 0.44 provides only deprecated
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2421
diff
changeset
|
15 |
from logilab.common.deprecation import deprecated |
2312
af4d8f75c5db
use xml_escape
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2125
diff
changeset
|
16 |
from logilab.mtconverter import TransformData, TransformError, xml_escape |
631
99f5852f8604
major selector refactoring (mostly to avoid looking for select parameters on the target class), start accept / interface unification)
sylvain.thenault@logilab.fr
parents:
479
diff
changeset
|
17 |
|
3241
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
18 |
from rql import parse |
0 | 19 |
from rql.utils import rqlvar_maker |
20 |
||
21 |
from cubicweb import Unauthorized |
|
22 |
from cubicweb.rset import ResultSet |
|
692
800592b8d39b
replace deprecated cubicweb.common.selectors by its new module path (cubicweb.selectors)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
631
diff
changeset
|
23 |
from cubicweb.selectors import yes |
2656
a93ae0f6c0ad
R [base classes] only AppObject remaning, no more AppRsetObject
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2650
diff
changeset
|
24 |
from cubicweb.appobject import AppObject |
2827
d1a89d165045
remove 3.2 bw compat code
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2824
diff
changeset
|
25 |
from cubicweb.schema import RQLVocabularyConstraint, RQLConstraint |
3241
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
26 |
from cubicweb.rqlrewrite import RQLRewriter |
709 | 27 |
|
2421
08d42928fe36
does not make sense any more
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
2381
diff
changeset
|
28 |
from cubicweb.common.uilib import printable_value, soup2xhtml |
08d42928fe36
does not make sense any more
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
2381
diff
changeset
|
29 |
from cubicweb.common.mixins import MI_REL_TRIGGERS |
08d42928fe36
does not make sense any more
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
2381
diff
changeset
|
30 |
from cubicweb.common.mttransforms import ENGINE |
0 | 31 |
|
32 |
_marker = object() |
|
33 |
||
34 |
def greater_card(rschema, subjtypes, objtypes, index): |
|
35 |
for subjtype in subjtypes: |
|
36 |
for objtype in objtypes: |
|
37 |
card = rschema.rproperty(subjtype, objtype, 'cardinality')[index] |
|
38 |
if card in '+*': |
|
39 |
return card |
|
40 |
return '1' |
|
41 |
||
42 |
||
2656
a93ae0f6c0ad
R [base classes] only AppObject remaning, no more AppRsetObject
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2650
diff
changeset
|
43 |
class Entity(AppObject, dict): |
0 | 44 |
"""an entity instance has e_schema automagically set on |
45 |
the class and instances has access to their issuing cursor. |
|
1474 | 46 |
|
0 | 47 |
A property is set for each attribute and relation on each entity's type |
48 |
class. Becare that among attributes, 'eid' is *NEITHER* stored in the |
|
49 |
dict containment (which acts as a cache for other attributes dynamically |
|
50 |
fetched) |
|
51 |
||
52 |
:type e_schema: `cubicweb.schema.EntitySchema` |
|
53 |
:ivar e_schema: the entity's schema |
|
54 |
||
55 |
:type rest_var: str |
|
56 |
:cvar rest_var: indicates which attribute should be used to build REST urls |
|
57 |
If None is specified, the first non-meta attribute will |
|
58 |
be used |
|
1474 | 59 |
|
0 | 60 |
:type skip_copy_for: list |
61 |
:cvar skip_copy_for: a list of relations that should be skipped when copying |
|
62 |
this kind of entity. Note that some relations such |
|
63 |
as composite relations or relations that have '?1' as object |
|
64 |
cardinality |
|
65 |
""" |
|
66 |
__registry__ = 'etypes' |
|
717 | 67 |
__select__ = yes() |
1264
fe2934a7df7f
cleanup, avoid spurious warning
sylvain.thenault@logilab.fr
parents:
1177
diff
changeset
|
68 |
|
1474 | 69 |
# class attributes that must be set in class definition |
0 | 70 |
rest_attr = None |
1138
22f634977c95
make pylint happy, fix some bugs on the way
sylvain.thenault@logilab.fr
parents:
1132
diff
changeset
|
71 |
fetch_attrs = None |
2920
64322aa83a1d
start a new workflow engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2877
diff
changeset
|
72 |
skip_copy_for = ('in_state',) |
1264
fe2934a7df7f
cleanup, avoid spurious warning
sylvain.thenault@logilab.fr
parents:
1177
diff
changeset
|
73 |
# class attributes set automatically at registration time |
fe2934a7df7f
cleanup, avoid spurious warning
sylvain.thenault@logilab.fr
parents:
1177
diff
changeset
|
74 |
e_schema = None |
1474 | 75 |
|
0 | 76 |
@classmethod |
2807
696ff03f9a58
__initialize__ needs the schema as argument
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2788
diff
changeset
|
77 |
def __initialize__(cls, schema): |
0 | 78 |
"""initialize a specific entity class by adding descriptors to access |
79 |
entity type's attributes and relations |
|
80 |
""" |
|
2829
054a8805da52
turn id into __id__
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2827
diff
changeset
|
81 |
etype = cls.__id__ |
0 | 82 |
assert etype != 'Any', etype |
2807
696ff03f9a58
__initialize__ needs the schema as argument
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2788
diff
changeset
|
83 |
cls.e_schema = eschema = schema.eschema(etype) |
0 | 84 |
for rschema, _ in eschema.attribute_definitions(): |
85 |
if rschema.type == 'eid': |
|
86 |
continue |
|
87 |
setattr(cls, rschema.type, Attribute(rschema.type)) |
|
88 |
mixins = [] |
|
2941
196493bd099c
[entity] use role instead of x
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2931
diff
changeset
|
89 |
for rschema, _, role in eschema.relation_definitions(): |
196493bd099c
[entity] use role instead of x
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2931
diff
changeset
|
90 |
if (rschema, role) in MI_REL_TRIGGERS: |
196493bd099c
[entity] use role instead of x
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2931
diff
changeset
|
91 |
mixin = MI_REL_TRIGGERS[(rschema, role)] |
0 | 92 |
if not (issubclass(cls, mixin) or mixin in mixins): # already mixed ? |
93 |
mixins.append(mixin) |
|
94 |
for iface in getattr(mixin, '__implements__', ()): |
|
95 |
if not interface.implements(cls, iface): |
|
96 |
interface.extend(cls, iface) |
|
2941
196493bd099c
[entity] use role instead of x
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2931
diff
changeset
|
97 |
if role == 'subject': |
0 | 98 |
setattr(cls, rschema.type, SubjectRelation(rschema)) |
99 |
else: |
|
100 |
attr = 'reverse_%s' % rschema.type |
|
101 |
setattr(cls, attr, ObjectRelation(rschema)) |
|
102 |
if mixins: |
|
103 |
cls.__bases__ = tuple(mixins + [p for p in cls.__bases__ if not p is object]) |
|
104 |
cls.debug('plugged %s mixins on %s', mixins, etype) |
|
1474 | 105 |
|
0 | 106 |
@classmethod |
107 |
def fetch_rql(cls, user, restriction=None, fetchattrs=None, mainvar='X', |
|
108 |
settype=True, ordermethod='fetch_order'): |
|
109 |
"""return a rql to fetch all entities of the class type""" |
|
110 |
restrictions = restriction or [] |
|
111 |
if settype: |
|
2829
054a8805da52
turn id into __id__
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2827
diff
changeset
|
112 |
restrictions.append('%s is %s' % (mainvar, cls.__id__)) |
0 | 113 |
if fetchattrs is None: |
114 |
fetchattrs = cls.fetch_attrs |
|
115 |
selection = [mainvar] |
|
116 |
orderby = [] |
|
117 |
# start from 26 to avoid possible conflicts with X |
|
118 |
varmaker = rqlvar_maker(index=26) |
|
119 |
cls._fetch_restrictions(mainvar, varmaker, fetchattrs, selection, |
|
120 |
orderby, restrictions, user, ordermethod) |
|
121 |
rql = 'Any %s' % ','.join(selection) |
|
122 |
if orderby: |
|
123 |
rql += ' ORDERBY %s' % ','.join(orderby) |
|
124 |
rql += ' WHERE %s' % ', '.join(restrictions) |
|
125 |
return rql |
|
1474 | 126 |
|
0 | 127 |
@classmethod |
128 |
def _fetch_restrictions(cls, mainvar, varmaker, fetchattrs, |
|
129 |
selection, orderby, restrictions, user, |
|
130 |
ordermethod='fetch_order', visited=None): |
|
131 |
eschema = cls.e_schema |
|
132 |
if visited is None: |
|
133 |
visited = set((eschema.type,)) |
|
134 |
elif eschema.type in visited: |
|
135 |
# avoid infinite recursion |
|
136 |
return |
|
137 |
else: |
|
138 |
visited.add(eschema.type) |
|
139 |
_fetchattrs = [] |
|
140 |
for attr in fetchattrs: |
|
141 |
try: |
|
142 |
rschema = eschema.subject_relation(attr) |
|
143 |
except KeyError: |
|
144 |
cls.warning('skipping fetch_attr %s defined in %s (not found in schema)', |
|
2829
054a8805da52
turn id into __id__
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2827
diff
changeset
|
145 |
attr, cls.__id__) |
0 | 146 |
continue |
147 |
if not user.matching_groups(rschema.get_groups('read')): |
|
148 |
continue |
|
149 |
var = varmaker.next() |
|
150 |
selection.append(var) |
|
151 |
restriction = '%s %s %s' % (mainvar, attr, var) |
|
152 |
restrictions.append(restriction) |
|
153 |
if not rschema.is_final(): |
|
154 |
# XXX this does not handle several destination types |
|
155 |
desttype = rschema.objects(eschema.type)[0] |
|
156 |
card = rschema.rproperty(eschema, desttype, 'cardinality')[0] |
|
157 |
if card not in '?1': |
|
2928
edfdb69df6e8
oops, not self but cls here
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2877
diff
changeset
|
158 |
cls.warning('bad relation %s specified in fetch attrs for %s', |
edfdb69df6e8
oops, not self but cls here
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2877
diff
changeset
|
159 |
attr, cls) |
0 | 160 |
selection.pop() |
161 |
restrictions.pop() |
|
162 |
continue |
|
2871
83c5499e1436
[entity] fix fetch_rql w/ case where it's called while entity is not 'complete' (eg time where it's being added but have not yet all mandatory relations set)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2658
diff
changeset
|
163 |
# XXX we need outer join in case the relation is not mandatory |
83c5499e1436
[entity] fix fetch_rql w/ case where it's called while entity is not 'complete' (eg time where it's being added but have not yet all mandatory relations set)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2658
diff
changeset
|
164 |
# (card == '?') *or if the entity is being added*, since in |
83c5499e1436
[entity] fix fetch_rql w/ case where it's called while entity is not 'complete' (eg time where it's being added but have not yet all mandatory relations set)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2658
diff
changeset
|
165 |
# that case the relation may still be missing. As we miss this |
83c5499e1436
[entity] fix fetch_rql w/ case where it's called while entity is not 'complete' (eg time where it's being added but have not yet all mandatory relations set)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2658
diff
changeset
|
166 |
# later information here, systematically add it. |
83c5499e1436
[entity] fix fetch_rql w/ case where it's called while entity is not 'complete' (eg time where it's being added but have not yet all mandatory relations set)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2658
diff
changeset
|
167 |
restrictions[-1] += '?' |
2831
ddde6cf856a1
quick and dirty fix until introduction of CWEntityManager
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2830
diff
changeset
|
168 |
# XXX user.req.vreg iiiirk |
ddde6cf856a1
quick and dirty fix until introduction of CWEntityManager
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2830
diff
changeset
|
169 |
destcls = user.req.vreg['etypes'].etype_class(desttype) |
0 | 170 |
destcls._fetch_restrictions(var, varmaker, destcls.fetch_attrs, |
171 |
selection, orderby, restrictions, |
|
172 |
user, ordermethod, visited=visited) |
|
173 |
orderterm = getattr(cls, ordermethod)(attr, var) |
|
174 |
if orderterm: |
|
175 |
orderby.append(orderterm) |
|
176 |
return selection, orderby, restrictions |
|
177 |
||
1471
c889c3bcf5ec
new parent_classes method (cached)
sylvain.thenault@logilab.fr
parents:
1435
diff
changeset
|
178 |
@classmethod |
c889c3bcf5ec
new parent_classes method (cached)
sylvain.thenault@logilab.fr
parents:
1435
diff
changeset
|
179 |
@cached |
1840
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
180 |
def _rest_attr_info(cls): |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
181 |
mainattr, needcheck = 'eid', True |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
182 |
if cls.rest_attr: |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
183 |
mainattr = cls.rest_attr |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
184 |
needcheck = not cls.e_schema.has_unique_values(mainattr) |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
185 |
else: |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
186 |
for rschema in cls.e_schema.subject_relations(): |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
187 |
if rschema.is_final() and rschema != 'eid' and cls.e_schema.has_unique_values(rschema): |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
188 |
mainattr = str(rschema) |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
189 |
needcheck = False |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
190 |
break |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
191 |
if mainattr == 'eid': |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
192 |
needcheck = False |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
193 |
return mainattr, needcheck |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
194 |
|
1435
6cd6172718bb
allow to instantiate an entity without rset
sylvain.thenault@logilab.fr
parents:
1363
diff
changeset
|
195 |
def __init__(self, req, rset=None, row=None, col=0): |
2822
f26578339214
deprecate appobject.vreg and rename appobject instance attributes using cw_ prefix
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2818
diff
changeset
|
196 |
AppObject.__init__(self, req, rset=rset, row=row, col=col) |
0 | 197 |
dict.__init__(self) |
198 |
self._related_cache = {} |
|
199 |
if rset is not None: |
|
200 |
self.eid = rset[row][col] |
|
201 |
else: |
|
202 |
self.eid = None |
|
203 |
self._is_saved = True |
|
1474 | 204 |
|
0 | 205 |
def __repr__(self): |
206 |
return '<Entity %s %s %s at %s>' % ( |
|
207 |
self.e_schema, self.eid, self.keys(), id(self)) |
|
208 |
||
209 |
def __nonzero__(self): |
|
210 |
return True |
|
211 |
||
212 |
def __hash__(self): |
|
213 |
return id(self) |
|
214 |
||
3047
ba86b1bdbcab
fix __cmp__ arguments
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3000
diff
changeset
|
215 |
def __cmp__(self, other): |
3000
4e76477949d5
B [entities] #343385 comparing entities should raise NotImplementedError
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2928
diff
changeset
|
216 |
raise NotImplementedError('comparison not implemented for %s' % self.__class__) |
4e76477949d5
B [entities] #343385 comparing entities should raise NotImplementedError
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2928
diff
changeset
|
217 |
|
0 | 218 |
def pre_add_hook(self): |
219 |
"""hook called by the repository before doing anything to add the entity |
|
220 |
(before_add entity hooks have not been called yet). This give the |
|
221 |
occasion to do weird stuff such as autocast (File -> Image for instance). |
|
1474 | 222 |
|
0 | 223 |
This method must return the actual entity to be added. |
224 |
""" |
|
225 |
return self |
|
1474 | 226 |
|
0 | 227 |
def set_eid(self, eid): |
228 |
self.eid = self['eid'] = eid |
|
229 |
||
230 |
def has_eid(self): |
|
231 |
"""return True if the entity has an attributed eid (False |
|
232 |
meaning that the entity has to be created |
|
233 |
""" |
|
234 |
try: |
|
235 |
int(self.eid) |
|
236 |
return True |
|
237 |
except (ValueError, TypeError): |
|
238 |
return False |
|
239 |
||
240 |
def is_saved(self): |
|
241 |
"""during entity creation, there is some time during which the entity |
|
242 |
has an eid attributed though it's not saved (eg during before_add_entity |
|
243 |
hooks). You can use this method to ensure the entity has an eid *and* is |
|
244 |
saved in its source. |
|
245 |
""" |
|
246 |
return self.has_eid() and self._is_saved |
|
1474 | 247 |
|
0 | 248 |
@cached |
249 |
def metainformation(self): |
|
250 |
res = dict(zip(('type', 'source', 'extid'), self.req.describe(self.eid))) |
|
251 |
res['source'] = self.req.source_defs()[res['source']] |
|
252 |
return res |
|
253 |
||
475
b32a5772ff06
should clear local perm cache if first attempt failed
sylvain.thenault@logilab.fr
parents:
413
diff
changeset
|
254 |
def clear_local_perm_cache(self, action): |
b32a5772ff06
should clear local perm cache if first attempt failed
sylvain.thenault@logilab.fr
parents:
413
diff
changeset
|
255 |
for rqlexpr in self.e_schema.get_rqlexprs(action): |
b32a5772ff06
should clear local perm cache if first attempt failed
sylvain.thenault@logilab.fr
parents:
413
diff
changeset
|
256 |
self.req.local_perm_cache.pop((rqlexpr.eid, (('x', self.eid),)), None) |
b32a5772ff06
should clear local perm cache if first attempt failed
sylvain.thenault@logilab.fr
parents:
413
diff
changeset
|
257 |
|
0 | 258 |
def check_perm(self, action): |
259 |
self.e_schema.check_perm(self.req, action, self.eid) |
|
260 |
||
261 |
def has_perm(self, action): |
|
262 |
return self.e_schema.has_perm(self.req, action, self.eid) |
|
1474 | 263 |
|
2650
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2647
diff
changeset
|
264 |
def view(self, vid, __registry='views', **kwargs): |
0 | 265 |
"""shortcut to apply a view on this entity""" |
2650
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2647
diff
changeset
|
266 |
return self.vreg[__registry].render(vid, self.req, rset=self.rset, |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2647
diff
changeset
|
267 |
row=self.row, col=self.col, **kwargs) |
0 | 268 |
|
2059
af33833d7571
absolute_url / build_url refactoring to avoid potential name clash
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2058
diff
changeset
|
269 |
def absolute_url(self, *args, **kwargs): |
0 | 270 |
"""return an absolute url to view this entity""" |
2059
af33833d7571
absolute_url / build_url refactoring to avoid potential name clash
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2058
diff
changeset
|
271 |
# use *args since we don't want first argument to be "anonymous" to |
af33833d7571
absolute_url / build_url refactoring to avoid potential name clash
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2058
diff
changeset
|
272 |
# avoid potential clash with kwargs |
af33833d7571
absolute_url / build_url refactoring to avoid potential name clash
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2058
diff
changeset
|
273 |
if args: |
af33833d7571
absolute_url / build_url refactoring to avoid potential name clash
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2058
diff
changeset
|
274 |
assert len(args) == 1, 'only 0 or 1 non-named-argument expected' |
af33833d7571
absolute_url / build_url refactoring to avoid potential name clash
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2058
diff
changeset
|
275 |
method = args[0] |
af33833d7571
absolute_url / build_url refactoring to avoid potential name clash
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2058
diff
changeset
|
276 |
else: |
af33833d7571
absolute_url / build_url refactoring to avoid potential name clash
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2058
diff
changeset
|
277 |
method = None |
0 | 278 |
# in linksearch mode, we don't want external urls else selecting |
279 |
# the object for use in the relation is tricky |
|
280 |
# XXX search_state is web specific |
|
281 |
if getattr(self.req, 'search_state', ('normal',))[0] == 'normal': |
|
282 |
kwargs['base_url'] = self.metainformation()['source'].get('base-url') |
|
1904
e23536d29231
minor refactoring of absolute_url()
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
1842
diff
changeset
|
283 |
if method in (None, 'view'): |
1842
c7a22540d6f7
add some bw compat code for old rest_path prototype
sylvain.thenault@logilab.fr
parents:
1840
diff
changeset
|
284 |
try: |
c7a22540d6f7
add some bw compat code for old rest_path prototype
sylvain.thenault@logilab.fr
parents:
1840
diff
changeset
|
285 |
kwargs['_restpath'] = self.rest_path(kwargs.get('base_url')) |
c7a22540d6f7
add some bw compat code for old rest_path prototype
sylvain.thenault@logilab.fr
parents:
1840
diff
changeset
|
286 |
except TypeError: |
c7a22540d6f7
add some bw compat code for old rest_path prototype
sylvain.thenault@logilab.fr
parents:
1840
diff
changeset
|
287 |
warn('%s: rest_path() now take use_ext_eid argument, ' |
2829
054a8805da52
turn id into __id__
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2827
diff
changeset
|
288 |
'please update' % self.__id__, DeprecationWarning) |
1842
c7a22540d6f7
add some bw compat code for old rest_path prototype
sylvain.thenault@logilab.fr
parents:
1840
diff
changeset
|
289 |
kwargs['_restpath'] = self.rest_path() |
0 | 290 |
else: |
291 |
kwargs['rql'] = 'Any X WHERE X eid %s' % self.eid |
|
2818
326375561412
propagate some api changes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2807
diff
changeset
|
292 |
return self.req.build_url(method, **kwargs) |
0 | 293 |
|
1840
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
294 |
def rest_path(self, use_ext_eid=False): |
0 | 295 |
"""returns a REST-like (relative) path for this entity""" |
296 |
mainattr, needcheck = self._rest_attr_info() |
|
297 |
etype = str(self.e_schema) |
|
1840
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
298 |
path = etype.lower() |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
299 |
if mainattr != 'eid': |
0 | 300 |
value = getattr(self, mainattr) |
2125
19861294506f
https://www.logilab.net/cwo/ticket/343724
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2005
diff
changeset
|
301 |
if value is None or unicode(value) == u'': |
1840
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
302 |
mainattr = 'eid' |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
303 |
path += '/eid' |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
304 |
elif needcheck: |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
305 |
# make sure url is not ambiguous |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
306 |
rql = 'Any COUNT(X) WHERE X is %s, X %s %%(value)s' % ( |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
307 |
etype, mainattr) |
1904
e23536d29231
minor refactoring of absolute_url()
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
1842
diff
changeset
|
308 |
nbresults = self.req.execute(rql, {'value' : value})[0][0] |
e23536d29231
minor refactoring of absolute_url()
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
1842
diff
changeset
|
309 |
if nbresults != 1: # ambiguity? |
e23536d29231
minor refactoring of absolute_url()
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
1842
diff
changeset
|
310 |
mainattr = 'eid' |
e23536d29231
minor refactoring of absolute_url()
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
1842
diff
changeset
|
311 |
path += '/eid' |
0 | 312 |
if mainattr == 'eid': |
1840
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
313 |
if use_ext_eid: |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
314 |
value = self.metainformation()['extid'] |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
315 |
else: |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
316 |
value = self.eid |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
317 |
return '%s/%s' % (path, self.req.url_quote(value)) |
0 | 318 |
|
1360
13ae1121835e
rename attribute_metadata method to attr_metadata to save a few chars
sylvain.thenault@logilab.fr
parents:
1313
diff
changeset
|
319 |
def attr_metadata(self, attr, metadata): |
1101
0c067de38e46
unification of meta-attributes handling:
sylvain.thenault@logilab.fr
parents:
1098
diff
changeset
|
320 |
"""return a metadata for an attribute (None if unspecified)""" |
0c067de38e46
unification of meta-attributes handling:
sylvain.thenault@logilab.fr
parents:
1098
diff
changeset
|
321 |
value = getattr(self, '%s_%s' % (attr, metadata), None) |
0c067de38e46
unification of meta-attributes handling:
sylvain.thenault@logilab.fr
parents:
1098
diff
changeset
|
322 |
if value is None and metadata == 'encoding': |
0c067de38e46
unification of meta-attributes handling:
sylvain.thenault@logilab.fr
parents:
1098
diff
changeset
|
323 |
value = self.vreg.property_value('ui.encoding') |
0c067de38e46
unification of meta-attributes handling:
sylvain.thenault@logilab.fr
parents:
1098
diff
changeset
|
324 |
return value |
0 | 325 |
|
326 |
def printable_value(self, attr, value=_marker, attrtype=None, |
|
327 |
format='text/html', displaytime=True): |
|
328 |
"""return a displayable value (i.e. unicode string) which may contains |
|
329 |
html tags |
|
330 |
""" |
|
331 |
attr = str(attr) |
|
332 |
if value is _marker: |
|
333 |
value = getattr(self, attr) |
|
334 |
if isinstance(value, basestring): |
|
335 |
value = value.strip() |
|
336 |
if value is None or value == '': # don't use "not", 0 is an acceptable value |
|
337 |
return u'' |
|
338 |
if attrtype is None: |
|
339 |
attrtype = self.e_schema.destination(attr) |
|
340 |
props = self.e_schema.rproperties(attr) |
|
341 |
if attrtype == 'String': |
|
342 |
# internalinalized *and* formatted string such as schema |
|
343 |
# description... |
|
344 |
if props.get('internationalizable'): |
|
345 |
value = self.req._(value) |
|
1360
13ae1121835e
rename attribute_metadata method to attr_metadata to save a few chars
sylvain.thenault@logilab.fr
parents:
1313
diff
changeset
|
346 |
attrformat = self.attr_metadata(attr, 'format') |
0 | 347 |
if attrformat: |
348 |
return self.mtc_transform(value, attrformat, format, |
|
349 |
self.req.encoding) |
|
350 |
elif attrtype == 'Bytes': |
|
1360
13ae1121835e
rename attribute_metadata method to attr_metadata to save a few chars
sylvain.thenault@logilab.fr
parents:
1313
diff
changeset
|
351 |
attrformat = self.attr_metadata(attr, 'format') |
0 | 352 |
if attrformat: |
1360
13ae1121835e
rename attribute_metadata method to attr_metadata to save a few chars
sylvain.thenault@logilab.fr
parents:
1313
diff
changeset
|
353 |
encoding = self.attr_metadata(attr, 'encoding') |
0 | 354 |
return self.mtc_transform(value.getvalue(), attrformat, format, |
355 |
encoding) |
|
356 |
return u'' |
|
3212
07d11bacfefe
displaytime attribute should not have been removed from there
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3184
diff
changeset
|
357 |
value = printable_value(self.req, attrtype, value, props, |
07d11bacfefe
displaytime attribute should not have been removed from there
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3184
diff
changeset
|
358 |
displaytime=displaytime) |
0 | 359 |
if format == 'text/html': |
2312
af4d8f75c5db
use xml_escape
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2125
diff
changeset
|
360 |
value = xml_escape(value) |
0 | 361 |
return value |
362 |
||
363 |
def mtc_transform(self, data, format, target_format, encoding, |
|
364 |
_engine=ENGINE): |
|
365 |
trdata = TransformData(data, format, encoding, appobject=self) |
|
366 |
data = _engine.convert(trdata, target_format).decode() |
|
367 |
if format == 'text/html': |
|
1474 | 368 |
data = soup2xhtml(data, self.req.encoding) |
0 | 369 |
return data |
1474 | 370 |
|
0 | 371 |
# entity cloning ########################################################## |
372 |
||
373 |
def copy_relations(self, ceid): |
|
374 |
"""copy relations of the object with the given eid on this object |
|
375 |
||
376 |
By default meta and composite relations are skipped. |
|
377 |
Overrides this if you want another behaviour |
|
378 |
""" |
|
379 |
assert self.has_eid() |
|
380 |
execute = self.req.execute |
|
381 |
for rschema in self.e_schema.subject_relations(): |
|
2126
a25859917ccc
stop using meta attribute from yams schema. Use instead sets defining meta relations and another defining schema types. Refactor various schema view based on this
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2059
diff
changeset
|
382 |
if rschema.is_final() or rschema.meta: |
0 | 383 |
continue |
384 |
# skip already defined relations |
|
385 |
if getattr(self, rschema.type): |
|
386 |
continue |
|
387 |
if rschema.type in self.skip_copy_for: |
|
388 |
continue |
|
389 |
# skip composite relation |
|
390 |
if self.e_schema.subjrproperty(rschema, 'composite'): |
|
391 |
continue |
|
392 |
# skip relation with card in ?1 else we either change the copied |
|
393 |
# object (inlined relation) or inserting some inconsistency |
|
394 |
if self.e_schema.subjrproperty(rschema, 'cardinality')[1] in '?1': |
|
395 |
continue |
|
396 |
rql = 'SET X %s V WHERE X eid %%(x)s, Y eid %%(y)s, Y %s V' % ( |
|
397 |
rschema.type, rschema.type) |
|
398 |
execute(rql, {'x': self.eid, 'y': ceid}, ('x', 'y')) |
|
399 |
self.clear_related_cache(rschema.type, 'subject') |
|
400 |
for rschema in self.e_schema.object_relations(): |
|
401 |
if rschema.meta: |
|
402 |
continue |
|
403 |
# skip already defined relations |
|
404 |
if getattr(self, 'reverse_%s' % rschema.type): |
|
405 |
continue |
|
406 |
# skip composite relation |
|
407 |
if self.e_schema.objrproperty(rschema, 'composite'): |
|
408 |
continue |
|
409 |
# skip relation with card in ?1 else we either change the copied |
|
410 |
# object (inlined relation) or inserting some inconsistency |
|
411 |
if self.e_schema.objrproperty(rschema, 'cardinality')[0] in '?1': |
|
412 |
continue |
|
413 |
rql = 'SET V %s X WHERE X eid %%(x)s, Y eid %%(y)s, V %s Y' % ( |
|
414 |
rschema.type, rschema.type) |
|
415 |
execute(rql, {'x': self.eid, 'y': ceid}, ('x', 'y')) |
|
416 |
self.clear_related_cache(rschema.type, 'object') |
|
417 |
||
418 |
# data fetching methods ################################################### |
|
419 |
||
420 |
@cached |
|
421 |
def as_rset(self): |
|
422 |
"""returns a resultset containing `self` information""" |
|
423 |
rset = ResultSet([(self.eid,)], 'Any X WHERE X eid %(x)s', |
|
2829
054a8805da52
turn id into __id__
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2827
diff
changeset
|
424 |
{'x': self.eid}, [(self.__id__,)]) |
0 | 425 |
return self.req.decorate_rset(rset) |
1474 | 426 |
|
0 | 427 |
def to_complete_relations(self): |
428 |
"""by default complete final relations to when calling .complete()""" |
|
429 |
for rschema in self.e_schema.subject_relations(): |
|
430 |
if rschema.is_final(): |
|
431 |
continue |
|
432 |
if len(rschema.objects(self.e_schema)) > 1: |
|
433 |
# ambigous relations, the querier doesn't handle |
|
434 |
# outer join correctly in this case |
|
435 |
continue |
|
436 |
if rschema.inlined: |
|
437 |
matching_groups = self.req.user.matching_groups |
|
438 |
if matching_groups(rschema.get_groups('read')) and \ |
|
439 |
all(matching_groups(es.get_groups('read')) |
|
440 |
for es in rschema.objects(self.e_schema)): |
|
441 |
yield rschema, 'subject' |
|
1474 | 442 |
|
0 | 443 |
def to_complete_attributes(self, skip_bytes=True): |
444 |
for rschema, attrschema in self.e_schema.attribute_definitions(): |
|
445 |
# skip binary data by default |
|
446 |
if skip_bytes and attrschema.type == 'Bytes': |
|
447 |
continue |
|
448 |
attr = rschema.type |
|
449 |
if attr == 'eid': |
|
450 |
continue |
|
451 |
# password retreival is blocked at the repository server level |
|
452 |
if not self.req.user.matching_groups(rschema.get_groups('read')) \ |
|
453 |
or attrschema.type == 'Password': |
|
454 |
self[attr] = None |
|
455 |
continue |
|
456 |
yield attr |
|
1474 | 457 |
|
0 | 458 |
def complete(self, attributes=None, skip_bytes=True): |
459 |
"""complete this entity by adding missing attributes (i.e. query the |
|
460 |
repository to fill the entity) |
|
461 |
||
462 |
:type skip_bytes: bool |
|
463 |
:param skip_bytes: |
|
464 |
if true, attribute of type Bytes won't be considered |
|
465 |
""" |
|
466 |
assert self.has_eid() |
|
467 |
varmaker = rqlvar_maker() |
|
468 |
V = varmaker.next() |
|
469 |
rql = ['WHERE %s eid %%(x)s' % V] |
|
470 |
selected = [] |
|
471 |
for attr in (attributes or self.to_complete_attributes(skip_bytes)): |
|
472 |
# if attribute already in entity, nothing to do |
|
473 |
if self.has_key(attr): |
|
474 |
continue |
|
475 |
# case where attribute must be completed, but is not yet in entity |
|
476 |
var = varmaker.next() |
|
477 |
rql.append('%s %s %s' % (V, attr, var)) |
|
478 |
selected.append((attr, var)) |
|
479 |
# +1 since this doen't include the main variable |
|
480 |
lastattr = len(selected) + 1 |
|
481 |
if attributes is None: |
|
482 |
# fetch additional relations (restricted to 0..1 relations) |
|
483 |
for rschema, role in self.to_complete_relations(): |
|
484 |
rtype = rschema.type |
|
485 |
if self.relation_cached(rtype, role): |
|
486 |
continue |
|
487 |
var = varmaker.next() |
|
488 |
if role == 'subject': |
|
489 |
targettype = rschema.objects(self.e_schema)[0] |
|
490 |
card = rschema.rproperty(self.e_schema, targettype, |
|
491 |
'cardinality')[0] |
|
492 |
if card == '1': |
|
493 |
rql.append('%s %s %s' % (V, rtype, var)) |
|
494 |
else: # '?" |
|
495 |
rql.append('%s %s %s?' % (V, rtype, var)) |
|
496 |
else: |
|
497 |
targettype = rschema.subjects(self.e_schema)[1] |
|
498 |
card = rschema.rproperty(self.e_schema, targettype, |
|
499 |
'cardinality')[1] |
|
500 |
if card == '1': |
|
501 |
rql.append('%s %s %s' % (var, rtype, V)) |
|
502 |
else: # '?" |
|
503 |
rql.append('%s? %s %s' % (var, rtype, V)) |
|
504 |
assert card in '1?', '%s %s %s %s' % (self.e_schema, rtype, |
|
505 |
role, card) |
|
506 |
selected.append(((rtype, role), var)) |
|
507 |
if selected: |
|
508 |
# select V, we need it as the left most selected variable |
|
509 |
# if some outer join are included to fetch inlined relations |
|
510 |
rql = 'Any %s,%s %s' % (V, ','.join(var for attr, var in selected), |
|
511 |
','.join(rql)) |
|
512 |
execute = getattr(self.req, 'unsafe_execute', self.req.execute) |
|
513 |
rset = execute(rql, {'x': self.eid}, 'x', build_descr=False)[0] |
|
514 |
# handle attributes |
|
515 |
for i in xrange(1, lastattr): |
|
516 |
self[str(selected[i-1][0])] = rset[i] |
|
517 |
# handle relations |
|
518 |
for i in xrange(lastattr, len(rset)): |
|
2941
196493bd099c
[entity] use role instead of x
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2931
diff
changeset
|
519 |
rtype, role = selected[i-1][0] |
0 | 520 |
value = rset[i] |
521 |
if value is None: |
|
522 |
rrset = ResultSet([], rql, {'x': self.eid}) |
|
523 |
self.req.decorate_rset(rrset) |
|
524 |
else: |
|
525 |
rrset = self.req.eid_rset(value) |
|
2941
196493bd099c
[entity] use role instead of x
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2931
diff
changeset
|
526 |
self.set_related_cache(rtype, role, rrset) |
1474 | 527 |
|
0 | 528 |
def get_value(self, name): |
529 |
"""get value for the attribute relation <name>, query the repository |
|
530 |
to get the value if necessary. |
|
531 |
||
532 |
:type name: str |
|
533 |
:param name: name of the attribute to get |
|
534 |
""" |
|
535 |
try: |
|
536 |
value = self[name] |
|
537 |
except KeyError: |
|
538 |
if not self.is_saved(): |
|
539 |
return None |
|
540 |
rql = "Any A WHERE X eid %%(x)s, X %s A" % name |
|
2647
b0a2e779845c
enable server side entity caching, 25% speedup on codenaf insertion. ALL CW TESTS OK
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2613
diff
changeset
|
541 |
# XXX should we really use unsafe_execute here? I think so (syt), |
b0a2e779845c
enable server side entity caching, 25% speedup on codenaf insertion. ALL CW TESTS OK
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2613
diff
changeset
|
542 |
# see #344874 |
0 | 543 |
execute = getattr(self.req, 'unsafe_execute', self.req.execute) |
544 |
try: |
|
545 |
rset = execute(rql, {'x': self.eid}, 'x') |
|
546 |
except Unauthorized: |
|
547 |
self[name] = value = None |
|
548 |
else: |
|
549 |
assert rset.rowcount <= 1, (self, rql, rset.rowcount) |
|
550 |
try: |
|
551 |
self[name] = value = rset.rows[0][0] |
|
552 |
except IndexError: |
|
553 |
# probably a multisource error |
|
554 |
self.critical("can't get value for attribute %s of entity with eid %s", |
|
555 |
name, self.eid) |
|
556 |
if self.e_schema.destination(name) == 'String': |
|
2320 | 557 |
# XXX (syt) imo emtpy string is better |
0 | 558 |
self[name] = value = self.req._('unaccessible') |
559 |
else: |
|
560 |
self[name] = value = None |
|
561 |
return value |
|
562 |
||
563 |
def related(self, rtype, role='subject', limit=None, entities=False): |
|
564 |
"""returns a resultset of related entities |
|
1474 | 565 |
|
0 | 566 |
:param role: is the role played by 'self' in the relation ('subject' or 'object') |
567 |
:param limit: resultset's maximum size |
|
568 |
:param entities: if True, the entites are returned; if False, a result set is returned |
|
569 |
""" |
|
570 |
try: |
|
571 |
return self.related_cache(rtype, role, entities, limit) |
|
572 |
except KeyError: |
|
573 |
pass |
|
574 |
assert self.has_eid() |
|
575 |
rql = self.related_rql(rtype, role) |
|
2647
b0a2e779845c
enable server side entity caching, 25% speedup on codenaf insertion. ALL CW TESTS OK
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2613
diff
changeset
|
576 |
# XXX should we really use unsafe_execute here? I think so (syt), |
b0a2e779845c
enable server side entity caching, 25% speedup on codenaf insertion. ALL CW TESTS OK
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2613
diff
changeset
|
577 |
# see #344874 |
b0a2e779845c
enable server side entity caching, 25% speedup on codenaf insertion. ALL CW TESTS OK
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2613
diff
changeset
|
578 |
execute = getattr(self.req, 'unsafe_execute', self.req.execute) |
b0a2e779845c
enable server side entity caching, 25% speedup on codenaf insertion. ALL CW TESTS OK
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2613
diff
changeset
|
579 |
rset = execute(rql, {'x': self.eid}, 'x') |
0 | 580 |
self.set_related_cache(rtype, role, rset) |
581 |
return self.related(rtype, role, limit, entities) |
|
582 |
||
3130
2486163c4630
allow to specify targettypes in related_rql
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3047
diff
changeset
|
583 |
def related_rql(self, rtype, role='subject', targettypes=None): |
2818
326375561412
propagate some api changes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2807
diff
changeset
|
584 |
rschema = self.req.vreg.schema[rtype] |
0 | 585 |
if role == 'subject': |
3130
2486163c4630
allow to specify targettypes in related_rql
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3047
diff
changeset
|
586 |
if targettypes is None: |
2486163c4630
allow to specify targettypes in related_rql
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3047
diff
changeset
|
587 |
targettypes = rschema.objects(self.e_schema) |
0 | 588 |
restriction = 'E eid %%(x)s, E %s X' % rtype |
589 |
card = greater_card(rschema, (self.e_schema,), targettypes, 0) |
|
590 |
else: |
|
3130
2486163c4630
allow to specify targettypes in related_rql
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3047
diff
changeset
|
591 |
if targettypes is None: |
2486163c4630
allow to specify targettypes in related_rql
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3047
diff
changeset
|
592 |
targettypes = rschema.subjects(self.e_schema) |
0 | 593 |
restriction = 'E eid %%(x)s, X %s E' % rtype |
594 |
card = greater_card(rschema, targettypes, (self.e_schema,), 1) |
|
595 |
if len(targettypes) > 1: |
|
413
a7366dd3c33c
fix bug in entity.related_rql(): fetch_attr list / fetchorder weren't computed correctly
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
397
diff
changeset
|
596 |
fetchattrs_list = [] |
0 | 597 |
for ttype in targettypes: |
2650
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2647
diff
changeset
|
598 |
etypecls = self.vreg['etypes'].etype_class(ttype) |
413
a7366dd3c33c
fix bug in entity.related_rql(): fetch_attr list / fetchorder weren't computed correctly
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
397
diff
changeset
|
599 |
fetchattrs_list.append(set(etypecls.fetch_attrs)) |
a7366dd3c33c
fix bug in entity.related_rql(): fetch_attr list / fetchorder weren't computed correctly
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
397
diff
changeset
|
600 |
fetchattrs = reduce(set.intersection, fetchattrs_list) |
0 | 601 |
rql = etypecls.fetch_rql(self.req.user, [restriction], fetchattrs, |
602 |
settype=False) |
|
603 |
else: |
|
2650
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2647
diff
changeset
|
604 |
etypecls = self.vreg['etypes'].etype_class(targettypes[0]) |
0 | 605 |
rql = etypecls.fetch_rql(self.req.user, [restriction], settype=False) |
606 |
# optimisation: remove ORDERBY if cardinality is 1 or ? (though |
|
607 |
# greater_card return 1 for those both cases) |
|
608 |
if card == '1': |
|
609 |
if ' ORDERBY ' in rql: |
|
610 |
rql = '%s WHERE %s' % (rql.split(' ORDERBY ', 1)[0], |
|
611 |
rql.split(' WHERE ', 1)[1]) |
|
612 |
elif not ' ORDERBY ' in rql: |
|
613 |
args = tuple(rql.split(' WHERE ', 1)) |
|
614 |
rql = '%s ORDERBY Z DESC WHERE X modification_date Z, %s' % args |
|
615 |
return rql |
|
1474 | 616 |
|
0 | 617 |
# generic vocabulary methods ############################################## |
618 |
||
619 |
def unrelated_rql(self, rtype, targettype, role, ordermethod=None, |
|
620 |
vocabconstraints=True): |
|
621 |
"""build a rql to fetch `targettype` entities unrelated to this entity |
|
3241
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
622 |
using (rtype, role) relation. |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
623 |
|
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
624 |
Consider relation permissions so that returned entities may be actually |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
625 |
linked by `rtype`. |
0 | 626 |
""" |
627 |
ordermethod = ordermethod or 'fetch_unrelated_order' |
|
628 |
if isinstance(rtype, basestring): |
|
2818
326375561412
propagate some api changes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2807
diff
changeset
|
629 |
rtype = self.req.vreg.schema.rschema(rtype) |
0 | 630 |
if role == 'subject': |
631 |
evar, searchedvar = 'S', 'O' |
|
632 |
subjtype, objtype = self.e_schema, targettype |
|
633 |
else: |
|
634 |
searchedvar, evar = 'S', 'O' |
|
635 |
objtype, subjtype = self.e_schema, targettype |
|
636 |
if self.has_eid(): |
|
637 |
restriction = ['NOT S %s O' % rtype, '%s eid %%(x)s' % evar] |
|
3241
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
638 |
args = {'x': self.eid} |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
639 |
if role == 'subject': |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
640 |
securitycheck_args = {'fromeid': self.eid} |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
641 |
else: |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
642 |
securitycheck_args = {'toeid': self.eid} |
0 | 643 |
else: |
644 |
restriction = [] |
|
3241
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
645 |
args = {} |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
646 |
securitycheck_args = {} |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
647 |
insertsecurity = (rtype.has_local_role('add') and not |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
648 |
rtype.has_perm(self.req, 'add', **securitycheck_args)) |
0 | 649 |
constraints = rtype.rproperty(subjtype, objtype, 'constraints') |
650 |
if vocabconstraints: |
|
651 |
# RQLConstraint is a subclass for RQLVocabularyConstraint, so they |
|
652 |
# will be included as well |
|
653 |
restriction += [cstr.restriction for cstr in constraints |
|
654 |
if isinstance(cstr, RQLVocabularyConstraint)] |
|
655 |
else: |
|
656 |
restriction += [cstr.restriction for cstr in constraints |
|
657 |
if isinstance(cstr, RQLConstraint)] |
|
2650
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2647
diff
changeset
|
658 |
etypecls = self.vreg['etypes'].etype_class(targettype) |
0 | 659 |
rql = etypecls.fetch_rql(self.req.user, restriction, |
660 |
mainvar=searchedvar, ordermethod=ordermethod) |
|
661 |
# ensure we have an order defined |
|
662 |
if not ' ORDERBY ' in rql: |
|
663 |
before, after = rql.split(' WHERE ', 1) |
|
664 |
rql = '%s ORDERBY %s WHERE %s' % (before, searchedvar, after) |
|
3241
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
665 |
if insertsecurity: |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
666 |
rqlexprs = rtype.get_rqlexprs('add') |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
667 |
rewriter = RQLRewriter(self.req) |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
668 |
rqlst = self.req.vreg.parse(self.req, rql, args) |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
669 |
for select in rqlst.children: |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
670 |
rewriter.rewrite(select, [((searchedvar, searchedvar), rqlexprs)], |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
671 |
select.solutions, args) |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
672 |
rql = rqlst.as_string() |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
673 |
return rql, args |
1474 | 674 |
|
0 | 675 |
def unrelated(self, rtype, targettype, role='subject', limit=None, |
676 |
ordermethod=None): |
|
677 |
"""return a result set of target type objects that may be related |
|
678 |
by a given relation, with self as subject or object |
|
679 |
""" |
|
3241
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
680 |
try: |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
681 |
rql, args = self.unrelated_rql(rtype, targettype, role, ordermethod) |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
682 |
except Unauthorized: |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
683 |
return self.req.empty_rset() |
0 | 684 |
if limit is not None: |
685 |
before, after = rql.split(' WHERE ', 1) |
|
686 |
rql = '%s LIMIT %s WHERE %s' % (before, limit, after) |
|
3245 | 687 |
return self.req.execute(rql, args, tuple(args)) |
1474 | 688 |
|
0 | 689 |
# relations cache handling ################################################ |
1474 | 690 |
|
0 | 691 |
def relation_cached(self, rtype, role): |
692 |
"""return true if the given relation is already cached on the instance |
|
693 |
""" |
|
2647
b0a2e779845c
enable server side entity caching, 25% speedup on codenaf insertion. ALL CW TESTS OK
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2613
diff
changeset
|
694 |
return self._related_cache.get('%s_%s' % (rtype, role)) |
1474 | 695 |
|
0 | 696 |
def related_cache(self, rtype, role, entities=True, limit=None): |
697 |
"""return values for the given relation if it's cached on the instance, |
|
698 |
else raise `KeyError` |
|
699 |
""" |
|
700 |
res = self._related_cache['%s_%s' % (rtype, role)][entities] |
|
701 |
if limit: |
|
702 |
if entities: |
|
703 |
res = res[:limit] |
|
704 |
else: |
|
705 |
res = res.limit(limit) |
|
706 |
return res |
|
1474 | 707 |
|
0 | 708 |
def set_related_cache(self, rtype, role, rset, col=0): |
709 |
"""set cached values for the given relation""" |
|
710 |
if rset: |
|
711 |
related = list(rset.entities(col)) |
|
2818
326375561412
propagate some api changes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2807
diff
changeset
|
712 |
rschema = self.req.vreg.schema.rschema(rtype) |
0 | 713 |
if role == 'subject': |
714 |
rcard = rschema.rproperty(self.e_schema, related[0].e_schema, |
|
715 |
'cardinality')[1] |
|
716 |
target = 'object' |
|
717 |
else: |
|
718 |
rcard = rschema.rproperty(related[0].e_schema, self.e_schema, |
|
719 |
'cardinality')[0] |
|
720 |
target = 'subject' |
|
721 |
if rcard in '?1': |
|
722 |
for rentity in related: |
|
723 |
rentity._related_cache['%s_%s' % (rtype, target)] = (self.as_rset(), [self]) |
|
724 |
else: |
|
725 |
related = [] |
|
726 |
self._related_cache['%s_%s' % (rtype, role)] = (rset, related) |
|
1474 | 727 |
|
0 | 728 |
def clear_related_cache(self, rtype=None, role=None): |
729 |
"""clear cached values for the given relation or the entire cache if |
|
730 |
no relation is given |
|
731 |
""" |
|
732 |
if rtype is None: |
|
733 |
self._related_cache = {} |
|
734 |
else: |
|
735 |
assert role |
|
736 |
self._related_cache.pop('%s_%s' % (rtype, role), None) |
|
1474 | 737 |
|
2942
77ebdbe93cf8
[entity] generic clear_all_caches methods, to use in test
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2941
diff
changeset
|
738 |
def clear_all_caches(self): |
77ebdbe93cf8
[entity] generic clear_all_caches methods, to use in test
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2941
diff
changeset
|
739 |
self.clear() |
77ebdbe93cf8
[entity] generic clear_all_caches methods, to use in test
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2941
diff
changeset
|
740 |
for rschema, _, role in self.e_schema.relation_definitions(): |
77ebdbe93cf8
[entity] generic clear_all_caches methods, to use in test
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2941
diff
changeset
|
741 |
self.clear_related_cache(rschema.type, role) |
77ebdbe93cf8
[entity] generic clear_all_caches methods, to use in test
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2941
diff
changeset
|
742 |
|
0 | 743 |
# raw edition utilities ################################################### |
1474 | 744 |
|
2877
e469f3602858
new _cw_unsafe argument to Entity.set_attributes until something nicer is done (eg #344874)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2875
diff
changeset
|
745 |
def set_attributes(self, _cw_unsafe=False, **kwargs): |
0 | 746 |
assert kwargs |
747 |
relations = [] |
|
748 |
for key in kwargs: |
|
749 |
relations.append('X %s %%(%s)s' % (key, key)) |
|
397
cf577e26f924
don't introduce a spurious 'x' key in the entity-as dict
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
237
diff
changeset
|
750 |
# update current local object |
cf577e26f924
don't introduce a spurious 'x' key in the entity-as dict
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
237
diff
changeset
|
751 |
self.update(kwargs) |
cf577e26f924
don't introduce a spurious 'x' key in the entity-as dict
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
237
diff
changeset
|
752 |
# and now update the database |
0 | 753 |
kwargs['x'] = self.eid |
2877
e469f3602858
new _cw_unsafe argument to Entity.set_attributes until something nicer is done (eg #344874)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2875
diff
changeset
|
754 |
if _cw_unsafe: |
e469f3602858
new _cw_unsafe argument to Entity.set_attributes until something nicer is done (eg #344874)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2875
diff
changeset
|
755 |
self.req.unsafe_execute( |
e469f3602858
new _cw_unsafe argument to Entity.set_attributes until something nicer is done (eg #344874)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2875
diff
changeset
|
756 |
'SET %s WHERE X eid %%(x)s' % ','.join(relations), kwargs, 'x') |
e469f3602858
new _cw_unsafe argument to Entity.set_attributes until something nicer is done (eg #344874)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2875
diff
changeset
|
757 |
else: |
e469f3602858
new _cw_unsafe argument to Entity.set_attributes until something nicer is done (eg #344874)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2875
diff
changeset
|
758 |
self.req.execute('SET %s WHERE X eid %%(x)s' % ','.join(relations), |
e469f3602858
new _cw_unsafe argument to Entity.set_attributes until something nicer is done (eg #344874)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2875
diff
changeset
|
759 |
kwargs, 'x') |
1474 | 760 |
|
0 | 761 |
def delete(self): |
762 |
assert self.has_eid(), self.eid |
|
763 |
self.req.execute('DELETE %s X WHERE X eid %%(x)s' % self.e_schema, |
|
764 |
{'x': self.eid}) |
|
1474 | 765 |
|
0 | 766 |
# server side utilities ################################################### |
1474 | 767 |
|
0 | 768 |
def set_defaults(self): |
769 |
"""set default values according to the schema""" |
|
770 |
self._default_set = set() |
|
771 |
for attr, value in self.e_schema.defaults(): |
|
772 |
if not self.has_key(attr): |
|
773 |
self[str(attr)] = value |
|
774 |
self._default_set.add(attr) |
|
775 |
||
776 |
def check(self, creation=False): |
|
777 |
"""check this entity against its schema. Only final relation |
|
778 |
are checked here, constraint on actual relations are checked in hooks |
|
779 |
""" |
|
780 |
# necessary since eid is handled specifically and yams require it to be |
|
781 |
# in the dictionary |
|
782 |
if self.req is None: |
|
783 |
_ = unicode |
|
784 |
else: |
|
785 |
_ = self.req._ |
|
786 |
self.e_schema.check(self, creation=creation, _=_) |
|
787 |
||
788 |
def fti_containers(self, _done=None): |
|
789 |
if _done is None: |
|
790 |
_done = set() |
|
791 |
_done.add(self.eid) |
|
792 |
containers = tuple(self.e_schema.fulltext_containers()) |
|
793 |
if containers: |
|
476
62968fa8845c
yield self if no ft container found
sylvain.thenault@logilab.fr
parents:
475
diff
changeset
|
794 |
yielded = False |
0 | 795 |
for rschema, target in containers: |
796 |
if target == 'object': |
|
797 |
targets = getattr(self, rschema.type) |
|
798 |
else: |
|
799 |
targets = getattr(self, 'reverse_%s' % rschema) |
|
800 |
for entity in targets: |
|
801 |
if entity.eid in _done: |
|
802 |
continue |
|
803 |
for container in entity.fti_containers(_done): |
|
804 |
yield container |
|
476
62968fa8845c
yield self if no ft container found
sylvain.thenault@logilab.fr
parents:
475
diff
changeset
|
805 |
yielded = True |
62968fa8845c
yield self if no ft container found
sylvain.thenault@logilab.fr
parents:
475
diff
changeset
|
806 |
if not yielded: |
62968fa8845c
yield self if no ft container found
sylvain.thenault@logilab.fr
parents:
475
diff
changeset
|
807 |
yield self |
0 | 808 |
else: |
809 |
yield self |
|
1474 | 810 |
|
0 | 811 |
def get_words(self): |
812 |
"""used by the full text indexer to get words to index |
|
813 |
||
814 |
this method should only be used on the repository side since it depends |
|
815 |
on the indexer package |
|
1474 | 816 |
|
0 | 817 |
:rtype: list |
818 |
:return: the list of indexable word of this entity |
|
819 |
""" |
|
820 |
from indexer.query_objects import tokenize |
|
821 |
words = [] |
|
822 |
for rschema in self.e_schema.indexable_attributes(): |
|
823 |
try: |
|
824 |
value = self.printable_value(rschema, format='text/plain') |
|
1132 | 825 |
except TransformError: |
0 | 826 |
continue |
827 |
except: |
|
828 |
self.exception("can't add value of %s to text index for entity %s", |
|
829 |
rschema, self.eid) |
|
830 |
continue |
|
831 |
if value: |
|
832 |
words += tokenize(value) |
|
1474 | 833 |
|
0 | 834 |
for rschema, role in self.e_schema.fulltext_relations(): |
835 |
if role == 'subject': |
|
836 |
for entity in getattr(self, rschema.type): |
|
837 |
words += entity.get_words() |
|
838 |
else: # if role == 'object': |
|
839 |
for entity in getattr(self, 'reverse_%s' % rschema.type): |
|
840 |
words += entity.get_words() |
|
841 |
return words |
|
842 |
||
3245 | 843 |
@deprecated('[3.2] see new form api') |
844 |
def vocabulary(self, rtype, role='subject', limit=None): |
|
845 |
"""vocabulary functions must return a list of couples |
|
846 |
(label, eid) that will typically be used to fill the |
|
847 |
edition view's combobox. |
|
848 |
||
849 |
If `eid` is None in one of these couples, it should be |
|
850 |
interpreted as a separator in case vocabulary results are grouped |
|
851 |
""" |
|
852 |
from logilab.common.testlib import mock_object |
|
853 |
form = self.vreg.select('forms', 'edition', self.req, entity=self) |
|
854 |
field = mock_object(name=rtype, role=role) |
|
855 |
return form.form_field_vocabulary(field, limit) |
|
856 |
||
0 | 857 |
|
858 |
# attribute and relation descriptors ########################################## |
|
859 |
||
860 |
class Attribute(object): |
|
861 |
"""descriptor that controls schema attribute access""" |
|
862 |
||
863 |
def __init__(self, attrname): |
|
864 |
assert attrname != 'eid' |
|
865 |
self._attrname = attrname |
|
866 |
||
867 |
def __get__(self, eobj, eclass): |
|
868 |
if eobj is None: |
|
869 |
return self |
|
870 |
return eobj.get_value(self._attrname) |
|
871 |
||
872 |
def __set__(self, eobj, value): |
|
873 |
eobj[self._attrname] = value |
|
2875
b7399ef8b3e0
towards better edited attributes handling
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2872
diff
changeset
|
874 |
if hasattr(eobj, 'edited_attributes'): |
b7399ef8b3e0
towards better edited attributes handling
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2872
diff
changeset
|
875 |
eobj.edited_attributes.add(self._attrname) |
0 | 876 |
|
877 |
class Relation(object): |
|
878 |
"""descriptor that controls schema relation access""" |
|
879 |
_role = None # for pylint |
|
880 |
||
881 |
def __init__(self, rschema): |
|
882 |
self._rschema = rschema |
|
883 |
self._rtype = rschema.type |
|
884 |
||
885 |
def __get__(self, eobj, eclass): |
|
886 |
if eobj is None: |
|
887 |
raise AttributeError('%s cannot be only be accessed from instances' |
|
888 |
% self._rtype) |
|
889 |
return eobj.related(self._rtype, self._role, entities=True) |
|
1474 | 890 |
|
0 | 891 |
def __set__(self, eobj, value): |
892 |
raise NotImplementedError |
|
893 |
||
894 |
||
895 |
class SubjectRelation(Relation): |
|
896 |
"""descriptor that controls schema relation access""" |
|
897 |
_role = 'subject' |
|
1474 | 898 |
|
0 | 899 |
class ObjectRelation(Relation): |
900 |
"""descriptor that controls schema relation access""" |
|
901 |
_role = 'object' |
|
902 |
||
903 |
from logging import getLogger |
|
904 |
from cubicweb import set_log_methods |
|
905 |
set_log_methods(Entity, getLogger('cubicweb.entity')) |