Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify a generic type for a function parameter

Tags:

postgresql

Is it possible to define a function that takes a parameter of a generic type in Postgresql? So for example if I wanted to define a function where the argument could be either numeric or character varying:

CREATE OR REPLACE FUNCTION toStr(col ??Generic Type??)
  RETURNS character varying AS
$BODY$
select 
case when pg_typeof(col) = 'character varying'::regtype then col::'character varying'
case when pg_typeof(col) = 'numeric'::regtype then to_char(col::numeric, '999')
  else 'Unsupported type'
$BODY$

So if this is possible what would my ??Generic Type?? be?

like image 228
user79074 Avatar asked Mar 25 '16 14:03

user79074


1 Answers

You can use the anyelement pseudo type which accepts any data type;

CREATE OR REPLACE FUNCTION toStr(col anyelement)
  RETURNS character varying 
AS $$
select 
case when pg_typeof(col) = 'character varying'::regtype then (col::character varying)
     when pg_typeof(col) = 'numeric'::regtype then to_char(col::numeric, '999')
  else 'Unsupported type' end
$$
LANGUAGE sql;

An SQLfiddle showing it in action.

like image 69
Joachim Isaksson Avatar answered Sep 23 '22 08:09

Joachim Isaksson