Great little snippet for using Postgres enum types inside clojure.java.jdbc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn keyword->pg-enum | |
"Convert a keyword value into an enum-compatible object." | |
[enum-type kw] | |
(doto (org.postgresql.util.PGobject.) | |
(.setType enum-type) | |
(.setValue (name kw)))) | |
(def ->status | |
"Convert a keyword status into a something_status enum object" | |
(partial keyword->pg-enum "something_status")) | |
;; Use it: | |
(->status :accepted) | |
; -> #<PGobject accepted> |
@hlship I get an error if I try to do
(clojure.java.jdbc/insert! dbspec :some_table {:enum_t_col "some_enum_val"})
ERROR: column "enum_t_col" is of type enum_event_type but expression
is of type character varying Hint: You will need to rewrite or cast
the expression
You have to cast the enum string.
Like this example where the gender is the enum type:
'F'::gender
or
'M'::gender
This works because all PostgreSQL types have a input method that takes a text representation and converts that to the internal form.
So your insert would be:
(clojure.java.jdbc/insert! dbspec :some_table {:enum_t_col "some_enum_val"::})
or close to that.
I got this from here: http://stackoverflow.com/questions/16492370/java-enum-and-postgresql-enum
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is there an advantage to this over just using (:accepted name)? Postgres seems quite happy to convert that string back into the numeric value stored in the table automatically.