PostgreSQL – How to Pass a Type as an Argument in Functions

plpgsqlpostgresql

I am using this query to list the values that are part of an enum:

SELECT unnest(enum_range(null::my_enum_name)) AS enum_values;

It works.

I am trying to make it more reusable by wrapping it in a function that takes the name of the enum (my_enum_name in the example above) as a parameter, but I can't find a lot of documentation on this.

Is it possible?

Best Answer

It is possible:

create type mood as enum ('sad','ok', 'happy');
CREATE TYPE

create function f(p_typname text) returns setof text 
as $$
begin
   return query execute 
      format(
         'SELECT unnest(enum_range(null:: %s))::text AS enum_values',
         p_typname
      );
end;
$$
language plpgsql;
CREATE FUNCTION

select * from f('mood');
   f   
-------
 sad
 ok
 happy
(3 rows)