-- -- tree_level/1 -- create or replace function tree_level( bit varying ) returns int4 as $$ -- Return the tree level of the given key. The root level is defined -- to be at level one. declare p_tree_key alias for $1; v_pos integer; v_level integer; begin if p_tree_key is null then return 0; end if; v_pos := 1; v_level := 0; while v_pos <= length(p_tree_key) loop v_level := v_level + 1; if substring(p_tree_key, v_pos, 1) = '1' then v_pos := v_pos + 32; else v_pos := v_pos + 8; end if; end loop; return v_level; end;$$ language plpgsql;