@@ -583,6 +583,7 @@ async def query_init(self, db: InfrahubDatabase, **kwargs) -> None: # pylint: d
583583 query = """
584584 MATCH (source_node:Node)%(arrow_left_start)s[:IS_RELATED]%(arrow_left_end)s(rl:Relationship { name: $rel_identifier })
585585 WHERE source_node.uuid IN $source_ids
586+ WITH DISTINCT source_node, rl
586587 CALL {
587588 WITH rl, source_node
588589 MATCH path = (source_node)%(path)s(peer:Node)
@@ -659,10 +660,23 @@ async def query_init(self, db: InfrahubDatabase, **kwargs) -> None: # pylint: d
659660 # QUERY Properties
660661 # ----------------------------------------------------------------------------
661662 query = """
662- MATCH (rl)-[rel_is_visible:IS_VISIBLE]-(is_visible)
663- MATCH (rl)-[rel_is_protected:IS_PROTECTED]-(is_protected)
664- WHERE all(r IN [ rel_is_visible, rel_is_protected] WHERE (%s))
665- """ % (branch_filter ,)
663+ CALL {
664+ WITH rl
665+ MATCH (rl)-[r:IS_VISIBLE]-(is_visible)
666+ WHERE %(branch_filter)s
667+ RETURN r AS rel_is_visible, is_visible
668+ ORDER BY r.branch_level DESC, r.from DESC, r.status ASC
669+ LIMIT 1
670+ }
671+ CALL {
672+ WITH rl
673+ MATCH (rl)-[r:IS_PROTECTED]-(is_protected)
674+ WHERE %(branch_filter)s
675+ RETURN r AS rel_is_protected, is_protected
676+ ORDER BY r.branch_level DESC, r.from DESC, r.status ASC
677+ LIMIT 1
678+ }
679+ """ % {"branch_filter" : branch_filter }
666680
667681 self .add_to_query (query )
668682
@@ -672,20 +686,24 @@ async def query_init(self, db: InfrahubDatabase, **kwargs) -> None: # pylint: d
672686 # We must query them one by one otherwise the second one won't return
673687 for node_prop in ["source" , "owner" ]:
674688 query = """
675- WITH %s
676- OPTIONAL MATCH (rl)-[rel_%s:HAS_%s]-(%s)
677- WHERE all(r IN [ rel_%s ] WHERE (%s))
678- """ % (
679- "," .join (self .return_labels ),
680- node_prop ,
681- node_prop .upper (),
682- node_prop ,
683- node_prop ,
684- branch_filter ,
685- )
689+ CALL {
690+ WITH rl
691+ OPTIONAL MATCH (rl)-[r:HAS_%(node_prop_type)s]-(%(node_prop)s)
692+ WHERE %(branch_filter)s
693+ RETURN r AS rel_%(node_prop)s, %(node_prop)s
694+ ORDER BY r.branch_level DESC, r.from DESC, r.status ASC
695+ LIMIT 1
696+ }
697+ """ % {
698+ "node_prop" : node_prop ,
699+ "node_prop_type" : node_prop .upper (),
700+ "branch_filter" : branch_filter ,
701+ }
686702 self .add_to_query (query )
687703 self .update_return_labels ([f"rel_{ node_prop } " , node_prop ])
688704
705+ self .add_to_query ("WITH " + "," .join (self .return_labels ))
706+
689707 # ----------------------------------------------------------------------------
690708 # ORDER Results
691709 # ----------------------------------------------------------------------------
0 commit comments