33 from cubicweb.rset import ResultSet |
33 from cubicweb.rset import ResultSet |
34 |
34 |
35 ONESECOND = timedelta(0, 1, 0) |
35 ONESECOND = timedelta(0, 1, 0) |
36 CACHE_REGISTRY = {} |
36 CACHE_REGISTRY = {} |
37 |
37 |
|
38 class FindEntityError(Exception): |
|
39 """raised when find_one_entity() can not return one and only one entity""" |
38 |
40 |
39 def _check_cw_unsafe(kwargs): |
41 def _check_cw_unsafe(kwargs): |
40 if kwargs.pop('_cw_unsafe', False): |
42 if kwargs.pop('_cw_unsafe', False): |
41 warn('[3.7] _cw_unsafe argument is deprecated, now unsafe by ' |
43 warn('[3.7] _cw_unsafe argument is deprecated, now unsafe by ' |
42 'default, control it using cw_[read|write]_security.', |
44 'default, control it using cw_[read|write]_security.', |
137 |
139 |
138 """ |
140 """ |
139 _check_cw_unsafe(kwargs) |
141 _check_cw_unsafe(kwargs) |
140 cls = self.vreg['etypes'].etype_class(etype) |
142 cls = self.vreg['etypes'].etype_class(etype) |
141 return cls.cw_instantiate(self.execute, **kwargs) |
143 return cls.cw_instantiate(self.execute, **kwargs) |
|
144 |
|
145 def find_entities(self, etype, **kwargs): |
|
146 """find entities of the given type and attribute values. |
|
147 |
|
148 >>> users = find_entities('CWGroup', name=u'users') |
|
149 >>> groups = find_entities('CWGroup') |
|
150 """ |
|
151 parts = ['Any X WHERE X is %s' % etype] |
|
152 parts.extend('X %(attr)s %%(%(attr)s)s' % {'attr': attr} for attr in kwargs) |
|
153 return self.execute(', '.join(parts), kwargs).entities() |
|
154 |
|
155 def find_one_entity(self, etype, **kwargs): |
|
156 """find one entity of the given type and attribute values. |
|
157 raise FindEntityError if can not return one and only one entity. |
|
158 |
|
159 >>> users = find_one_entity('CWGroup', name=u'users') |
|
160 >>> groups = find_one_entity('CWGroup') |
|
161 Exception() |
|
162 """ |
|
163 parts = ['Any X WHERE X is %s' % etype] |
|
164 parts.extend('X %(attr)s %%(%(attr)s)s' % {'attr': attr} for attr in kwargs) |
|
165 rql = ', '.join(parts) |
|
166 rset = self.execute(rql, kwargs) |
|
167 if len(rset) != 1: |
|
168 raise FindEntityError('Found %i entitie(s) when 1 was expected (rql=%s ; %s)' |
|
169 % (len(rset), rql, repr(kwargs))) |
|
170 return rset.get_entity(0,0) |
142 |
171 |
143 def ensure_ro_rql(self, rql): |
172 def ensure_ro_rql(self, rql): |
144 """raise an exception if the given rql is not a select query""" |
173 """raise an exception if the given rql is not a select query""" |
145 first = rql.split(None, 1)[0].lower() |
174 first = rql.split(None, 1)[0].lower() |
146 if first in ('insert', 'set', 'delete'): |
175 if first in ('insert', 'set', 'delete'): |