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