How to cast string value to enum
Asked Answered
E

4

42

I have a table with an enum type in it, and I created a function to add data to that table. I want that function to be generous in what to accept, so I take a text as the enum type and want to cast it later.

This is the enum:

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

And this is the function:

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';

I know this doesn't work:

ERROR: column "priority" is of type enum_log_priority but expression is of type text

but how can I do this?

Evergreen answered 5/9, 2013 at 8:52 Comment(1)
Please specify the structure of enum_log_priority with all possible valuesLucey
L
66

Use syntax like below during insertion

'critical'::enum_log_priority 

Please see some link as well

http://www.postgresql.org/docs/9.1/static/datatype-enum.html

Inserting into custom SQL types with prepared statements in java

java enum and postgresql enum

Lucey answered 5/9, 2013 at 9:17 Comment(0)
C
6

Postgres supports also the cast function:

cast(priority AS enum_log_priority);
Cath answered 6/12, 2021 at 14:59 Comment(5)
not working for me, same errorTaverner
please post a question stating what you tried, which error you get and reference this answerCath
"ERROR: column "type" is of type geotargettypenum but expression is of type text" with cast(type AS geotargettypeenum); ENUM is create type geotargettypeenum as enum ('ADMIN_ZONE', 'BUFFER', 'INSEE_CODE', 'IRIS_CODE', 'POLYGON', 'POSTAL_CODE');Taverner
Not here. You need to write your own question.Cath
you don't need the cast, your expression is not an enum, but a textCath
A
5

change your function like this:

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 demo |

Autograph answered 5/9, 2013 at 12:6 Comment(0)
W
0

Consider that sometimes (for example in Prisma raw queries) you need to put the enum type inside quotations.

'critical'::"enum_log_priority" 
Windpollinated answered 6/1, 2023 at 21:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.