title: Cast produces 'Returned type character varying does not match expected type character varying(8)'
body: <p>Yesterday we had a PostgreSQL database upgraded to version 9.1.3. We thought we had everything tested and ready, but there is a function we missed. It returns a table type like this:</p>
  
  <pre><code>CREATE OR REPLACE FUNCTION myfunc( patient_number varchar
      , tumor_number_param varchar, facility_number varchar)
    RETURNS SETOF patient_for_registrar
    LANGUAGE plpgsql
  AS
  $body$
  BEGIN
      RETURN QUERY            
  
      SELECT cast(nfa.patient_id_number as varchar),
      ...
  </code></pre>
  
  <p>I only only give the first column of the select because that is where the error happens. Before today this function ran fine, but now it gives this error: </p>
  
  <blockquote>
    <p>ERROR: structure of query does not match function result type<br>
    Detail: Returned type character varying does not match expected type
    character varying(8) in column 1.   Where: PL/pgSQL function
    "getwebregistrarpatient_withdeletes" line 3 at RETURN QUERY [SQL
    State=42804]</p>
  </blockquote>
  
  <p>The column <code>nfa.patient_id_number</code> is text and is being cast for the column <code>patient_id_number</code> in <code>patient_for_registrar</code> that is <code>varchar(8)</code>. After reading about this some I think the problem is because the column length isn't being specified when casting from text. But the problem is I've tried various combinations of substrings to fix this and none are solving the problem:</p>
  
  <pre><code>substring(cast(nfa.patient_id_number as varchar) from 1 for 8),
  
  cast(substring(nfa.patient_id_number from 1 for 8) as varchar),
  
  cast(substring(nfa.patient_id_number from 1 for 8) as varchar(8)),
  </code></pre>
  
  <p>Does anyone have any pointers?</p>