如何将字符串值转换为枚举类型

38

我有一张表格里面有一个枚举类型,我创建了一个添加数据到该表的函数。我希望这个函数在接收输入时能够更加宽容,因此我把文本作为枚举类型的输入,并想稍后再进行转换。

这是枚举:

CREATE TYPE public.enum_log_priority AS ENUM (
    'critical','error','warning','notice','debug'
);

这就是该函数:

CREATE OR REPLACE FUNCTION public.log_write(
    _message text,
    _priority text
) RETURNS integer AS
$body$
BEGIN
    _priority = lower(_priority);
    INSERT INTO log (message, priority) VALUES (_message, _priority);

    RETURN 0;
END
$body$
LANGUAGE 'plpgsql';

我知道这行代码不能正常工作:

ERROR: 列 "priority" 的类型是 enum_log_priority,但表达式的类型是 text

但我应该怎么做呢?


请指定enum_log_priority的结构以及所有可能的值。 - Rakesh Soni
4个回答

61

5
Postgres也支持转换函数:
cast(priority AS enum_log_priority);

不适用于我,同样的错误。 - mik3fly-4steri5k
1
请发一个问题,说明你尝试了什么,遇到了什么错误,并引用此答案。 - Michele Dorigatti
错误:列"type"的类型为geotargettypenum,但表达式的类型为文本 使用cast(type AS geotargettypeenum)进行转换;ENUM是创建类型geotargettypeenum作为枚举('ADMIN_ZONE', 'BUFFER', 'INSEE_CODE', 'IRIS_CODE', 'POLYGON', 'POSTAL_CODE'); - mik3fly-4steri5k
1
不是这里。您需要自己编写问题。 - Michele Dorigatti
你不需要进行强制类型转换,你的表达式不是枚举类型,而是文本。 - Michele Dorigatti

5
将你的函数改成如下形式:
CREATE OR REPLACE FUNCTION public.log_write(
    _message text,
    _priority text
) RETURNS integer AS
$body$
BEGIN
    _priority = lower(_priority);
    INSERT INTO log (message, priority) VALUES (_message, _priority::enum_log_priority);

    RETURN 0;
END
$body$
LANGUAGE 'plpgsql';

| SQL Fiddle 示例 |


0

有时候(例如在 Prisma 原始查询中),您需要将枚举类型放在引号内。

'critical'::"enum_log_priority" 

这实际上就是被接受的答案。 - Bart Friederichs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接