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