It's unclear what's "not working", but I see an ambiguous column reference "node_id". Easily fixed by table-qualifying the column name:
CREATE OR REPLACE FUNCTION find_node_id(_relation_id text)
RETURNS TABLE(node_id text)
LANGUAGE plpgsql AS
$func$
BEGIN
RETURN QUERY
SELECT n.node_id::text -- HERE!
FROM node_mapping n
WHERE n.related_ids ? _relation_id;
END
$func$;
Note that node_id
in the RETURNS TABLE
declaration is implicitly visible as OUT
parameter in the whole function body. So you need to disambiguate between it and the column with the same name.
Related:
I fixed a couple of other oddities (that would still work, though). Among other things, you don't need to cast related_ids::jsonb
when the column is already type jsonb
.
A final RETURN;
is optional. The manual:
A final RETURN
, which should have no argument, causes control to exit the function (or you can just let control reach the end of the function).
For the simple example, rather use a simpler, equivalent SQL function:
CREATE OR REPLACE FUNCTION find_node_id(_relation_id text)
RETURNS TABLE(node_id text)
LANGUAGE sql AS
$func$
SELECT n.node_id::text
FROM node_mapping n
WHERE n.related_ids ? _relation_id;
$func$;
Or, equivalent:
CREATE OR REPLACE FUNCTION find_node_id(_relation_id text, OUT node_id text)
RETURNS SETOF record
LANGUAGE sql AS
$func$
SELECT n.node_id::text
FROM node_mapping n
WHERE n.related_ids ? _relation_id;
$func$;