Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgres return json from a function

I got to know that I can use row_to_json to return json output

For example If my query is:

select * from sample;

I can rewrite it as follows to return json output:

select row_to_json(sample) from sample;

But one thing I am trying to achieve is the same functionality in the function.

To give you an example, here is the function returning table:

CREATE FUNCTION find_val(val text) 
RETURNS SETOF sample AS
$$
BEGIN
RETURN QUERY
SELECT * FROM sample where $1 = ANY(col4);
END;
$$
LANGUAGE 'plpgsql';

Now instead of rows, I want to return JSON output from my function. How can I do that ?

Here is what I have tried so far:

native=> CREATE FUNCTION find_val(val text) 
RETURNS SETOF sample AS
$$
BEGIN
RETURN QUERY
SELECT row_to_json(sample) FROM sample where $1 = ANY(col4) ; 
END;
$$
LANGUAGE 'plpgsql';
CREATE FUNCTION
native=> select find_val('yo');
ERROR:  structure of query does not match function result type
DETAIL:  Returned type json does not match expected type integer in column 1.
CONTEXT:  PL/pgSQL function find_val(text) line 3 at RETURN QUERY
native=> drop function find_val(text);
DROP FUNCTION



native=> CREATE FUNCTION find_val(val text) 
native-> RETURNS json AS
native-> $$
native$> BEGIN
native$> SELECT row_to_json(sample) FROM sample where $1 = ANY(col4);
native$> END;
native$> $$
native-> LANGUAGE 'plpgsql';
CREATE FUNCTION
native=> select find_val('yo');
ERROR:  query has no destination for result data
HINT:  If you want to discard the results of a SELECT, use PERFORM instead.
CONTEXT:  PL/pgSQL function find_val(text) line 3 at SQL statement
native=> 
like image 675
Mandeep Singh Avatar asked Jun 14 '14 13:06

Mandeep Singh


1 Answers

This is nothing to do with json vs other return types. You can't use plain SELECT in a PL/PgSQL function, it has to be SELECT INTO, RETURN QUERY SELECT, or PERFORM. Per the HINT error.

In your case all you need is a plain SQL function.

CREATE FUNCTION find_val(val text) 
RETURNS json AS
$$
SELECT row_to_json(sample) FROM sample where $1 = ANY(col4);
$$ LANGUAGE sql;
like image 142
Craig Ringer Avatar answered Oct 02 '22 07:10

Craig Ringer