Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Great little snippet for using Postgres enum types inside
(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>
Copy link

hlship commented Aug 18, 2014

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.

Copy link

laczoka commented Dec 15, 2014

@hlship I get an error if I try to do
(! 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

Copy link

staypufd commented Apr 1, 2016

You have to cast the enum string.

Like this example where the gender is the enum type:

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:

(! dbspec :some_table {:enum_t_col "some_enum_val"::})

or close to that.

I got this from here:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment