title: set-valued function called in context that cannot accept a set
body: <p>I am receiving the error:</p>
  
  <blockquote>
    <p>set-valued function called in context that cannot accept a set</p>
  </blockquote>
  
  <p>when executing this function at <code>RETURN QUERY EXECUTE</code> line:</p>
  
  <pre><code>PLSQL $ cat lookup_email.pl 
  CREATE OR REPLACE FUNCTION app.lookup_email(ident_id bigint,sess bigint,company_id bigint,email varchar)
  RETURNS SETOF RECORD as $$
  DECLARE
      rec RECORD;
      comp_id bigint;
      server_session bigint;
      schema_name varchar;
      query varchar;
  BEGIN
      schema_name:='comp' || company_id;
      select app.session.session into server_session from app.session where app.session.identity_id=ident_id and app.session.session=sess;
      IF FOUND
      THEN
          BEGIN
              query:='SELECT i.email,u.user_id FROM app.identity as i,' || schema_name || '.uzer as u WHERE i.email like ''%' || email || '%'' and i.identity_id=u.identity_id';
              RAISE NOTICE 'executing: %',query;
              RETURN QUERY EXECUTE query;
              RETURN;
          EXCEPTION
              WHEN OTHERS THEN
                  RAISE NOTICE ' query error (%)',SQLERRM;
  
          END;
      END IF;
  END;
  $$ LANGUAGE plpgsql;
  </code></pre>
  
  <p>This is the ouput from psql:</p>
  
  <pre><code>dev=&gt; select app.lookup_email(4,730035455897450,6,'u');
  NOTICE:  executing: SELECT i.email,u.user_id FROM app.identity as i,comp6.uzer as u WHERE i.email like '%u%' and i.identity_id=u.identity_id
  NOTICE:   query error (set-valued function called in context that cannot accept a set)
   lookup_email 
  --------------
  (0 rows)
  </code></pre>
  
  <p>I know the query doesn't contain any error, because it works in another psql session:</p>
  
  <pre><code>dev=&gt; SELECT i.email,u.user_id FROM app.identity as i,comp6.uzer as u WHERE i.email like '%u%' and i.identity_id=u.identity_id;
       email      | user_id 
  ----------------+---------
   hola@mundo.com |       1
  (1 row)
  </code></pre>
  
  <p>So why is Postgres complaining if I declared my function being as <code>RETURNS SETOF RECORD</code>? Where is my error?</p>