2

I am trying to write a simple application which reads the a database and produces a set of functions with which to access it; so far so good. Now, what I have come across is that some of the columns in my database are defined as MySQL enum types (e.g. ENUM('red','green','violet')) and I would like to validate the stuff I send to the database rather than receive an error from the driver when an unacceptable value is given, so I was wondering if there is a way to retrieve the possible values for the enum from within clojure.

I am using [clojure.java.jdbc "0.3.0-alpha5"] and [mysql/mysql-connector-java "5.1.25"]. In order to get the metadata for the table I am currently using java.sql.DatabaseMetaData, but trying .getPseudoColumns just gives me nil every time.

dsm
  • 10,263
  • 1
  • 38
  • 72
  • 1
    See [How can I get enum possible values in a MySQL database?](http://stackoverflow.com/q/2350052) It's not a perfect dupe, because that question is tagged PHP (in which most answers have been provided), but it should be sufficient to show the solution. – eggyal Oct 11 '13 at 17:31
  • I was afraid someone would say that – dsm Oct 14 '13 at 10:07

1 Answers1

1

Turns out there is no straight forward way to do this using libraries. My own solution is:

(defn- parse-enum
  "Parses an enum string and returns it's components"
  [enum-str]
  ; "enum('temp','active','canceled','deleted')"
  (map (comp keyword #(.replace % "'" ""))
       (-> enum-str
           (.replaceFirst "^[^\\(]+\\(([^\\)]+)\\)$" "$1")
           (.split "'?,'?"))))

(defn get-enum-value 
  "Returns the values for an enum in a table.column"
  [table column]
  (jdbc/with-connection db
    (jdbc/with-query-results rs
      [(str "show columns from " table " where field = ?") column]
      ((comp set parse-enum :type first) rs))))
dsm
  • 10,263
  • 1
  • 38
  • 72