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