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