title: Return dynamic table with unknown columns from PL/pgSQL function
body: <p>I need to create a function that checks on a given table if the <code>infowindow</code> field exists. If it exists the function must return <code>select * from table</code> but if it does not, it must return an additional <code>id</code> field:</p>
  
  <pre><code>CREATE OR REPLACE FUNCTION getxo_ocx_cincu_preparar_infowindow(
                                                guretabla character varying)
    RETURNS TABLE AS
  $BODY$ 
  DECLARE
      tabla ALIAS FOR $1;
  
  BEGIN
  
  IF  EXISTS (SELECT 1
     FROM   pg_namespace n
     JOIN   pg_class     c ON c.relnamespace = n.oid
     JOIN   pg_attribute a ON a.attrelid = c.oid 
     WHERE  n.nspname = current_schema()  -- default to current schema
     AND    c.relname = tabla
     AND    a.attname = 'infowindow'
     AND    NOT a.attisdropped)
  THEN
      RETURN QUERY EXECUTE 'SELECT * from ' ||tabla ;
  ELSE
      RETURN QUERY EXECUTE 'SELECT *, ID:' || id::text ||' as infowindow
                                     from ' ||tabla ;
  END IF;
  
  END;
  $BODY$
    LANGUAGE plpgsql VOLATILE;
  </code></pre>
  
  <p>If I use <code>RETURNS SETOF RECORDS</code>, when I do the select to the function I need to specify the columns, which I don't know. And if I use <code>RETURNS TABLE</code> I need to specify the fields too, so I don't know how to do it.</p>