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.

2
  • 1
    See How can I get enum possible values in a MySQL database? 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. Commented Oct 11, 2013 at 17:31
  • I was afraid someone would say that Commented Oct 14, 2013 at 10:07

1 Answer 1

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))))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.