[itree] Move calculation of the next `ordering` value to itree
authorSylvain Thénault <sylvain.thenault@logilab.fr>
Mon, 11 Dec 2017 14:03:16 +0100
changeset 2907 45a1b86c2805
parent 2906 69ce3f55cd88
child 2908 e08c4e3177f5
[itree] Move calculation of the next `ordering` value to itree so all implementation details of this ordering management is at the same place.
cubicweb_seda/entities/itree.py
cubicweb_seda/hooks.py
--- a/cubicweb_seda/entities/itree.py	Mon Dec 11 16:10:27 2017 +0100
+++ b/cubicweb_seda/entities/itree.py	Mon Dec 11 14:03:16 2017 +0100
@@ -152,6 +152,15 @@
 ETYPE_PARENT_RTYPE = dict(MULTIPLE_CHILDREN)
 
 
+def next_child_ordering(cnx, parent_eid, rtype):
+    """Return value for the `ordering` attribute of a child freshly appended through
+    `rtype` to parent entity with the given eid.
+    """
+    rql = 'Any MAX(O) WHERE X {rtype} P, P eid %(p)s, X ordering O'
+    ordering = cnx.execute(rql.format(rtype=rtype), {'p': parent_eid})[0][0]
+    return 1 if ordering is None else ordering + 1
+
+
 def reparent(entity, new_parent_eid):
     """Move `entity` as a children of `new_parent_eid`.
     """
--- a/cubicweb_seda/hooks.py	Mon Dec 11 16:10:27 2017 +0100
+++ b/cubicweb_seda/hooks.py	Mon Dec 11 14:03:16 2017 +0100
@@ -27,6 +27,7 @@
 
 from .xsd2yams import MULTIPLE_CHILDREN
 from .entities import rule_type_from_etype, diag
+from .entities.itree import next_child_ordering
 from .entities.generated import (CHOICE_RTYPE,
                                  CHECK_CARD_ETYPES, CHECK_CHILDREN_CARD_RTYPES)
 
@@ -518,10 +519,7 @@
 
     def __call__(self):
         eid, parent_eid = self.eidfrom, self.eidto
-        rql = 'Any MAX(O) WHERE X {rtype} P, P eid %(p)s, X ordering O'
-        ordering = self._cw.execute(rql.format(rtype=self.rtype),
-                                    {'p': parent_eid})[0][0]
-        ordering = 0 if ordering is None else ordering
+        ordering = next_child_ordering(self._cw, parent_eid, self.rtype)
         entity = self._cw.entity_from_eid(eid)
         entity.cw_set(ordering=ordering + 1)