author | Adrien Di Mascio <Adrien.DiMascio@logilab.fr> |
Thu, 24 Sep 2009 20:25:49 +0200 | |
changeset 3462 | 3a79fecdd2b4 |
parent 3459 | e134d2dd9992 |
child 3589 | a5432f99f2d9 |
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 |
""" |
|
3376
f5c69485381f
[appobjects] use __regid__ instead of __id__, more explicit
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3369
diff
changeset
|
81 |
etype = cls.__regid__ |
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: |
|
3376
f5c69485381f
[appobjects] use __regid__ instead of __id__, more explicit
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3369
diff
changeset
|
112 |
restrictions.append('%s is %s' % (mainvar, cls.__regid__)) |
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)', |
|
3376
f5c69485381f
[appobjects] use __regid__ instead of __id__, more explicit
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3369
diff
changeset
|
145 |
attr, cls.__regid__) |
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 |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
169 |
destcls = user._cw.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): |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
250 |
res = dict(zip(('type', 'source', 'extid'), self._cw.describe(self.eid))) |
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
251 |
res['source'] = self._cw.source_defs()[res['source']] |
0 | 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): |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
256 |
self._cw.local_perm_cache.pop((rqlexpr.eid, (('x', self.eid),)), None) |
475
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): |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
259 |
self.e_schema.check_perm(self._cw, action, self.eid) |
0 | 260 |
|
261 |
def has_perm(self, action): |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
262 |
return self.e_schema.has_perm(self._cw, 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""" |
3459
e134d2dd9992
[entity] pass cw_row and cw_col to select(vid, ...) in self.view
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
3452
diff
changeset
|
266 |
view = self._cw.vreg[__registry].select(vid, self._cw, rset=self.cw_rset, |
e134d2dd9992
[entity] pass cw_row and cw_col to select(vid, ...) in self.view
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
3452
diff
changeset
|
267 |
row=self.cw_row, col=self.cw_col, |
e134d2dd9992
[entity] pass cw_row and cw_col to select(vid, ...) in self.view
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
3452
diff
changeset
|
268 |
**kwargs) |
3418
7b49fa7e942d
[api] use _cw, cw_row, cw_col, cw_rset etc.
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
3405
diff
changeset
|
269 |
return view.render(row=self.cw_row, col=self.cw_col, **kwargs) |
0 | 270 |
|
2059
af33833d7571
absolute_url / build_url refactoring to avoid potential name clash
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2058
diff
changeset
|
271 |
def absolute_url(self, *args, **kwargs): |
0 | 272 |
"""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
|
273 |
# 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
|
274 |
# 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
|
275 |
if args: |
af33833d7571
absolute_url / build_url refactoring to avoid potential name clash
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2058
diff
changeset
|
276 |
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
|
277 |
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
|
278 |
else: |
af33833d7571
absolute_url / build_url refactoring to avoid potential name clash
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2058
diff
changeset
|
279 |
method = None |
0 | 280 |
# in linksearch mode, we don't want external urls else selecting |
281 |
# the object for use in the relation is tricky |
|
282 |
# XXX search_state is web specific |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
283 |
if getattr(self._cw, 'search_state', ('normal',))[0] == 'normal': |
0 | 284 |
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
|
285 |
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
|
286 |
try: |
c7a22540d6f7
add some bw compat code for old rest_path prototype
sylvain.thenault@logilab.fr
parents:
1840
diff
changeset
|
287 |
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
|
288 |
except TypeError: |
3405
9d31c9cb8103
nicer deprecation warnings
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3382
diff
changeset
|
289 |
warn('[3.4] %s: rest_path() now take use_ext_eid argument, ' |
3376
f5c69485381f
[appobjects] use __regid__ instead of __id__, more explicit
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3369
diff
changeset
|
290 |
'please update' % self.__regid__, DeprecationWarning) |
1842
c7a22540d6f7
add some bw compat code for old rest_path prototype
sylvain.thenault@logilab.fr
parents:
1840
diff
changeset
|
291 |
kwargs['_restpath'] = self.rest_path() |
0 | 292 |
else: |
293 |
kwargs['rql'] = 'Any X WHERE X eid %s' % self.eid |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
294 |
return self._cw.build_url(method, **kwargs) |
0 | 295 |
|
1840
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
296 |
def rest_path(self, use_ext_eid=False): |
0 | 297 |
"""returns a REST-like (relative) path for this entity""" |
298 |
mainattr, needcheck = self._rest_attr_info() |
|
299 |
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
|
300 |
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
|
301 |
if mainattr != 'eid': |
0 | 302 |
value = getattr(self, mainattr) |
2125
19861294506f
https://www.logilab.net/cwo/ticket/343724
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2005
diff
changeset
|
303 |
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
|
304 |
mainattr = 'eid' |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
305 |
path += '/eid' |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
306 |
elif needcheck: |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
307 |
# 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
|
308 |
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
|
309 |
etype, mainattr) |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
310 |
nbresults = self._cw.execute(rql, {'value' : value})[0][0] |
1904
e23536d29231
minor refactoring of absolute_url()
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
1842
diff
changeset
|
311 |
if nbresults != 1: # ambiguity? |
e23536d29231
minor refactoring of absolute_url()
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
1842
diff
changeset
|
312 |
mainattr = 'eid' |
e23536d29231
minor refactoring of absolute_url()
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
1842
diff
changeset
|
313 |
path += '/eid' |
0 | 314 |
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
|
315 |
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
|
316 |
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
|
317 |
else: |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
318 |
value = self.eid |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
319 |
return '%s/%s' % (path, self._cw.url_quote(value)) |
0 | 320 |
|
1360
13ae1121835e
rename attribute_metadata method to attr_metadata to save a few chars
sylvain.thenault@logilab.fr
parents:
1313
diff
changeset
|
321 |
def attr_metadata(self, attr, metadata): |
1101
0c067de38e46
unification of meta-attributes handling:
sylvain.thenault@logilab.fr
parents:
1098
diff
changeset
|
322 |
"""return a metadata for an attribute (None if unspecified)""" |
0c067de38e46
unification of meta-attributes handling:
sylvain.thenault@logilab.fr
parents:
1098
diff
changeset
|
323 |
value = getattr(self, '%s_%s' % (attr, metadata), None) |
0c067de38e46
unification of meta-attributes handling:
sylvain.thenault@logilab.fr
parents:
1098
diff
changeset
|
324 |
if value is None and metadata == 'encoding': |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
325 |
value = self._cw.vreg.property_value('ui.encoding') |
1101
0c067de38e46
unification of meta-attributes handling:
sylvain.thenault@logilab.fr
parents:
1098
diff
changeset
|
326 |
return value |
0 | 327 |
|
328 |
def printable_value(self, attr, value=_marker, attrtype=None, |
|
329 |
format='text/html', displaytime=True): |
|
330 |
"""return a displayable value (i.e. unicode string) which may contains |
|
331 |
html tags |
|
332 |
""" |
|
333 |
attr = str(attr) |
|
334 |
if value is _marker: |
|
335 |
value = getattr(self, attr) |
|
336 |
if isinstance(value, basestring): |
|
337 |
value = value.strip() |
|
338 |
if value is None or value == '': # don't use "not", 0 is an acceptable value |
|
339 |
return u'' |
|
340 |
if attrtype is None: |
|
341 |
attrtype = self.e_schema.destination(attr) |
|
342 |
props = self.e_schema.rproperties(attr) |
|
343 |
if attrtype == 'String': |
|
344 |
# internalinalized *and* formatted string such as schema |
|
345 |
# description... |
|
346 |
if props.get('internationalizable'): |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
347 |
value = self._cw._(value) |
1360
13ae1121835e
rename attribute_metadata method to attr_metadata to save a few chars
sylvain.thenault@logilab.fr
parents:
1313
diff
changeset
|
348 |
attrformat = self.attr_metadata(attr, 'format') |
0 | 349 |
if attrformat: |
350 |
return self.mtc_transform(value, attrformat, format, |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
351 |
self._cw.encoding) |
0 | 352 |
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
|
353 |
attrformat = self.attr_metadata(attr, 'format') |
0 | 354 |
if attrformat: |
1360
13ae1121835e
rename attribute_metadata method to attr_metadata to save a few chars
sylvain.thenault@logilab.fr
parents:
1313
diff
changeset
|
355 |
encoding = self.attr_metadata(attr, 'encoding') |
0 | 356 |
return self.mtc_transform(value.getvalue(), attrformat, format, |
357 |
encoding) |
|
358 |
return u'' |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
359 |
value = printable_value(self._cw, attrtype, value, props, |
3212
07d11bacfefe
displaytime attribute should not have been removed from there
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3184
diff
changeset
|
360 |
displaytime=displaytime) |
0 | 361 |
if format == 'text/html': |
2312
af4d8f75c5db
use xml_escape
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2125
diff
changeset
|
362 |
value = xml_escape(value) |
0 | 363 |
return value |
364 |
||
365 |
def mtc_transform(self, data, format, target_format, encoding, |
|
366 |
_engine=ENGINE): |
|
367 |
trdata = TransformData(data, format, encoding, appobject=self) |
|
368 |
data = _engine.convert(trdata, target_format).decode() |
|
369 |
if format == 'text/html': |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
370 |
data = soup2xhtml(data, self._cw.encoding) |
0 | 371 |
return data |
1474 | 372 |
|
0 | 373 |
# entity cloning ########################################################## |
374 |
||
375 |
def copy_relations(self, ceid): |
|
376 |
"""copy relations of the object with the given eid on this object |
|
377 |
||
378 |
By default meta and composite relations are skipped. |
|
379 |
Overrides this if you want another behaviour |
|
380 |
""" |
|
381 |
assert self.has_eid() |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
382 |
execute = self._cw.execute |
0 | 383 |
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
|
384 |
if rschema.is_final() or rschema.meta: |
0 | 385 |
continue |
386 |
# skip already defined relations |
|
387 |
if getattr(self, rschema.type): |
|
388 |
continue |
|
389 |
if rschema.type in self.skip_copy_for: |
|
390 |
continue |
|
391 |
# skip composite relation |
|
392 |
if self.e_schema.subjrproperty(rschema, 'composite'): |
|
393 |
continue |
|
394 |
# skip relation with card in ?1 else we either change the copied |
|
395 |
# object (inlined relation) or inserting some inconsistency |
|
396 |
if self.e_schema.subjrproperty(rschema, 'cardinality')[1] in '?1': |
|
397 |
continue |
|
398 |
rql = 'SET X %s V WHERE X eid %%(x)s, Y eid %%(y)s, Y %s V' % ( |
|
399 |
rschema.type, rschema.type) |
|
400 |
execute(rql, {'x': self.eid, 'y': ceid}, ('x', 'y')) |
|
401 |
self.clear_related_cache(rschema.type, 'subject') |
|
402 |
for rschema in self.e_schema.object_relations(): |
|
403 |
if rschema.meta: |
|
404 |
continue |
|
405 |
# skip already defined relations |
|
406 |
if getattr(self, 'reverse_%s' % rschema.type): |
|
407 |
continue |
|
408 |
# skip composite relation |
|
409 |
if self.e_schema.objrproperty(rschema, 'composite'): |
|
410 |
continue |
|
411 |
# skip relation with card in ?1 else we either change the copied |
|
412 |
# object (inlined relation) or inserting some inconsistency |
|
413 |
if self.e_schema.objrproperty(rschema, 'cardinality')[0] in '?1': |
|
414 |
continue |
|
415 |
rql = 'SET V %s X WHERE X eid %%(x)s, Y eid %%(y)s, V %s Y' % ( |
|
416 |
rschema.type, rschema.type) |
|
417 |
execute(rql, {'x': self.eid, 'y': ceid}, ('x', 'y')) |
|
418 |
self.clear_related_cache(rschema.type, 'object') |
|
419 |
||
420 |
# data fetching methods ################################################### |
|
421 |
||
422 |
@cached |
|
423 |
def as_rset(self): |
|
424 |
"""returns a resultset containing `self` information""" |
|
425 |
rset = ResultSet([(self.eid,)], 'Any X WHERE X eid %(x)s', |
|
3376
f5c69485381f
[appobjects] use __regid__ instead of __id__, more explicit
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3369
diff
changeset
|
426 |
{'x': self.eid}, [(self.__regid__,)]) |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
427 |
return self._cw.decorate_rset(rset) |
1474 | 428 |
|
0 | 429 |
def to_complete_relations(self): |
430 |
"""by default complete final relations to when calling .complete()""" |
|
431 |
for rschema in self.e_schema.subject_relations(): |
|
432 |
if rschema.is_final(): |
|
433 |
continue |
|
434 |
if len(rschema.objects(self.e_schema)) > 1: |
|
435 |
# ambigous relations, the querier doesn't handle |
|
436 |
# outer join correctly in this case |
|
437 |
continue |
|
438 |
if rschema.inlined: |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
439 |
matching_groups = self._cw.user.matching_groups |
0 | 440 |
if matching_groups(rschema.get_groups('read')) and \ |
441 |
all(matching_groups(es.get_groups('read')) |
|
442 |
for es in rschema.objects(self.e_schema)): |
|
443 |
yield rschema, 'subject' |
|
1474 | 444 |
|
0 | 445 |
def to_complete_attributes(self, skip_bytes=True): |
446 |
for rschema, attrschema in self.e_schema.attribute_definitions(): |
|
447 |
# skip binary data by default |
|
448 |
if skip_bytes and attrschema.type == 'Bytes': |
|
449 |
continue |
|
450 |
attr = rschema.type |
|
451 |
if attr == 'eid': |
|
452 |
continue |
|
453 |
# password retreival is blocked at the repository server level |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
454 |
if not self._cw.user.matching_groups(rschema.get_groups('read')) \ |
0 | 455 |
or attrschema.type == 'Password': |
456 |
self[attr] = None |
|
457 |
continue |
|
458 |
yield attr |
|
1474 | 459 |
|
0 | 460 |
def complete(self, attributes=None, skip_bytes=True): |
461 |
"""complete this entity by adding missing attributes (i.e. query the |
|
462 |
repository to fill the entity) |
|
463 |
||
464 |
:type skip_bytes: bool |
|
465 |
:param skip_bytes: |
|
466 |
if true, attribute of type Bytes won't be considered |
|
467 |
""" |
|
468 |
assert self.has_eid() |
|
469 |
varmaker = rqlvar_maker() |
|
470 |
V = varmaker.next() |
|
471 |
rql = ['WHERE %s eid %%(x)s' % V] |
|
472 |
selected = [] |
|
473 |
for attr in (attributes or self.to_complete_attributes(skip_bytes)): |
|
474 |
# if attribute already in entity, nothing to do |
|
475 |
if self.has_key(attr): |
|
476 |
continue |
|
477 |
# case where attribute must be completed, but is not yet in entity |
|
478 |
var = varmaker.next() |
|
479 |
rql.append('%s %s %s' % (V, attr, var)) |
|
480 |
selected.append((attr, var)) |
|
481 |
# +1 since this doen't include the main variable |
|
482 |
lastattr = len(selected) + 1 |
|
483 |
if attributes is None: |
|
484 |
# fetch additional relations (restricted to 0..1 relations) |
|
485 |
for rschema, role in self.to_complete_relations(): |
|
486 |
rtype = rschema.type |
|
487 |
if self.relation_cached(rtype, role): |
|
488 |
continue |
|
489 |
var = varmaker.next() |
|
490 |
if role == 'subject': |
|
491 |
targettype = rschema.objects(self.e_schema)[0] |
|
492 |
card = rschema.rproperty(self.e_schema, targettype, |
|
493 |
'cardinality')[0] |
|
494 |
if card == '1': |
|
495 |
rql.append('%s %s %s' % (V, rtype, var)) |
|
496 |
else: # '?" |
|
497 |
rql.append('%s %s %s?' % (V, rtype, var)) |
|
498 |
else: |
|
499 |
targettype = rschema.subjects(self.e_schema)[1] |
|
500 |
card = rschema.rproperty(self.e_schema, targettype, |
|
501 |
'cardinality')[1] |
|
502 |
if card == '1': |
|
503 |
rql.append('%s %s %s' % (var, rtype, V)) |
|
504 |
else: # '?" |
|
505 |
rql.append('%s? %s %s' % (var, rtype, V)) |
|
506 |
assert card in '1?', '%s %s %s %s' % (self.e_schema, rtype, |
|
507 |
role, card) |
|
508 |
selected.append(((rtype, role), var)) |
|
509 |
if selected: |
|
510 |
# select V, we need it as the left most selected variable |
|
511 |
# if some outer join are included to fetch inlined relations |
|
512 |
rql = 'Any %s,%s %s' % (V, ','.join(var for attr, var in selected), |
|
513 |
','.join(rql)) |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
514 |
execute = getattr(self._cw, 'unsafe_execute', self._cw.execute) |
0 | 515 |
rset = execute(rql, {'x': self.eid}, 'x', build_descr=False)[0] |
516 |
# handle attributes |
|
517 |
for i in xrange(1, lastattr): |
|
518 |
self[str(selected[i-1][0])] = rset[i] |
|
519 |
# handle relations |
|
520 |
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
|
521 |
rtype, role = selected[i-1][0] |
0 | 522 |
value = rset[i] |
523 |
if value is None: |
|
524 |
rrset = ResultSet([], rql, {'x': self.eid}) |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
525 |
self._cw.decorate_rset(rrset) |
0 | 526 |
else: |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
527 |
rrset = self._cw.eid_rset(value) |
2941
196493bd099c
[entity] use role instead of x
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2931
diff
changeset
|
528 |
self.set_related_cache(rtype, role, rrset) |
1474 | 529 |
|
0 | 530 |
def get_value(self, name): |
531 |
"""get value for the attribute relation <name>, query the repository |
|
532 |
to get the value if necessary. |
|
533 |
||
534 |
:type name: str |
|
535 |
:param name: name of the attribute to get |
|
536 |
""" |
|
537 |
try: |
|
538 |
value = self[name] |
|
539 |
except KeyError: |
|
540 |
if not self.is_saved(): |
|
541 |
return None |
|
542 |
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
|
543 |
# 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
|
544 |
# see #344874 |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
545 |
execute = getattr(self._cw, 'unsafe_execute', self._cw.execute) |
0 | 546 |
try: |
547 |
rset = execute(rql, {'x': self.eid}, 'x') |
|
548 |
except Unauthorized: |
|
549 |
self[name] = value = None |
|
550 |
else: |
|
551 |
assert rset.rowcount <= 1, (self, rql, rset.rowcount) |
|
552 |
try: |
|
553 |
self[name] = value = rset.rows[0][0] |
|
554 |
except IndexError: |
|
555 |
# probably a multisource error |
|
556 |
self.critical("can't get value for attribute %s of entity with eid %s", |
|
557 |
name, self.eid) |
|
558 |
if self.e_schema.destination(name) == 'String': |
|
2320 | 559 |
# XXX (syt) imo emtpy string is better |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
560 |
self[name] = value = self._cw._('unaccessible') |
0 | 561 |
else: |
562 |
self[name] = value = None |
|
563 |
return value |
|
564 |
||
565 |
def related(self, rtype, role='subject', limit=None, entities=False): |
|
566 |
"""returns a resultset of related entities |
|
1474 | 567 |
|
0 | 568 |
:param role: is the role played by 'self' in the relation ('subject' or 'object') |
569 |
:param limit: resultset's maximum size |
|
570 |
:param entities: if True, the entites are returned; if False, a result set is returned |
|
571 |
""" |
|
572 |
try: |
|
573 |
return self.related_cache(rtype, role, entities, limit) |
|
574 |
except KeyError: |
|
575 |
pass |
|
576 |
assert self.has_eid() |
|
577 |
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
|
578 |
# 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
|
579 |
# see #344874 |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
580 |
execute = getattr(self._cw, 'unsafe_execute', self._cw.execute) |
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
|
581 |
rset = execute(rql, {'x': self.eid}, 'x') |
0 | 582 |
self.set_related_cache(rtype, role, rset) |
583 |
return self.related(rtype, role, limit, entities) |
|
584 |
||
3130
2486163c4630
allow to specify targettypes in related_rql
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3047
diff
changeset
|
585 |
def related_rql(self, rtype, role='subject', targettypes=None): |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
586 |
rschema = self._cw.vreg.schema[rtype] |
0 | 587 |
if role == 'subject': |
3130
2486163c4630
allow to specify targettypes in related_rql
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3047
diff
changeset
|
588 |
if targettypes is None: |
2486163c4630
allow to specify targettypes in related_rql
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3047
diff
changeset
|
589 |
targettypes = rschema.objects(self.e_schema) |
0 | 590 |
restriction = 'E eid %%(x)s, E %s X' % rtype |
591 |
card = greater_card(rschema, (self.e_schema,), targettypes, 0) |
|
592 |
else: |
|
3130
2486163c4630
allow to specify targettypes in related_rql
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3047
diff
changeset
|
593 |
if targettypes is None: |
2486163c4630
allow to specify targettypes in related_rql
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3047
diff
changeset
|
594 |
targettypes = rschema.subjects(self.e_schema) |
0 | 595 |
restriction = 'E eid %%(x)s, X %s E' % rtype |
596 |
card = greater_card(rschema, targettypes, (self.e_schema,), 1) |
|
597 |
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
|
598 |
fetchattrs_list = [] |
0 | 599 |
for ttype in targettypes: |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
600 |
etypecls = self._cw.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
|
601 |
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
|
602 |
fetchattrs = reduce(set.intersection, fetchattrs_list) |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
603 |
rql = etypecls.fetch_rql(self._cw.user, [restriction], fetchattrs, |
0 | 604 |
settype=False) |
605 |
else: |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
606 |
etypecls = self._cw.vreg['etypes'].etype_class(targettypes[0]) |
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
607 |
rql = etypecls.fetch_rql(self._cw.user, [restriction], settype=False) |
0 | 608 |
# optimisation: remove ORDERBY if cardinality is 1 or ? (though |
609 |
# greater_card return 1 for those both cases) |
|
610 |
if card == '1': |
|
611 |
if ' ORDERBY ' in rql: |
|
612 |
rql = '%s WHERE %s' % (rql.split(' ORDERBY ', 1)[0], |
|
613 |
rql.split(' WHERE ', 1)[1]) |
|
614 |
elif not ' ORDERBY ' in rql: |
|
615 |
args = tuple(rql.split(' WHERE ', 1)) |
|
616 |
rql = '%s ORDERBY Z DESC WHERE X modification_date Z, %s' % args |
|
617 |
return rql |
|
1474 | 618 |
|
0 | 619 |
# generic vocabulary methods ############################################## |
620 |
||
621 |
def unrelated_rql(self, rtype, targettype, role, ordermethod=None, |
|
622 |
vocabconstraints=True): |
|
623 |
"""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
|
624 |
using (rtype, role) relation. |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
625 |
|
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
626 |
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
|
627 |
linked by `rtype`. |
0 | 628 |
""" |
629 |
ordermethod = ordermethod or 'fetch_unrelated_order' |
|
630 |
if isinstance(rtype, basestring): |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
631 |
rtype = self._cw.vreg.schema.rschema(rtype) |
0 | 632 |
if role == 'subject': |
633 |
evar, searchedvar = 'S', 'O' |
|
634 |
subjtype, objtype = self.e_schema, targettype |
|
635 |
else: |
|
636 |
searchedvar, evar = 'S', 'O' |
|
637 |
objtype, subjtype = self.e_schema, targettype |
|
638 |
if self.has_eid(): |
|
639 |
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
|
640 |
args = {'x': self.eid} |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
641 |
if role == 'subject': |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
642 |
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
|
643 |
else: |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
644 |
securitycheck_args = {'toeid': self.eid} |
0 | 645 |
else: |
646 |
restriction = [] |
|
3241
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
647 |
args = {} |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
648 |
securitycheck_args = {} |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
649 |
insertsecurity = (rtype.has_local_role('add') and not |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
650 |
rtype.has_perm(self._cw, 'add', **securitycheck_args)) |
0 | 651 |
constraints = rtype.rproperty(subjtype, objtype, 'constraints') |
652 |
if vocabconstraints: |
|
653 |
# RQLConstraint is a subclass for RQLVocabularyConstraint, so they |
|
654 |
# will be included as well |
|
655 |
restriction += [cstr.restriction for cstr in constraints |
|
656 |
if isinstance(cstr, RQLVocabularyConstraint)] |
|
657 |
else: |
|
658 |
restriction += [cstr.restriction for cstr in constraints |
|
659 |
if isinstance(cstr, RQLConstraint)] |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
660 |
etypecls = self._cw.vreg['etypes'].etype_class(targettype) |
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
661 |
rql = etypecls.fetch_rql(self._cw.user, restriction, |
0 | 662 |
mainvar=searchedvar, ordermethod=ordermethod) |
663 |
# ensure we have an order defined |
|
664 |
if not ' ORDERBY ' in rql: |
|
665 |
before, after = rql.split(' WHERE ', 1) |
|
666 |
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
|
667 |
if insertsecurity: |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
668 |
rqlexprs = rtype.get_rqlexprs('add') |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
669 |
rewriter = RQLRewriter(self._cw) |
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
670 |
rqlst = self._cw.vreg.parse(self._cw, rql, args) |
3241
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
671 |
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
|
672 |
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
|
673 |
select.solutions, args) |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
674 |
rql = rqlst.as_string() |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
675 |
return rql, args |
1474 | 676 |
|
0 | 677 |
def unrelated(self, rtype, targettype, role='subject', limit=None, |
678 |
ordermethod=None): |
|
679 |
"""return a result set of target type objects that may be related |
|
680 |
by a given relation, with self as subject or object |
|
681 |
""" |
|
3241
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
682 |
try: |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
683 |
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
|
684 |
except Unauthorized: |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
685 |
return self._cw.empty_rset() |
0 | 686 |
if limit is not None: |
687 |
before, after = rql.split(' WHERE ', 1) |
|
688 |
rql = '%s LIMIT %s WHERE %s' % (before, limit, after) |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
689 |
return self._cw.execute(rql, args, tuple(args)) |
1474 | 690 |
|
0 | 691 |
# relations cache handling ################################################ |
1474 | 692 |
|
0 | 693 |
def relation_cached(self, rtype, role): |
694 |
"""return true if the given relation is already cached on the instance |
|
695 |
""" |
|
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
|
696 |
return self._related_cache.get('%s_%s' % (rtype, role)) |
1474 | 697 |
|
0 | 698 |
def related_cache(self, rtype, role, entities=True, limit=None): |
699 |
"""return values for the given relation if it's cached on the instance, |
|
700 |
else raise `KeyError` |
|
701 |
""" |
|
702 |
res = self._related_cache['%s_%s' % (rtype, role)][entities] |
|
703 |
if limit: |
|
704 |
if entities: |
|
705 |
res = res[:limit] |
|
706 |
else: |
|
707 |
res = res.limit(limit) |
|
708 |
return res |
|
1474 | 709 |
|
0 | 710 |
def set_related_cache(self, rtype, role, rset, col=0): |
711 |
"""set cached values for the given relation""" |
|
712 |
if rset: |
|
713 |
related = list(rset.entities(col)) |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
714 |
rschema = self._cw.vreg.schema.rschema(rtype) |
0 | 715 |
if role == 'subject': |
716 |
rcard = rschema.rproperty(self.e_schema, related[0].e_schema, |
|
717 |
'cardinality')[1] |
|
718 |
target = 'object' |
|
719 |
else: |
|
720 |
rcard = rschema.rproperty(related[0].e_schema, self.e_schema, |
|
721 |
'cardinality')[0] |
|
722 |
target = 'subject' |
|
723 |
if rcard in '?1': |
|
724 |
for rentity in related: |
|
725 |
rentity._related_cache['%s_%s' % (rtype, target)] = (self.as_rset(), [self]) |
|
726 |
else: |
|
727 |
related = [] |
|
728 |
self._related_cache['%s_%s' % (rtype, role)] = (rset, related) |
|
1474 | 729 |
|
0 | 730 |
def clear_related_cache(self, rtype=None, role=None): |
731 |
"""clear cached values for the given relation or the entire cache if |
|
732 |
no relation is given |
|
733 |
""" |
|
734 |
if rtype is None: |
|
735 |
self._related_cache = {} |
|
736 |
else: |
|
737 |
assert role |
|
738 |
self._related_cache.pop('%s_%s' % (rtype, role), None) |
|
1474 | 739 |
|
2942
77ebdbe93cf8
[entity] generic clear_all_caches methods, to use in test
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2941
diff
changeset
|
740 |
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
|
741 |
self.clear() |
77ebdbe93cf8
[entity] generic clear_all_caches methods, to use in test
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2941
diff
changeset
|
742 |
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
|
743 |
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
|
744 |
|
0 | 745 |
# raw edition utilities ################################################### |
1474 | 746 |
|
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
|
747 |
def set_attributes(self, _cw_unsafe=False, **kwargs): |
0 | 748 |
assert kwargs |
749 |
relations = [] |
|
750 |
for key in kwargs: |
|
751 |
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
|
752 |
# 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
|
753 |
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
|
754 |
# and now update the database |
0 | 755 |
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
|
756 |
if _cw_unsafe: |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
757 |
self._cw.unsafe_execute( |
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
|
758 |
'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
|
759 |
else: |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
760 |
self._cw.execute('SET %s WHERE X eid %%(x)s' % ','.join(relations), |
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
|
761 |
kwargs, 'x') |
1474 | 762 |
|
0 | 763 |
def delete(self): |
764 |
assert self.has_eid(), self.eid |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
765 |
self._cw.execute('DELETE %s X WHERE X eid %%(x)s' % self.e_schema, |
0 | 766 |
{'x': self.eid}) |
1474 | 767 |
|
0 | 768 |
# server side utilities ################################################### |
1474 | 769 |
|
0 | 770 |
def set_defaults(self): |
771 |
"""set default values according to the schema""" |
|
772 |
self._default_set = set() |
|
773 |
for attr, value in self.e_schema.defaults(): |
|
774 |
if not self.has_key(attr): |
|
775 |
self[str(attr)] = value |
|
776 |
self._default_set.add(attr) |
|
777 |
||
778 |
def check(self, creation=False): |
|
779 |
"""check this entity against its schema. Only final relation |
|
780 |
are checked here, constraint on actual relations are checked in hooks |
|
781 |
""" |
|
782 |
# necessary since eid is handled specifically and yams require it to be |
|
783 |
# in the dictionary |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
784 |
if self._cw is None: |
0 | 785 |
_ = unicode |
786 |
else: |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
787 |
_ = self._cw._ |
0 | 788 |
self.e_schema.check(self, creation=creation, _=_) |
789 |
||
790 |
def fti_containers(self, _done=None): |
|
791 |
if _done is None: |
|
792 |
_done = set() |
|
793 |
_done.add(self.eid) |
|
794 |
containers = tuple(self.e_schema.fulltext_containers()) |
|
795 |
if containers: |
|
476
62968fa8845c
yield self if no ft container found
sylvain.thenault@logilab.fr
parents:
475
diff
changeset
|
796 |
yielded = False |
0 | 797 |
for rschema, target in containers: |
798 |
if target == 'object': |
|
799 |
targets = getattr(self, rschema.type) |
|
800 |
else: |
|
801 |
targets = getattr(self, 'reverse_%s' % rschema) |
|
802 |
for entity in targets: |
|
803 |
if entity.eid in _done: |
|
804 |
continue |
|
805 |
for container in entity.fti_containers(_done): |
|
806 |
yield container |
|
476
62968fa8845c
yield self if no ft container found
sylvain.thenault@logilab.fr
parents:
475
diff
changeset
|
807 |
yielded = True |
62968fa8845c
yield self if no ft container found
sylvain.thenault@logilab.fr
parents:
475
diff
changeset
|
808 |
if not yielded: |
62968fa8845c
yield self if no ft container found
sylvain.thenault@logilab.fr
parents:
475
diff
changeset
|
809 |
yield self |
0 | 810 |
else: |
811 |
yield self |
|
1474 | 812 |
|
0 | 813 |
def get_words(self): |
814 |
"""used by the full text indexer to get words to index |
|
815 |
||
816 |
this method should only be used on the repository side since it depends |
|
817 |
on the indexer package |
|
1474 | 818 |
|
0 | 819 |
:rtype: list |
820 |
:return: the list of indexable word of this entity |
|
821 |
""" |
|
822 |
from indexer.query_objects import tokenize |
|
823 |
words = [] |
|
824 |
for rschema in self.e_schema.indexable_attributes(): |
|
825 |
try: |
|
826 |
value = self.printable_value(rschema, format='text/plain') |
|
1132 | 827 |
except TransformError: |
0 | 828 |
continue |
829 |
except: |
|
830 |
self.exception("can't add value of %s to text index for entity %s", |
|
831 |
rschema, self.eid) |
|
832 |
continue |
|
833 |
if value: |
|
834 |
words += tokenize(value) |
|
1474 | 835 |
|
0 | 836 |
for rschema, role in self.e_schema.fulltext_relations(): |
837 |
if role == 'subject': |
|
838 |
for entity in getattr(self, rschema.type): |
|
839 |
words += entity.get_words() |
|
840 |
else: # if role == 'object': |
|
841 |
for entity in getattr(self, 'reverse_%s' % rschema.type): |
|
842 |
words += entity.get_words() |
|
843 |
return words |
|
844 |
||
845 |
||
846 |
# attribute and relation descriptors ########################################## |
|
847 |
||
848 |
class Attribute(object): |
|
849 |
"""descriptor that controls schema attribute access""" |
|
850 |
||
851 |
def __init__(self, attrname): |
|
852 |
assert attrname != 'eid' |
|
853 |
self._attrname = attrname |
|
854 |
||
855 |
def __get__(self, eobj, eclass): |
|
856 |
if eobj is None: |
|
857 |
return self |
|
858 |
return eobj.get_value(self._attrname) |
|
859 |
||
860 |
def __set__(self, eobj, value): |
|
861 |
eobj[self._attrname] = value |
|
2875
b7399ef8b3e0
towards better edited attributes handling
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2872
diff
changeset
|
862 |
if hasattr(eobj, 'edited_attributes'): |
b7399ef8b3e0
towards better edited attributes handling
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2872
diff
changeset
|
863 |
eobj.edited_attributes.add(self._attrname) |
0 | 864 |
|
865 |
class Relation(object): |
|
866 |
"""descriptor that controls schema relation access""" |
|
867 |
_role = None # for pylint |
|
868 |
||
869 |
def __init__(self, rschema): |
|
870 |
self._rschema = rschema |
|
871 |
self._rtype = rschema.type |
|
872 |
||
873 |
def __get__(self, eobj, eclass): |
|
874 |
if eobj is None: |
|
875 |
raise AttributeError('%s cannot be only be accessed from instances' |
|
876 |
% self._rtype) |
|
877 |
return eobj.related(self._rtype, self._role, entities=True) |
|
1474 | 878 |
|
0 | 879 |
def __set__(self, eobj, value): |
880 |
raise NotImplementedError |
|
881 |
||
882 |
||
883 |
class SubjectRelation(Relation): |
|
884 |
"""descriptor that controls schema relation access""" |
|
885 |
_role = 'subject' |
|
1474 | 886 |
|
0 | 887 |
class ObjectRelation(Relation): |
888 |
"""descriptor that controls schema relation access""" |
|
889 |
_role = 'object' |
|
890 |
||
891 |
from logging import getLogger |
|
892 |
from cubicweb import set_log_methods |
|
893 |
set_log_methods(Entity, getLogger('cubicweb.entity')) |