create or replace function self_and_children_ids(tb text, id text[], includeSelf bool = true) returns text[] AS
$$

declare

    ans   text[];
    sql   text;
    text1 text;
begin
    -- logic

    if includeSelf then
        text1 = 'id' ;
    else
        text1 = 'parent_id' ;
    end if;

    sql = 'with recursive tmp as (select id
                       from ' ||
          tb ||
          '
                       where ' ||
          text1 ||
          ' = any($1)
                       union all
                       select ' ||
          tb ||
          '.id
                       from ' ||
          tb ||
          '
                                inner join tmp on ' ||
          tb ||
          '.parent_id = tmp.id)

select array_agg(id)
from tmp';

    execute sql into ans using id;


    return ans;
end
$$ language plpgsql
;



create or replace function self_and_parent_ids(tb text, id text[], includeSelf bool = true) returns text[] AS
$$

declare

    ans   text[];
    sql   text;
begin
    -- logic



    sql = 'with recursive tmp as (select id,parent_id
                       from ' ||
          tb ||
          '
                       where ' ||

          'id = any($1)
                       union all
                       select ' ||
          tb ||
          '.id, ' || tb || '.parent_id
                       from ' ||
          tb ||
          '
                                inner join tmp on ' ||
          tb ||
          '.id = tmp.parent_id)

select array_agg(id)
from tmp ';

    if not includeSelf
    then
        sql = sql ||  ' where id != any($1)';
    end if;

    execute sql into ans using id;


    return ans;
end
$$ language plpgsql
;
