$$ LANGUAGE SQL STABLE ROWS 1;
CREATE OR REPLACE FUNCTION actor.org_unit_ancestors( INT ) RETURNS SETOF actor.org_unit AS $$
- WITH RECURSIVE anscestor_depth AS (
- SELECT ou.id,
- ou.parent_ou
- FROM actor.org_unit ou
- WHERE ou.id = $1
- UNION ALL
- SELECT ou.id,
- ou.parent_ou
- FROM actor.org_unit ou
- JOIN anscestor_depth ot ON (ot.parent_ou = ou.id)
- ) SELECT ou.* FROM actor.org_unit ou JOIN anscestor_depth USING (id);
+ WITH RECURSIVE org_unit_ancestors_distance(id, distance) AS (
+ SELECT $1, 0
+ UNION
+ SELECT ou.parent_ou, ouad.distance+1
+ FROM actor.org_unit ou JOIN org_unit_ancestors_distance ouad ON (ou.id = ouad.id)
+ WHERE ou.parent_ou IS NOT NULL
+ )
+ SELECT ou.* FROM actor.org_unit ou JOIN org_unit_ancestors_distance ouad USING (id) ORDER BY ouad.distance;
$$ LANGUAGE SQL ROWS 1;
CREATE OR REPLACE FUNCTION actor.org_unit_ancestor_at_depth ( INT,INT ) RETURNS actor.org_unit AS $$