PostgreSQL raw query vs "Function returns TABLE" - insane difference in performance. Why?

Solution 1:

OK, that was easy. Turns out the database has to prepare the query plan before it knows about the parameters, which leads to bad results. The solution was to use plpgsql and to return QUERY EXECUTE. Now the performance is the same, as expected.

CREATE OR REPLACE FUNCTION GetMyReport(IN fromdate timestamp without time zone, IN todate timestamp without time zone)
  RETURNS TABLE(Name1 character varying, Name2 character varying) AS
$BODY$

BEGIN
RETURN QUERY EXECUTE'
select Column1 as Name1, Column2 as Name2
from sometable tbl
inner join ...
where ...
and ...
and $1 <= somedate
and $2 >= somedate
group by ...
order by ...;' USING $1, $2
END

$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 10
  ROWS 1000;