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