我在PostgreSQL中定义了一个枚举,如下所示:
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.
险恶。我在这里可以做什么?
最佳答案
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接口(interface)访问数组的内容。我已经从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>