返回随机枚举的postgres函数

时间:2019-07-15 16:43:36

标签: postgresql plpgsql

我想编写一个返回随机枚举值的函数random_enum(enum_name)

我已停止使用此变体

create type  myenum
as enum (
   'one',
   'two',
   'three',
   'four'
);


create or replace function random_enum(relation_name anyelement) returns anyenum as $$
begin
  return execute format(
    $sql$
      select unnest(enum_range(NULL::%1$I)) ORDER BY random() LIMIT 1;
    $sql$,
    pg_typeof(relation_name)
  );
end;
$$ language plpgsql;

select random_enum(null::myenum)

you can try it here

但由于

而无法使用
ERROR:  syntax error at or near "("
LINE 12:   return execute format(

2 个答案:

答案 0 :(得分:1)

使用out参数的方式:

create or replace function random_enum(relation_name anyelement, out result anyenum) 
as $$
begin
  execute format(
    $sql$
      select elem 
      from unnest(enum_range(null::%1$I)) as elem
      order by random() 
      limit 1;
    $sql$,
    pg_typeof(relation_name)
  ) into result;
end;
$$ language plpgsql;

db<>fiddle.

答案 1 :(得分:1)

不带OUT参数并定义为SQL函数的替代项。

create or replace function random_enum(
                  relation_name_in  text
                ) 
          returns text 
         language sql strict
as $$
    select e.enumlabel::text
      from pg_type t 
      join pg_enum e on t.oid = e.enumtypid  
      join pg_catalog.pg_namespace n on n.oid = t.typnamespace
     where t.typname = lower(relation_name_in)
     order by random()
     limit 1;
$$ ;

-- test 
select soq.random_enum('myenum');