Clojure / postgresql:如何从Jdbc4Array结果中访问枚举值?

时间:2011-08-30 03:00:58

标签: postgresql jdbc clojure

我在postgresql中有一个enum定义如下:

create type color as enum ('yellow', 'purple', 'white', 'black');

我可以像这样进入Jdbc4Array:

(def colors 
  ((first (sql/with-connection db/db 
    (sql/with-query-results res 
      ["select enum_range(null::color)"]
      (doall res)))) :enum_range))

这显示了这样一个对象:

#<Jdbc4Array {yellow,purple,white,black}>

但尝试通常的事情会引发异常:

(.getArray colors) => stream closed

所以我想我需要在连接关闭之前访问数组:

(def colors 
  ((sql/with-connection db/db 
    (sql/with-query-results res 
      ["select enum_range(null::color)"]
      (.getArray ((first (doall res)) :enum_range))))))

但是在这种情况下我得到了这个例外:

Method org.postgresql.jdbc4.Jdbc4Array.getArrayImpl(long,int,Map)
is not yet implemented.

险恶。我能在这做什么?

1 个答案:

答案 0 :(得分:1)

Postgresql Jdbc4Array.getArray()实现有一些非常奇怪的事情,我无法让它工作。但是,我在.getResultSet()方面取得了一些成功:

user=> (with-connection db (with-query-results rs ["select enum_range(null::color)"]     
           (.getResultSet (get (first(doall rs)) :enum_range))))
#<Jdbc4ResultSet org.postgresql.jdbc4.Jdbc4ResultSet@17cff66>

现在,可以通过标准ResultSet接口访问数组的内容。我已经从clojure.contrib.sql中复制了一些代码来执行此操作:

(defn resultset-seq
  [^java.sql.ResultSet rs]
  (let [rsmeta (. rs (getMetaData))
    idxs (range 1 (inc (. rsmeta (getColumnCount))))
    keys (map (fn [i] (. rsmeta (getColumnLabel i))) idxs)
    check-keys (or (apply distinct? keys)
               (throw (Exception. "ResultSet must have unique column labels")))
    row-struct (apply create-struct keys)
    row-values (fn [] (map (fn [^Integer i] (. rs (getObject i))) idxs))
    rows (fn thisfn []
           (when (. rs (next))
         (cons (apply struct row-struct (row-values)) (lazy-seq (thisfn)))))]
  (rows)))

给出(抱歉快速破解样式代码)

user=> (with-connection db 
         (with-query-results rs ["select enum_range(null::color)"] 
                            (get (first (resultset-seq 
                                           (.getResultSet (get (first(doall rs))
                                                              :enum_range))))
                                 "VALUE")))
#<PGobject yellow>