I'm very, very new to writing Postgres functions. I'm writing a function to build a materialized path for a child by searching for parents recursively starting with the child's id. Here's the function I have, but I keep getting the error ERROR: RETURN cannot have a parameter in function returning set
create or replace function build_mp(child_id text)
returns SETOF text
language plpgsql
as $$
begin
select parentid from account where childid = child_id;
if parentid IS NULL then
return ARRAY[child_id];
else
return build_mp(parentid) || ARRAY[child_id];
end if;
end $$;
SELECT build_mp('mychild');
What am I doing wrong?
Edit
Here's the working solution. It takes a child's id, then searches recursively for all parents above it building a material path for the new child item.
create or replace function build_mp(child_id text)
returns text[]
language plpgsql
as $$
declare
parent text;
begin
execute 'select parentid from account where childid = $1' INTO parent USING child_id;
if parent IS NULL THEN
return ARRAY[child_id];
else
return build_mp(parent) || ARRAY[child_id];
end if;
end $$;
SELECT build_mp('mychild') AS mp;