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