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