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