43

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?

1
  • Please specify the structure of enum_log_priority with all possible values Commented Sep 5, 2013 at 9:11

4 Answers 4

69

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

Sign up to request clarification or add additional context in comments.

Comments

6

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 |

Comments

6

Postgres supports also the cast function:

cast(priority AS enum_log_priority);

5 Comments

not working for me, same error
please post a question stating what you tried, which error you get and reference this answer
"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');
Not here. You need to write your own question.
you don't need the cast, your expression is not an enum, but a text
0

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

'critical'::"enum_log_priority" 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.