Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast string value to enum

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?

like image 542
Bart Friederichs Avatar asked Sep 05 '13 08:09

Bart Friederichs


People also ask

Can you cast a string to an enum?

IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.

How do you create an enum from a string?

You can create Enum from String by using Enum. valueOf() method. valueOf() is a static method that is added on every Enum class during compile-time and it's implicitly available to all Enum along with values(), name(), and cardinal() methods.

Can we assign string value to enum in C#?

You can even assign different values to each member. The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.

What is enum parse in C#?

The Parse method in Enum converts the string representation of the name or numeric value of enum constants to an equivalent enumerated object.


2 Answers

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

like image 192
Rakesh Soni Avatar answered Sep 18 '22 13:09

Rakesh Soni


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 |

like image 37
Roman Pekar Avatar answered Sep 19 '22 13:09

Roman Pekar