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

前端之家收集整理的这篇文章主要介绍了Clojure / postgresql:如何从Jdbc4Array结果中访问枚举值?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在 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接口访问数组的内容.我已经从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>
原文链接:https://www.f2er.com/postgresql/192099.html

猜你在找的Postgre SQL相关文章