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?
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.
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.
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.
The Parse method in Enum converts the string representation of the name or numeric value of enum constants to an equivalent enumerated object.
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
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 |
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With