Skip to content

Instantly share code, notes, and snippets.

@avescodes
Created August 18, 2014 18:42
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save avescodes/e5d1acbb007f47655508 to your computer and use it in GitHub Desktop.
Save avescodes/e5d1acbb007f47655508 to your computer and use it in GitHub Desktop.
Great little snippet for using Postgres enum types inside clojure.java.jdbc
(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
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.

@laczoka
Copy link

laczoka commented Dec 15, 2014

@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

@staypufd
Copy link

staypufd commented Apr 1, 2016

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