author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Tue, 13 Oct 2009 15:59:47 +0200 | |
changeset 3657 | 706d7bf0ae3d |
parent 3649 | 59eb710b9862 |
child 3674 | 387d51af966d |
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 |
|
3626
017869a514c3
[doc] updated docstrings
Alexandre Fayolle <alexandre.fayolle@logilab.fr>
parents:
3552
diff
changeset
|
64 |
cardinality are always skipped. |
0 | 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): |
|
3626
017869a514c3
[doc] updated docstrings
Alexandre Fayolle <alexandre.fayolle@logilab.fr>
parents:
3552
diff
changeset
|
376 |
"""copy relations of the object with the given eid on this |
017869a514c3
[doc] updated docstrings
Alexandre Fayolle <alexandre.fayolle@logilab.fr>
parents:
3552
diff
changeset
|
377 |
object (this method is called on the newly created copy, and |
017869a514c3
[doc] updated docstrings
Alexandre Fayolle <alexandre.fayolle@logilab.fr>
parents:
3552
diff
changeset
|
378 |
ceid designates the original entity). |
0 | 379 |
|
380 |
By default meta and composite relations are skipped. |
|
381 |
Overrides this if you want another behaviour |
|
382 |
""" |
|
383 |
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
|
384 |
execute = self._cw.execute |
0 | 385 |
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
|
386 |
if rschema.is_final() or rschema.meta: |
0 | 387 |
continue |
388 |
# skip already defined relations |
|
389 |
if getattr(self, rschema.type): |
|
390 |
continue |
|
391 |
if rschema.type in self.skip_copy_for: |
|
392 |
continue |
|
393 |
# skip composite relation |
|
394 |
if self.e_schema.subjrproperty(rschema, 'composite'): |
|
395 |
continue |
|
396 |
# skip relation with card in ?1 else we either change the copied |
|
397 |
# object (inlined relation) or inserting some inconsistency |
|
398 |
if self.e_schema.subjrproperty(rschema, 'cardinality')[1] in '?1': |
|
399 |
continue |
|
400 |
rql = 'SET X %s V WHERE X eid %%(x)s, Y eid %%(y)s, Y %s V' % ( |
|
401 |
rschema.type, rschema.type) |
|
402 |
execute(rql, {'x': self.eid, 'y': ceid}, ('x', 'y')) |
|
403 |
self.clear_related_cache(rschema.type, 'subject') |
|
404 |
for rschema in self.e_schema.object_relations(): |
|
405 |
if rschema.meta: |
|
406 |
continue |
|
407 |
# skip already defined relations |
|
408 |
if getattr(self, 'reverse_%s' % rschema.type): |
|
409 |
continue |
|
410 |
# skip composite relation |
|
411 |
if self.e_schema.objrproperty(rschema, 'composite'): |
|
412 |
continue |
|
413 |
# skip relation with card in ?1 else we either change the copied |
|
414 |
# object (inlined relation) or inserting some inconsistency |
|
415 |
if self.e_schema.objrproperty(rschema, 'cardinality')[0] in '?1': |
|
416 |
continue |
|
417 |
rql = 'SET V %s X WHERE X eid %%(x)s, Y eid %%(y)s, V %s Y' % ( |
|
418 |
rschema.type, rschema.type) |
|
419 |
execute(rql, {'x': self.eid, 'y': ceid}, ('x', 'y')) |
|
420 |
self.clear_related_cache(rschema.type, 'object') |
|
421 |
||
422 |
# data fetching methods ################################################### |
|
423 |
||
424 |
@cached |
|
425 |
def as_rset(self): |
|
426 |
"""returns a resultset containing `self` information""" |
|
427 |
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
|
428 |
{'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
|
429 |
return self._cw.decorate_rset(rset) |
1474 | 430 |
|
0 | 431 |
def to_complete_relations(self): |
432 |
"""by default complete final relations to when calling .complete()""" |
|
433 |
for rschema in self.e_schema.subject_relations(): |
|
434 |
if rschema.is_final(): |
|
435 |
continue |
|
436 |
if len(rschema.objects(self.e_schema)) > 1: |
|
437 |
# ambigous relations, the querier doesn't handle |
|
438 |
# outer join correctly in this case |
|
439 |
continue |
|
440 |
if rschema.inlined: |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
441 |
matching_groups = self._cw.user.matching_groups |
0 | 442 |
if matching_groups(rschema.get_groups('read')) and \ |
443 |
all(matching_groups(es.get_groups('read')) |
|
444 |
for es in rschema.objects(self.e_schema)): |
|
445 |
yield rschema, 'subject' |
|
1474 | 446 |
|
0 | 447 |
def to_complete_attributes(self, skip_bytes=True): |
448 |
for rschema, attrschema in self.e_schema.attribute_definitions(): |
|
449 |
# skip binary data by default |
|
450 |
if skip_bytes and attrschema.type == 'Bytes': |
|
451 |
continue |
|
452 |
attr = rschema.type |
|
453 |
if attr == 'eid': |
|
454 |
continue |
|
455 |
# 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
|
456 |
if not self._cw.user.matching_groups(rschema.get_groups('read')) \ |
0 | 457 |
or attrschema.type == 'Password': |
458 |
self[attr] = None |
|
459 |
continue |
|
460 |
yield attr |
|
1474 | 461 |
|
0 | 462 |
def complete(self, attributes=None, skip_bytes=True): |
463 |
"""complete this entity by adding missing attributes (i.e. query the |
|
464 |
repository to fill the entity) |
|
465 |
||
466 |
:type skip_bytes: bool |
|
467 |
:param skip_bytes: |
|
468 |
if true, attribute of type Bytes won't be considered |
|
469 |
""" |
|
470 |
assert self.has_eid() |
|
471 |
varmaker = rqlvar_maker() |
|
472 |
V = varmaker.next() |
|
473 |
rql = ['WHERE %s eid %%(x)s' % V] |
|
474 |
selected = [] |
|
475 |
for attr in (attributes or self.to_complete_attributes(skip_bytes)): |
|
476 |
# if attribute already in entity, nothing to do |
|
477 |
if self.has_key(attr): |
|
478 |
continue |
|
479 |
# case where attribute must be completed, but is not yet in entity |
|
480 |
var = varmaker.next() |
|
481 |
rql.append('%s %s %s' % (V, attr, var)) |
|
482 |
selected.append((attr, var)) |
|
483 |
# +1 since this doen't include the main variable |
|
484 |
lastattr = len(selected) + 1 |
|
485 |
if attributes is None: |
|
486 |
# fetch additional relations (restricted to 0..1 relations) |
|
487 |
for rschema, role in self.to_complete_relations(): |
|
488 |
rtype = rschema.type |
|
489 |
if self.relation_cached(rtype, role): |
|
490 |
continue |
|
491 |
var = varmaker.next() |
|
492 |
if role == 'subject': |
|
493 |
targettype = rschema.objects(self.e_schema)[0] |
|
494 |
card = rschema.rproperty(self.e_schema, targettype, |
|
495 |
'cardinality')[0] |
|
496 |
if card == '1': |
|
497 |
rql.append('%s %s %s' % (V, rtype, var)) |
|
498 |
else: # '?" |
|
499 |
rql.append('%s %s %s?' % (V, rtype, var)) |
|
500 |
else: |
|
501 |
targettype = rschema.subjects(self.e_schema)[1] |
|
502 |
card = rschema.rproperty(self.e_schema, targettype, |
|
503 |
'cardinality')[1] |
|
504 |
if card == '1': |
|
505 |
rql.append('%s %s %s' % (var, rtype, V)) |
|
506 |
else: # '?" |
|
507 |
rql.append('%s? %s %s' % (var, rtype, V)) |
|
508 |
assert card in '1?', '%s %s %s %s' % (self.e_schema, rtype, |
|
509 |
role, card) |
|
510 |
selected.append(((rtype, role), var)) |
|
511 |
if selected: |
|
512 |
# select V, we need it as the left most selected variable |
|
513 |
# if some outer join are included to fetch inlined relations |
|
514 |
rql = 'Any %s,%s %s' % (V, ','.join(var for attr, var in selected), |
|
515 |
','.join(rql)) |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
516 |
execute = getattr(self._cw, 'unsafe_execute', self._cw.execute) |
0 | 517 |
rset = execute(rql, {'x': self.eid}, 'x', build_descr=False)[0] |
518 |
# handle attributes |
|
519 |
for i in xrange(1, lastattr): |
|
520 |
self[str(selected[i-1][0])] = rset[i] |
|
521 |
# handle relations |
|
522 |
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
|
523 |
rtype, role = selected[i-1][0] |
0 | 524 |
value = rset[i] |
525 |
if value is None: |
|
526 |
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
|
527 |
self._cw.decorate_rset(rrset) |
0 | 528 |
else: |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
529 |
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
|
530 |
self.set_related_cache(rtype, role, rrset) |
1474 | 531 |
|
0 | 532 |
def get_value(self, name): |
533 |
"""get value for the attribute relation <name>, query the repository |
|
534 |
to get the value if necessary. |
|
535 |
||
536 |
:type name: str |
|
537 |
:param name: name of the attribute to get |
|
538 |
""" |
|
539 |
try: |
|
540 |
value = self[name] |
|
541 |
except KeyError: |
|
542 |
if not self.is_saved(): |
|
543 |
return None |
|
544 |
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
|
545 |
# 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
|
546 |
# see #344874 |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
547 |
execute = getattr(self._cw, 'unsafe_execute', self._cw.execute) |
0 | 548 |
try: |
549 |
rset = execute(rql, {'x': self.eid}, 'x') |
|
550 |
except Unauthorized: |
|
551 |
self[name] = value = None |
|
552 |
else: |
|
553 |
assert rset.rowcount <= 1, (self, rql, rset.rowcount) |
|
554 |
try: |
|
555 |
self[name] = value = rset.rows[0][0] |
|
556 |
except IndexError: |
|
557 |
# probably a multisource error |
|
558 |
self.critical("can't get value for attribute %s of entity with eid %s", |
|
559 |
name, self.eid) |
|
560 |
if self.e_schema.destination(name) == 'String': |
|
2320 | 561 |
# 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
|
562 |
self[name] = value = self._cw._('unaccessible') |
0 | 563 |
else: |
564 |
self[name] = value = None |
|
565 |
return value |
|
566 |
||
567 |
def related(self, rtype, role='subject', limit=None, entities=False): |
|
568 |
"""returns a resultset of related entities |
|
1474 | 569 |
|
0 | 570 |
:param role: is the role played by 'self' in the relation ('subject' or 'object') |
571 |
:param limit: resultset's maximum size |
|
572 |
:param entities: if True, the entites are returned; if False, a result set is returned |
|
573 |
""" |
|
574 |
try: |
|
575 |
return self.related_cache(rtype, role, entities, limit) |
|
576 |
except KeyError: |
|
577 |
pass |
|
578 |
assert self.has_eid() |
|
579 |
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
|
580 |
# 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
|
581 |
# see #344874 |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
582 |
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
|
583 |
rset = execute(rql, {'x': self.eid}, 'x') |
0 | 584 |
self.set_related_cache(rtype, role, rset) |
585 |
return self.related(rtype, role, limit, entities) |
|
586 |
||
3130
2486163c4630
allow to specify targettypes in related_rql
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3047
diff
changeset
|
587 |
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
|
588 |
rschema = self._cw.vreg.schema[rtype] |
0 | 589 |
if role == 'subject': |
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.objects(self.e_schema) |
0 | 592 |
restriction = 'E eid %%(x)s, E %s X' % rtype |
593 |
card = greater_card(rschema, (self.e_schema,), targettypes, 0) |
|
594 |
else: |
|
3130
2486163c4630
allow to specify targettypes in related_rql
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3047
diff
changeset
|
595 |
if targettypes is None: |
2486163c4630
allow to specify targettypes in related_rql
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3047
diff
changeset
|
596 |
targettypes = rschema.subjects(self.e_schema) |
0 | 597 |
restriction = 'E eid %%(x)s, X %s E' % rtype |
598 |
card = greater_card(rschema, targettypes, (self.e_schema,), 1) |
|
599 |
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
|
600 |
fetchattrs_list = [] |
0 | 601 |
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
|
602 |
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
|
603 |
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
|
604 |
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
|
605 |
rql = etypecls.fetch_rql(self._cw.user, [restriction], fetchattrs, |
0 | 606 |
settype=False) |
607 |
else: |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
608 |
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
|
609 |
rql = etypecls.fetch_rql(self._cw.user, [restriction], settype=False) |
0 | 610 |
# optimisation: remove ORDERBY if cardinality is 1 or ? (though |
611 |
# greater_card return 1 for those both cases) |
|
612 |
if card == '1': |
|
613 |
if ' ORDERBY ' in rql: |
|
614 |
rql = '%s WHERE %s' % (rql.split(' ORDERBY ', 1)[0], |
|
615 |
rql.split(' WHERE ', 1)[1]) |
|
616 |
elif not ' ORDERBY ' in rql: |
|
617 |
args = tuple(rql.split(' WHERE ', 1)) |
|
618 |
rql = '%s ORDERBY Z DESC WHERE X modification_date Z, %s' % args |
|
619 |
return rql |
|
1474 | 620 |
|
0 | 621 |
# generic vocabulary methods ############################################## |
622 |
||
623 |
def unrelated_rql(self, rtype, targettype, role, ordermethod=None, |
|
624 |
vocabconstraints=True): |
|
625 |
"""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
|
626 |
using (rtype, role) relation. |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
627 |
|
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
628 |
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
|
629 |
linked by `rtype`. |
0 | 630 |
""" |
631 |
ordermethod = ordermethod or 'fetch_unrelated_order' |
|
632 |
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
|
633 |
rtype = self._cw.vreg.schema.rschema(rtype) |
0 | 634 |
if role == 'subject': |
635 |
evar, searchedvar = 'S', 'O' |
|
636 |
subjtype, objtype = self.e_schema, targettype |
|
637 |
else: |
|
638 |
searchedvar, evar = 'S', 'O' |
|
639 |
objtype, subjtype = self.e_schema, targettype |
|
640 |
if self.has_eid(): |
|
641 |
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
|
642 |
args = {'x': self.eid} |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
643 |
if role == 'subject': |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
644 |
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
|
645 |
else: |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
646 |
securitycheck_args = {'toeid': self.eid} |
0 | 647 |
else: |
648 |
restriction = [] |
|
3241
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
649 |
args = {} |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
650 |
securitycheck_args = {} |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
651 |
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
|
652 |
rtype.has_perm(self._cw, 'add', **securitycheck_args)) |
0 | 653 |
constraints = rtype.rproperty(subjtype, objtype, 'constraints') |
654 |
if vocabconstraints: |
|
655 |
# RQLConstraint is a subclass for RQLVocabularyConstraint, so they |
|
656 |
# will be included as well |
|
657 |
restriction += [cstr.restriction for cstr in constraints |
|
658 |
if isinstance(cstr, RQLVocabularyConstraint)] |
|
659 |
else: |
|
660 |
restriction += [cstr.restriction for cstr in constraints |
|
661 |
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
|
662 |
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
|
663 |
rql = etypecls.fetch_rql(self._cw.user, restriction, |
0 | 664 |
mainvar=searchedvar, ordermethod=ordermethod) |
665 |
# ensure we have an order defined |
|
666 |
if not ' ORDERBY ' in rql: |
|
667 |
before, after = rql.split(' WHERE ', 1) |
|
668 |
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
|
669 |
if insertsecurity: |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
670 |
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
|
671 |
rewriter = RQLRewriter(self._cw) |
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
672 |
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
|
673 |
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
|
674 |
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
|
675 |
select.solutions, args) |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
676 |
rql = rqlst.as_string() |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
677 |
return rql, args |
1474 | 678 |
|
0 | 679 |
def unrelated(self, rtype, targettype, role='subject', limit=None, |
680 |
ordermethod=None): |
|
681 |
"""return a result set of target type objects that may be related |
|
682 |
by a given relation, with self as subject or object |
|
683 |
""" |
|
3241
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
684 |
try: |
1a6f7a0e7dbd
unrelated_rql now considers relation's add perm
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3212
diff
changeset
|
685 |
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
|
686 |
except Unauthorized: |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
687 |
return self._cw.empty_rset() |
0 | 688 |
if limit is not None: |
689 |
before, after = rql.split(' WHERE ', 1) |
|
690 |
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
|
691 |
return self._cw.execute(rql, args, tuple(args)) |
1474 | 692 |
|
0 | 693 |
# relations cache handling ################################################ |
1474 | 694 |
|
0 | 695 |
def relation_cached(self, rtype, role): |
696 |
"""return true if the given relation is already cached on the instance |
|
697 |
""" |
|
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
|
698 |
return self._related_cache.get('%s_%s' % (rtype, role)) |
1474 | 699 |
|
0 | 700 |
def related_cache(self, rtype, role, entities=True, limit=None): |
701 |
"""return values for the given relation if it's cached on the instance, |
|
702 |
else raise `KeyError` |
|
703 |
""" |
|
704 |
res = self._related_cache['%s_%s' % (rtype, role)][entities] |
|
3552
8facb3324170
[entity] put cached related entities as tuple to be sure no one is modifying
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3546
diff
changeset
|
705 |
if limit is not None: |
0 | 706 |
if entities: |
707 |
res = res[:limit] |
|
708 |
else: |
|
709 |
res = res.limit(limit) |
|
710 |
return res |
|
1474 | 711 |
|
0 | 712 |
def set_related_cache(self, rtype, role, rset, col=0): |
713 |
"""set cached values for the given relation""" |
|
714 |
if rset: |
|
715 |
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
|
716 |
rschema = self._cw.vreg.schema.rschema(rtype) |
0 | 717 |
if role == 'subject': |
718 |
rcard = rschema.rproperty(self.e_schema, related[0].e_schema, |
|
719 |
'cardinality')[1] |
|
720 |
target = 'object' |
|
721 |
else: |
|
722 |
rcard = rschema.rproperty(related[0].e_schema, self.e_schema, |
|
723 |
'cardinality')[0] |
|
724 |
target = 'subject' |
|
725 |
if rcard in '?1': |
|
726 |
for rentity in related: |
|
3552
8facb3324170
[entity] put cached related entities as tuple to be sure no one is modifying
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3546
diff
changeset
|
727 |
rentity._related_cache['%s_%s' % (rtype, target)] = ( |
8facb3324170
[entity] put cached related entities as tuple to be sure no one is modifying
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3546
diff
changeset
|
728 |
self.as_rset(), (self,)) |
0 | 729 |
else: |
3552
8facb3324170
[entity] put cached related entities as tuple to be sure no one is modifying
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3546
diff
changeset
|
730 |
related = () |
0 | 731 |
self._related_cache['%s_%s' % (rtype, role)] = (rset, related) |
1474 | 732 |
|
0 | 733 |
def clear_related_cache(self, rtype=None, role=None): |
734 |
"""clear cached values for the given relation or the entire cache if |
|
735 |
no relation is given |
|
736 |
""" |
|
737 |
if rtype is None: |
|
738 |
self._related_cache = {} |
|
739 |
else: |
|
740 |
assert role |
|
741 |
self._related_cache.pop('%s_%s' % (rtype, role), None) |
|
1474 | 742 |
|
2942
77ebdbe93cf8
[entity] generic clear_all_caches methods, to use in test
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2941
diff
changeset
|
743 |
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
|
744 |
self.clear() |
77ebdbe93cf8
[entity] generic clear_all_caches methods, to use in test
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2941
diff
changeset
|
745 |
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
|
746 |
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
|
747 |
|
0 | 748 |
# raw edition utilities ################################################### |
1474 | 749 |
|
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
|
750 |
def set_attributes(self, _cw_unsafe=False, **kwargs): |
0 | 751 |
assert kwargs |
752 |
relations = [] |
|
753 |
for key in kwargs: |
|
754 |
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
|
755 |
# 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
|
756 |
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
|
757 |
# and now update the database |
0 | 758 |
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
|
759 |
if _cw_unsafe: |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
760 |
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
|
761 |
'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
|
762 |
else: |
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
763 |
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
|
764 |
kwargs, 'x') |
1474 | 765 |
|
0 | 766 |
def delete(self): |
767 |
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
|
768 |
self._cw.execute('DELETE %s X WHERE X eid %%(x)s' % self.e_schema, |
0 | 769 |
{'x': self.eid}) |
1474 | 770 |
|
0 | 771 |
# server side utilities ################################################### |
1474 | 772 |
|
0 | 773 |
def set_defaults(self): |
774 |
"""set default values according to the schema""" |
|
775 |
self._default_set = set() |
|
776 |
for attr, value in self.e_schema.defaults(): |
|
777 |
if not self.has_key(attr): |
|
778 |
self[str(attr)] = value |
|
779 |
self._default_set.add(attr) |
|
780 |
||
781 |
def check(self, creation=False): |
|
782 |
"""check this entity against its schema. Only final relation |
|
783 |
are checked here, constraint on actual relations are checked in hooks |
|
784 |
""" |
|
785 |
# necessary since eid is handled specifically and yams require it to be |
|
786 |
# in the dictionary |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
787 |
if self._cw is None: |
0 | 788 |
_ = unicode |
789 |
else: |
|
3378
2f25f701301d
use ._cw instead of req on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3376
diff
changeset
|
790 |
_ = self._cw._ |
0 | 791 |
self.e_schema.check(self, creation=creation, _=_) |
792 |
||
793 |
def fti_containers(self, _done=None): |
|
794 |
if _done is None: |
|
795 |
_done = set() |
|
796 |
_done.add(self.eid) |
|
797 |
containers = tuple(self.e_schema.fulltext_containers()) |
|
798 |
if containers: |
|
476
62968fa8845c
yield self if no ft container found
sylvain.thenault@logilab.fr
parents:
475
diff
changeset
|
799 |
yielded = False |
0 | 800 |
for rschema, target in containers: |
801 |
if target == 'object': |
|
802 |
targets = getattr(self, rschema.type) |
|
803 |
else: |
|
804 |
targets = getattr(self, 'reverse_%s' % rschema) |
|
805 |
for entity in targets: |
|
806 |
if entity.eid in _done: |
|
807 |
continue |
|
808 |
for container in entity.fti_containers(_done): |
|
809 |
yield container |
|
476
62968fa8845c
yield self if no ft container found
sylvain.thenault@logilab.fr
parents:
475
diff
changeset
|
810 |
yielded = True |
62968fa8845c
yield self if no ft container found
sylvain.thenault@logilab.fr
parents:
475
diff
changeset
|
811 |
if not yielded: |
62968fa8845c
yield self if no ft container found
sylvain.thenault@logilab.fr
parents:
475
diff
changeset
|
812 |
yield self |
0 | 813 |
else: |
814 |
yield self |
|
1474 | 815 |
|
0 | 816 |
def get_words(self): |
817 |
"""used by the full text indexer to get words to index |
|
818 |
||
819 |
this method should only be used on the repository side since it depends |
|
820 |
on the indexer package |
|
1474 | 821 |
|
0 | 822 |
:rtype: list |
823 |
:return: the list of indexable word of this entity |
|
824 |
""" |
|
825 |
from indexer.query_objects import tokenize |
|
3546
f0aecddf367e
fix bug when renaming a full text indexed attribute
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3316
diff
changeset
|
826 |
# take care to cases where we're modyfying the schema |
3649
59eb710b9862
3.6 updates
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3629
diff
changeset
|
827 |
pending = self._cw.transaction_data.setdefault('pendingrdefs', set()) |
0 | 828 |
words = [] |
829 |
for rschema in self.e_schema.indexable_attributes(): |
|
3546
f0aecddf367e
fix bug when renaming a full text indexed attribute
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3316
diff
changeset
|
830 |
if (self.e_schema, rschema) in pending: |
f0aecddf367e
fix bug when renaming a full text indexed attribute
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3316
diff
changeset
|
831 |
continue |
0 | 832 |
try: |
833 |
value = self.printable_value(rschema, format='text/plain') |
|
1132 | 834 |
except TransformError: |
0 | 835 |
continue |
836 |
except: |
|
837 |
self.exception("can't add value of %s to text index for entity %s", |
|
838 |
rschema, self.eid) |
|
839 |
continue |
|
840 |
if value: |
|
841 |
words += tokenize(value) |
|
1474 | 842 |
|
0 | 843 |
for rschema, role in self.e_schema.fulltext_relations(): |
844 |
if role == 'subject': |
|
845 |
for entity in getattr(self, rschema.type): |
|
846 |
words += entity.get_words() |
|
847 |
else: # if role == 'object': |
|
848 |
for entity in getattr(self, 'reverse_%s' % rschema.type): |
|
849 |
words += entity.get_words() |
|
850 |
return words |
|
851 |
||
852 |
||
853 |
# attribute and relation descriptors ########################################## |
|
854 |
||
855 |
class Attribute(object): |
|
856 |
"""descriptor that controls schema attribute access""" |
|
857 |
||
858 |
def __init__(self, attrname): |
|
859 |
assert attrname != 'eid' |
|
860 |
self._attrname = attrname |
|
861 |
||
862 |
def __get__(self, eobj, eclass): |
|
863 |
if eobj is None: |
|
864 |
return self |
|
865 |
return eobj.get_value(self._attrname) |
|
866 |
||
867 |
def __set__(self, eobj, value): |
|
868 |
eobj[self._attrname] = value |
|
2875
b7399ef8b3e0
towards better edited attributes handling
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2872
diff
changeset
|
869 |
if hasattr(eobj, 'edited_attributes'): |
b7399ef8b3e0
towards better edited attributes handling
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2872
diff
changeset
|
870 |
eobj.edited_attributes.add(self._attrname) |
0 | 871 |
|
872 |
class Relation(object): |
|
873 |
"""descriptor that controls schema relation access""" |
|
874 |
_role = None # for pylint |
|
875 |
||
876 |
def __init__(self, rschema): |
|
877 |
self._rschema = rschema |
|
878 |
self._rtype = rschema.type |
|
879 |
||
880 |
def __get__(self, eobj, eclass): |
|
881 |
if eobj is None: |
|
882 |
raise AttributeError('%s cannot be only be accessed from instances' |
|
883 |
% self._rtype) |
|
884 |
return eobj.related(self._rtype, self._role, entities=True) |
|
1474 | 885 |
|
0 | 886 |
def __set__(self, eobj, value): |
887 |
raise NotImplementedError |
|
888 |
||
889 |
||
890 |
class SubjectRelation(Relation): |
|
891 |
"""descriptor that controls schema relation access""" |
|
892 |
_role = 'subject' |
|
1474 | 893 |
|
0 | 894 |
class ObjectRelation(Relation): |
895 |
"""descriptor that controls schema relation access""" |
|
896 |
_role = 'object' |
|
897 |
||
898 |
from logging import getLogger |
|
899 |
from cubicweb import set_log_methods |
|
900 |
set_log_methods(Entity, getLogger('cubicweb.entity')) |