[selectors] enhance rql_condition to make it usable as a condition on request's user stable
authorSylvain Thénault <sylvain.thenault@logilab.fr>
Wed, 11 May 2011 09:42:02 +0200
branchstable
changeset 7362 b9813c9d32ac
parent 7357 5ad3154a8810
child 7363 2293c49b290a
[selectors] enhance rql_condition to make it usable as a condition on request's user
selectors.py
test/unittest_selectors.py
--- a/selectors.py	Tue May 10 18:50:13 2011 +0200
+++ b/selectors.py	Wed May 11 09:42:02 2011 +0200
@@ -1160,9 +1160,12 @@
     See :class:`~cubicweb.selectors.EntitySelector` documentation for entity
     lookup / score rules according to the input context.
     """
-    def __init__(self, expression, once_is_enough=False):
+    def __init__(self, expression, once_is_enough=False, user_condition=False):
         super(rql_condition, self).__init__(once_is_enough)
-        if 'U' in frozenset(split_expression(expression)):
+        self.user_condition = user_condition
+        if user_condition:
+            rql = 'Any COUNT(U) WHERE U eid %%(u)s, %s' % expression
+        elif 'U' in frozenset(split_expression(expression)):
             rql = 'Any COUNT(X) WHERE X eid %%(x)s, U eid %%(u)s, %s' % expression
         else:
             rql = 'Any COUNT(X) WHERE X eid %%(x)s, %s' % expression
@@ -1171,6 +1174,16 @@
     def __str__(self):
         return '%s(%r)' % (self.__class__.__name__, self.rql)
 
+    @lltrace
+    def __call__(self, cls, req, **kwargs):
+        if self.user_condition:
+            try:
+                return req.execute(self.rql, {'u': req.user.eid})[0][0]
+            except Unauthorized:
+                return 0
+        else:
+            return super(rql_condition, self).__call__(cls, req, **kwargs)
+
     def _score(self, req, eid):
         try:
             return req.execute(self.rql, {'x': eid, 'u': req.user.eid})[0][0]
--- a/test/unittest_selectors.py	Tue May 10 18:50:13 2011 +0200
+++ b/test/unittest_selectors.py	Wed May 11 09:42:02 2011 +0200
@@ -427,6 +427,13 @@
         self.assertEqual(selector(None, req, entity=req.user), 1)
         self.assertEqual(selector(None, req), 0)
 
+    def test_rql_condition_user(self):
+        req = self.request()
+        selector = rql_condition('U login "admin"', user_condition=True)
+        self.assertEqual(selector(None, req), 1)
+        selector = rql_condition('U login "toto"', user_condition=True)
+        self.assertEqual(selector(None, req), 0)
+
 if __name__ == '__main__':
     unittest_main()