`materialize mode required, but it is not allowed in this context` error in PostgreSQL

300 views Asked by At

I created my_func() which returns SETOF RECORD type with a RETURN NEXT or RETURN QUERY statement as shown below:

CREATE FUNCTION my_func() RETURNS SETOF RECORD AS $$
DECLARE 
  row RECORD;
BEGIN
  FOR row IN VALUES (ROW('John','Smith')), (ROW('David','Miller')) LOOP
    RETURN NEXT row;
  END LOOP;
  RETURN;
END;    
$$ LANGUAGE plpgsql;

Or:

CREATE FUNCTION my_func() RETURNS SETOF RECORD AS $$
BEGIN
  RETURN QUERY VALUES (ROW('John','Smith')), (ROW('David','Miller'));
END;    
$$ LANGUAGE plpgsql;

But, calling my_func() got the error as shown below:

postgres=# SELECT my_func();
ERROR:  materialize mode required, but it is not allowed in this context

Actually, I tried both the examples above with enable_material=on and enable_material=off but the error was not solved:

postgres=# SELECT current_setting('enable_material');
 current_setting
-----------------
 on
(1 row)
postgres=# SELECT current_setting('enable_material');
 current_setting
-----------------
 off
(1 row)

So, how can I solved the error?

In addition, I could successfully call my_func() below which returns SETOF INT type with a RETURN NEXT or RETURN QUERY statement:

CREATE FUNCTION my_func() RETURNS SETOF INT AS $$
DECLARE 
  num INT;
BEGIN
  FOR num IN VALUES (1), (2), (3) LOOP
    RETURN NEXT num;
  END LOOP;
  RETURN;
END;    
$$ LANGUAGE plpgsql;

Or:

CREATE FUNCTION my_func() RETURNS SETOF INT AS $$
BEGIN
  RETURN QUERY VALUES (1), (2), (3);
END;    
$$ LANGUAGE plpgsql;
1

There are 1 answers

2
JGH On

You must define what a record is. Either do it in the function (return table, or with out parameters) or at call time

select * from my_func() as (first_name text, last_name text);