curs.execute('''with recursive cte_c as ( select 1 as level ,call_group ,rule_id ,name ,parent_group ,null as keypress ,company_id ,call_group::text as route ,name::text as r_name ,null as keyroute from groups where (company_id ,call_group) = ( select company_id ,call_group from dids_group where did = %(outer_did)s ) union all select level + 1 ,g.call_group ,g.rule_id ,g.name ,g.parent_group ,g.keypress::text ,g.company_id ,c.route || ',' || g.call_group::text ,repeat(', ', level) || g.name ,coalesce( c.keyroute || ':' || g.keypress::text ,g.keypress::text) from cte_c c ,groups g where c.call_group = g.parent_group and c.company_id = g.company_id and c.rule_id = 4 and not (g.call_group::text = any(string_to_array(c.route, ','))) ) select row_number() over( order by route ) as rn ,level ,coalesce( lag(level, 1) over( order by route ) ,0) as lag_r ,coalesce( lead(level, 1) over( order by route ) ,0) as lead_r ,coalesce( lead(level, 2) over( order by route ) ,0) as lead_r2 ,call_group ,parent_group ,rule_id ,name ,keypress ,route ,keyroute ,(select filename from groups_ivr_files i1 where i1.company_id = c.company_id and i1.call_group = c.call_group ) as ivr_file ,(select fwd_to from cfwd_line cl1 where cl1.company_id = c.company_id and cl1.call_group = c.call_group ) as fwd_to ,array_to_string( array( select line from groups_line gl where gl.company_id = c.company_id and gl.call_group = c.call_group order by random() ) ,',' ) as at1 ,(select description from dial_rules dr where dr.id = c.rule_id ) as dial_rule ,(select count(*) from groups g where g.parent_group = c.parent_group ) as cnt_nums from cte_c c order by route; ''', {'outer_did': __outer_did})