--- a/__init__.py Wed Oct 14 14:09:40 2009 +0200
+++ b/__init__.py Wed Oct 14 15:59:00 2009 +0200
@@ -24,6 +24,7 @@
from logilab.common.decorators import cached
from logilab.common.logging_ext import set_log_methods
+
if os.environ.get('APYCOT_ROOT'):
logging.basicConfig(level=logging.CRITICAL)
else:
@@ -122,30 +123,34 @@
def set_entity_cache(self, entity):
pass
- def create_entity(self, etype, *args, **kwargs):
+ def create_entity(self, etype, **kwargs):
"""add a new entity of the given type
Example (in a shell session):
c = create_entity('Company', name=u'Logilab')
- create_entity('Person', ('works_for', 'Y'),
- Y=c.eid, firstname=u'John', lastname=u'Doe')
+ create_entity('Person', works_for=c, firstname=u'John', lastname=u'Doe')
"""
rql = 'INSERT %s X' % etype
relations = []
restrictions = set()
cachekey = []
- for rtype, rvar in args:
- relations.append('X %s %s' % (rtype, rvar))
- restriction = '%s eid %%(%s)s' % (rvar, rvar)
- if not restriction in restrictions:
- restrictions.add(restriction)
- cachekey.append(rvar)
- for attr in kwargs:
- if attr in cachekey:
- continue
- relations.append('X %s %%(%s)s' % (attr, attr))
+ for attr, value in kwargs.iteritems():
+ if hasattr(value, 'eid'): # non final relation
+ rvar = attr.upper()
+ # XXX safer detection of object relation
+ if attr.startswith('reverse_'):
+ relations.append('%s %s X' % (rvar, attr[len('reverse_'):]))
+ else:
+ relations.append('X %s %s' % (attr, rvar))
+ restriction = '%s eid %%(%s)s' % (rvar, attr)
+ if not restriction in restrictions:
+ restrictions.add(restriction)
+ cachekey.append(attr)
+ kwargs[attr] = value.eid
+ else: # attribute
+ relations.append('X %s %%(%s)s' % (attr, attr))
if relations:
rql = '%s: %s' % (rql, ', '.join(relations))
if restrictions:
--- a/test/unittest_entity.py Wed Oct 14 14:09:40 2009 +0200
+++ b/test/unittest_entity.py Wed Oct 14 15:59:00 2009 +0200
@@ -468,6 +468,19 @@
self.assertEquals(card.absolute_url(),
'http://testing.fr/cubicweb/card/eid/%s' % card.eid)
+ def test_create_entity(self):
+ p1 = self.add_entity('Personne', nom=u'fayolle', prenom=u'alexandre')
+ note = self.add_entity('Note', type=u'z')
+ req = self.request()
+ p = req.create_entity('Personne', nom=u'di mascio', prenom=u'adrien',
+ connait=p1, evaluee=p1,
+ reverse_ecrit_par=note)
+ self.assertEquals(p.nom, 'di mascio')
+ self.assertEquals([c.nom for c in p.connait], ['fayolle'])
+ self.assertEquals([c.nom for c in p.evaluee], ['fayolle'])
+ self.assertEquals([c.type for c in p.reverse_ecrit_par], ['z'])
+
+
if __name__ == '__main__':
from logilab.common.testlib import unittest_main
unittest_main()