PostgreSQL - 检查值是否等于枚举值

Udi*_*Udi 1 sql postgresql enums

我有以下枚举声明:
CREATE TYPE known_roles_list AS ENUM ('role1', 'role2')

当数据库执行某个查询时,我希望检查他们是否使用这些角色之一执行此操作,如果没有 - 让查询通过。就像是:

IF current_user NOT IN known_roles_list THEN
    RETURN OLD; 
END IF;
Run Code Online (Sandbox Code Playgroud)

显然,上面的代码不起作用(引发了运行时比较错误)。也没有unnest()-ing 枚举值并在其中搜索。

我如何进行搜索 - 并查看是否有任何枚举值与该值匹配current_user?(该current_user值只是一个示例 - 稍后,我需要将这些枚举值与行值进行比较,以列表示)

谢谢!

Łuk*_*ski 6

您可以使用enum_range(null::known_roles_list)获取枚举的数组列表元素,然后仅使用标准数组运算符。您需要将该数组强制转换为name[],否则它将无法比较nameknown_roles_list[]

postgres=> SELECT enum_range(null::known_roles_list);
  enum_range
---------------
 {role1,role2}

postgres=> SELECT current_user;
 current_user
--------------
 lkaminski

postgres=> SELECT current_user = any(enum_range(null::known_roles_list)::name[]);
 ?column?
----------
 f

postgres=> SELECT 'role2'::name = any(enum_range(null::known_roles_list)::name[]);
 ?column?
----------
 t
Run Code Online (Sandbox Code Playgroud)

枚举函数:https : //www.postgresql.org/docs/current/static/functions-enum.html

任何/一些:https : //www.postgresql.org/docs/current/static/functions-comparisons.html#id-1.5.8.28.16