2

I tried to define a PostgreSQL function that returns a complex type from a query via:

CREATE TYPE last_contract AS (
    contract_id bigint,
    contract_date timestamp
);

and

CREATE OR REPLACE FUNCTION delivery_last_contract(delivery bigint) RETURNS last_contract AS $func$
DECLARE ret last_contract;
BEGIN

    SELECT DISTINCT ON (tdf.delivery_id) ROW(tcf.contract_id, tcf.date)::last_contract INTO ret
        FROM task_delivery_fetch tdf 
        INNER JOIN task_contract_fetch tcf ON tcf.fetch_id = tdf.fetch_id 
        WHERE tdf.delivery_id = delivery
        ORDER BY tdf.delivery_id, tcf.contract_id DESC
        LIMIT 1;


    RETURN ret;

END;
$func$ LANGUAGE plpgsql;

sadly, all I get is an error:

SELECT delivery_last_contract(12197);
ERROR:  invalid input syntax for integer: "(13605,"2016-12-06 00:00:00+01")"
CONTEXT:  PL/pgSQL function delivery_last_contract(bigint) line 5 at SQL statement

Isn't there a way to actually return a single complex type returned from a query?

1
  • 3
    Could you please add the actual error message? One or two lines are missing. In any case, DISTINCT ON feels unnecessary with ORDER BY ... LIMIT 1. Commented Feb 17, 2017 at 14:32

1 Answer 1

1
CREATE OR REPLACE FUNCTION delivery_last_contract(delivery bigint) 
                   RETURNS last_contract AS $func$
  DECLARE ret last_contract;
  BEGIN
    SELECT tcf.contract_id, tcf.date
      INTO ret
      FROM task_delivery_fetch tdf 
      INNER JOIN task_contract_fetch tcf ON tcf.fetch_id = tdf.fetch_id 
     WHERE tdf.delivery_id = delivery
     ORDER BY tdf.delivery_id, tcf.contract_id DESC
     LIMIT 1;
    RETURN ret;    
  END;
$func$ LANGUAGE plpgsql;

works. Simpler is better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.