Thread: problem with polymorphic functions and implicit casting

problem with polymorphic functions and implicit casting

From
Pavel Stehule
Date:
I found following problem:

postgres=# create or replace function sum_items(anyarray) returns
anyelement as $$ select sum($1[i]) from
generate_series(array_lower($1,1), array_upper($1,1)) g(i)$$ language
sql immutable;
CREATE FUNCTION
Time: 1,983 ms
postgres=# select sum_items(array[1,2,3]);
ERROR:  return type mismatch in function declared to return integer
DETAIL:  Actual return type is bigint.
CONTEXT:  SQL function "sum_items" during startup
postgres=#

so in this case we need explicit casting to result type - like

create or replace function sum_items(anyarray) returns anyelement as $$ select sum($1[i])::anyelement -- <<<<<<    from
generate_series(array_lower($1,1),array_upper($1,1)) g(i)
 
$$ language sql immutable;

or some flag that ensure explicit casting.

Regards
Pavel Stehule